• Advertisement
Sign in to follow this  

OpenGL Graphical consistency problems when resizing

This topic is 4832 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I've been working on OpenGL and DirectDraw for a little while now, but I recently started doing the DirectX tutorials. I am currently working on Tut 5. Everything looks great with the preinitialized window resolution, but if you dare touch it, then it will look really ugly. I think I need to call something on the WM_SIZE msg, but then again other programs look fine even when they don't call that. What would an experienced D3D programmer tell me ? TIA

Share this post


Link to post
Share on other sites
Advertisement
Well I believe that if you want your program to be resizeable then when WM_SIZE is generated you need to adjust the projection or orthographic matrix depending on the new resolution.

If you want the border to be static(non-resizeable) create the window with WS_STATICEDGE(well I don't remember exactly what it's called but it's something like that).

Also I find that when the window is at a non 4:3 ratio(400x300,640x480,800x600,etc..) resolution the FPS drops and the scene looks like crap so I just make my apps non-resizable.

Edit: OK to create a non-resizeable window use CreateWindowEx and use WS_EX_STATICEDGE as the first parameter.

Share this post


Link to post
Share on other sites
If you're talking about your screen getting pixelly/blurry, then it's because you haven't resized the backbuffer.

To do so, you need to change the BackBufferWidth/Height in your presentParameters, the call pDevice->Reset(&presentParameters).

This can be a bit of a pain, because you need to release all non-managed resources (Like the backbuffer, any fonts and any textures created without D3DPOOL_MANAGED), then recreate them after the reset. You also need to set up all of your render-states again, and all your matrix settings.

There might be a better way of doing this, but this is the way I'm doing it at the moment.

Share this post


Link to post
Share on other sites
Thanks for the responses
I see that it's not that easy :(.

I have adjusted the width and height parameters in the d3dpp.

My question now is :
Would I call reset in a WM_SIZE msg from windows? Or is there a better way of doing this within the render scene(as I've seen other programs do invisibly to my knowledge)?

Wherever the code goes, I'm assuming it would look like this :

RECT box ;
GetClientRect(hWnd, &box) ;
d3dpp.BackBufferWidth = box.right ;
d3dpp.BackBufferHeight = box.bottom ;
g_pd3dDevice->Reset(&d3dpp) ;

I can't think of a better way. I gotta read up on this stuff. The SDK doesn't cover this. =(

Share this post


Link to post
Share on other sites
That's pretty much it! Just dont forget to call Release() on any fonts, additional swap chains or non-managed surfaces (If you dont have any textures, then that will probably just be your backbuffer) and then re-create them afterwards.


// Set the screen 'present parameters'
m_presentParameters.BackBufferWidth = m_windowWidth;
m_presentParameters.BackBufferHeight = m_windowHeight;

// Release all non-managed D3D resources
m_defaultFont->Release();
m_BackSurf->Release();

// Reset the device with the new present parameters
if(FAILED(m_pDevice->Reset(&m_presentParameters)))
throw "Error resetting D3D9 device!";

// Reaquire back buffer
m_pDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &m_BackSurf);

// Recreate default font
D3DXCreateFont(m_pDevice, (HFONT)GetStockObject(SYSTEM_FIXED_FONT), &m_defaultFont);

// Set any required renderstates below...
m_pDevice->SetRenderState( D3DRS_LIGHTING, TRUE);
m_pDevice->SetRenderState( D3DRS_ZENABLE, D3DZB_TRUE);
m_pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW);

SetPerspectiveMode(m_windowWidth, m_windowHeight, m_fov);



Note that 'SetPerspectiveMode' just recreates the projection matrix using D3DXMatrixPerspectiveFovLH(). This may seem like a slow procedure, but remember that your user wont be sizing the window every frame.

Good luck!

Share this post


Link to post
Share on other sites
I understand what you're saying, but I'm not sure if I'm implementing it.


//------------------------------------------------------------------
// Textures: renders a cylinder and wraps a texture around it
//------------------------------------------------------------------


#include <windows.h>
#include <mmsystem.h>
#include <d3dx9.h>
#include "resource.h"

//#define SHOW_HOW_TO_USE_TCI

// Global variables
LPDIRECT3D9 g_pD3D = NULL ; // used create the D3DDevice
LPDIRECT3DDEVICE9 g_pd3dDevice = NULL ; // our rendering device
LPDIRECT3DVERTEXBUFFER9 g_pVB = NULL ; // buffer to hold vertices
LPDIRECT3DTEXTURE9 g_pTexture = NULL ; // Our texture

// structure for custom vertex type. Normal added(color is provided by the material)
struct CUSTOMVERTEX
{
D3DXVECTOR3 position ; // the 3D position for the vertex
D3DCOLOR color ; // the surface normal for the vertex
#ifndef SHOW_HOW_TO_USE_TCI
FLOAT tu, tv ; // The texture coordinates
#endif
} ;

// custom FVF, describes custom vertex structure
#ifdef SHOW_HOW_TO_USE_TCI
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ | D3DFVF_DIFFUSE)
#else
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1)
#endif

HRESULT InitD3D(HWND hWnd);
HRESULT InitGeometry();
VOID SetupMatrices();
VOID Render();
VOID Cleanup();
LRESULT WINAPI MsgProc(HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam);

HWND g_hWnd ;
D3DPRESENT_PARAMETERS d3dpp ;
int g_x = 640 ;
int g_y = 480 ;

INT WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lPCmdLine,int nCmdShow)
{
// register the window class
WNDCLASSEX wc = {sizeof(WNDCLASSEX), CS_CLASSDC, MsgProc, 0L, 0L, GetModuleHandle(NULL),
LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1)), NULL, NULL, NULL, "D3D Tutorial", NULL} ;
RegisterClassEx(&wc) ;

// create the application's window
HWND hWnd=CreateWindow("D3D Tutorial", "D3D Tutorial 05 : Textures", WS_OVERLAPPEDWINDOW,
100, 100, g_x, g_y, GetDesktopWindow(), NULL, wc.hInstance, NULL) ;

g_hWnd = hWnd ;

// initialize Direct3D
if(SUCCEEDED(InitD3D(hWnd)))
{
// create the geometry
if(SUCCEEDED(InitGeometry()))
{
// show the window
ShowWindow(hWnd, SW_SHOWDEFAULT) ;
UpdateWindow(hWnd) ;

// enter the message loop
MSG msg ;
ZeroMemory(&msg, sizeof(msg)) ;
while(msg.message != WM_QUIT)
{
if(PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
{
TranslateMessage(&msg) ;
DispatchMessage(&msg) ;
}
else
Render() ;
}
}
}

UnregisterClass("D3D Tutorial", wc.hInstance) ;
return 0 ;
}
HRESULT InitD3D(HWND hWnd)
{
// create the D3D object
if((g_pD3D = Direct3DCreate9(D3D_SDK_VERSION)) == NULL)
return E_FAIL ;

// set up the structure used to create the D3DDevice. Since we are now
// using more complex geometry, we will create a device with a zbuffer.
ZeroMemory(&d3dpp, sizeof(d3dpp)) ;
d3dpp.Windowed = TRUE ;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD ;
d3dpp.BackBufferWidth = g_x ;
d3dpp.BackBufferHeight = g_y ;
d3dpp.BackBufferFormat = D3DFMT_UNKNOWN ;
d3dpp.EnableAutoDepthStencil = TRUE ;
d3dpp.AutoDepthStencilFormat = D3DFMT_D16 ;

// create the D3DDevice
if(FAILED(g_pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
D3DCREATE_HARDWARE_VERTEXPROCESSING, &d3dpp, &g_pd3dDevice)))
return E_FAIL ;

// turn of culling
g_pd3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE) ;

// turn off D3D lighting
g_pd3dDevice->SetRenderState(D3DRS_LIGHTING, FALSE) ;

// turn on the zbuffer
g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, TRUE) ;

return S_OK ;
}
HRESULT InitGeometry()
{
// use D3DX to create a texture from a file based image
if(FAILED(D3DXCreateTextureFromFile(g_pd3dDevice, "hovigTex.bmp", &g_pTexture)))
return E_FAIL ;
// create the vertex buffer
if(FAILED(g_pd3dDevice->CreateVertexBuffer(100 * sizeof(CUSTOMVERTEX), 0,
D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVB, NULL)))
return E_FAIL ;

// fill the vertex buffer. We are algorithmically generating a cylinder
// here, including the normals, which are used for lighting
CUSTOMVERTEX* pVertices ;
if(FAILED(g_pVB->Lock(0, 0, (void**)&pVertices, 0)))
return E_FAIL ;
for(DWORD i = 0; i < 50; i++)
{
FLOAT theta = (2 * D3DX_PI * i) / 49 ;
pVertices[2 * i + 0].position = D3DXVECTOR3(sinf(theta), -1.0f, cosf(theta)) ;
pVertices[2 * i + 0].color = 0xffffffff ;
#ifndef SHOW_HOW_TO_USE_TCI
pVertices[2 * i + 0].tu = FLOAT(i) / (49) ;
pVertices[2 * i + 0].tv = 1.0f ;
#endif
pVertices[2 * i + 1].position = D3DXVECTOR3(sinf(theta), 1.0f, cosf(theta)) ;
pVertices[2 * i + 1].color = 0xff808080 ;
#ifndef SHOW_HOW_TO_USE_TCI
pVertices[2 * i + 1].tu = FLOAT(i) / (49) ;
pVertices[2 * i + 1].tv = 0.0f ;
#endif
}
g_pVB->Unlock() ;

return S_OK ;
}
VOID SetupMatrices()
{
// for our world matrix, we will just leave it as the identity
D3DXMATRIXA16 matWorld ;
D3DXMatrixIdentity(&matWorld) ;
D3DXMatrixRotationX(&matWorld, timeGetTime() / 1000.0f) ;
g_pd3dDevice->SetTransform(D3DTS_WORLD, &matWorld) ;

// set up our view matrix. A view matrix can be defined given an eye point,
// a point to lookat, and a direction for which way is up. Here, we set the
// eye five units back along the z-axis and up three units, look at the
// origin, and define "up" to be in the y-direction.
D3DXVECTOR3 vEyePt(0.0f, 3.0f, -5.0f) ;
D3DXVECTOR3 vLookatPt(0.0f, 0.0f, 0.0f) ;
D3DXVECTOR3 vUpVec(0.0f, 1.0f, 0.0f) ;
D3DXMATRIXA16 matView ;
D3DXMatrixLookAtLH(&matView, &vEyePt, &vLookatPt, &vUpVec) ;
g_pd3dDevice->SetTransform(D3DTS_VIEW, &matView) ;

// for the projection matrix, we set up a perspective transform (which
// transforms geometry from 3D view space to 2D viewport space, with a
// perspective device making objects smaller in the distance). To build
// a perspective transform, we need the field of view (1/4 pi is common),
// the aspect ratio, and the near and far clipping planes (which define at
// what distances geometry should no longer be rendered).
D3DXMATRIXA16 matProj ;
D3DXMatrixPerspectiveFovLH(&matProj, D3DX_PI / 4, 1.0f, 1.0f, 100.0f) ;
g_pd3dDevice->SetTransform(D3DTS_PROJECTION, &matProj) ;
}
VOID Render()
{
// clear the backbuffer and the zbuffer to a black color
g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER,
D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0) ;

// begin the scene
if(SUCCEEDED(g_pd3dDevice->BeginScene()))
{
// setup the world, view, and projection matrices
SetupMatrices() ;

// Setup our texture. Using textures introduces the texture state states
// which govern how textures get blended together (in the case of multiple
// textures) and lighting information. In this case, we are modulating
// (blending) our texture with the diffuse color of the vertices.
g_pd3dDevice->SetTexture(0, g_pTexture) ;
g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE) ;
g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE) ;
g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE) ;
g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_DISABLE) ;

#ifdef SHOW_HOW_TO_USE_TCI
// Note : to use D3D texture coordinate generation, use teh stage state
// D3DTSS_TEXCOORDINDEX, as shown below. In this example, we are using
// the position of the vertex in camera space to generate texture
// coordinates. The tex coord index (TCI) parameters are passed into a
// texture transform, which is a 4x4 matrix which trasnforms the x, y, z
// TCI coordinates into tu, tv texture coordinates.

// In this example, the texture matrix is setup to
// transform the texture from (-1, +1) position coordinates to (0, 1)
// texture coordinate space:
// tu = 0.5 * x + 0.5
// tv = -0.5 * y + 0.5
D3DXMATRIXA16 mat ;

mat._11 = 0.25f ; mat._12 = 0.00f ; mat._13 = 0.00f ; mat._14 = 0.00f ;
mat._21 = 0.00f ; mat._22 = -0.25f ; mat._23 = 0.00f ; mat._24 = 0.00f ;
mat._31 = 0.00f ; mat._32 = 0.00f ; mat._33 = 1.00f ; mat._34 = 0.00f ;
mat._41 = 0.50f ; mat._42 = 0.50f ; mat._43 = 0.00f ; mat._44 = 1.00f ;

g_pd3dDevice->SetTransform(D3DTS_TEXTURE0, &mat) ;
g_pd3dDevice->SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2) ;
g_pd3dDevice->SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEPOSITION) ;
#endif

// render the vertex buffer contents
g_pd3dDevice->SetStreamSource(0, g_pVB, 0, sizeof(CUSTOMVERTEX)) ;
g_pd3dDevice->SetFVF(D3DFVF_CUSTOMVERTEX) ;
g_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 98) ;

// end the scene
g_pd3dDevice->EndScene() ;
}

// present the backbuffer contents to the display
g_pd3dDevice->Present(NULL, NULL, NULL, NULL) ;
}
VOID Cleanup()
{
if(g_pTexture != NULL)
g_pTexture->Release() ;

if(g_pVB != NULL)
g_pVB->Release() ;

if(g_pd3dDevice != NULL)
g_pd3dDevice->Release() ;

if(g_pD3D != NULL)
g_pD3D->Release() ;
}
LRESULT WINAPI MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
D3DXMATRIXA16 matProj ;
RECT rect ;

switch(msg)
{
case WM_SIZE :
GetClientRect(hWnd, &rect) ;
g_x = rect.right ;
g_y = rect.bottom ;

d3dpp.BackBufferWidth = g_x ;
d3dpp.BackBufferHeight = g_y ;
g_pd3dDevice->Reset(&d3dpp) ;
g_pd3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE) ;

// turn off D3D lighting
g_pd3dDevice->SetRenderState(D3DRS_LIGHTING, FALSE) ;

// turn on the zbuffer
g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, TRUE) ;

D3DXMatrixPerspectiveFovLH(&matProj, D3DX_PI / 4, 1.0f, 1.0f, 100.0f) ;
g_pd3dDevice->SetTransform(D3DTS_PROJECTION, &matProj) ;

return 0 ;
case WM_DESTROY :
Cleanup() ;
PostQuitMessage(0) ;
return 0 ;
}

return DefWindowProc(hWnd, msg, wParam, lParam) ;
}



[Edited by - Coder on October 24, 2004 12:26:49 PM]

Share this post


Link to post
Share on other sites
You might want to place some source /source tags around that code to make it easier to read. Here's some ideas, maybe they'll be useful.

Instead of using the WM_SIZE message in the WndProc or WinMain functions, I'd suggest creation a function similar to ProcessMessage(MSG Message) in your game engine. You'll need it for a lot more than just WM_SIZE eventually. You can then just put a call to this function in the WndProc message handler, passing the message to your game engine first.

Now, we're in the game engine ProcessMessage function and we case out WM_SIZE. Here's a code snipet from my engine.


ProcessMessage(MSG fpMessage)
{
...
case WM_SIZE:
if (pGraphicsManager && (fpMessage.wParam == SIZE_MAXIMIZED) &&
bGoFullScreenOnMaximize)
pGraphicsManager->SetFullScreen(true);
else
if (pGraphicsManager)
pGraphicsManager->ResizeWindow();
}

void ResizeWindow(void)
{
RECT rClientArea;

// hWindowHandle is passed in to the creation of the Graphics Manager
GetClientRect(hWindowHandle, &rClientArea);
uiWidth = rClientArea.right - rClientArea.left;
uiHeight = rClientArea.bottom - rClientArea.top;

ppPresentParameters.BackBufferWidth = uiWidth;
ppPresentParameters.BackBufferHeight = uiHeight;
pInterface->GetAdapterDisplayMode(uiCurrentAdapter, &dmDisplayMode);
pViewManager->GetActivePerspective()->SetFovLH(PI/4*((float)uiHeight/dmDisplayMode.Height), ((float)uiWidth)/uiHeight,
1.0f, 1000.0f);

BeginReset();
}




If the max button is pressed (which sends a WM_SIZE event) and if the game engine is set up to toggle to full screen on a maximize, then we go to full screen. Otherwise, we resize the window.

When resizing, I get the new size of the window, then store the values, replace the values in the backbuffer, and change the FOV. My calculation here of PI/4*((float)...) is so that my FOV will change with the screen resolution based on the max resolution currently available. If the window gets bigger, changing the FOV to be proportional allows the view to "spread out" as the window gets wider, so you can see more around. This may not be what you want to do. Finally, I call BeginReset which sets in motion a destruction of all objects that I manage. It also sets a flag "bResetting" so that the next time I enter the Render loop, I check this flag, and if it's set I call EndReset, and otherwise I render as usual. See the code below:


bool cGraphicsManager::EndReset(void)
{
bool ReturnVal = true;

// Attempt to reset the Device
if (pDevice->TestCooperativeLevel() == D3D_OK)
pDevice->Reset(&ppPresentParameters);
else
return false;

// End the resets
pMeshManager->EndReset();
pTextureManager->EndReset();
pCursorManager->EndReset();
...

if(ppPresentParameters.Windowed)
{
RECT rc;
const DWORD dwStyle = WS_CAPTION | WS_MINIMIZEBOX | WS_SYSMENU;

rc.left = rc.top = 0;
rc.right = uiWidth;
rc.bottom = uiHeight;
rc.right -= rc.left;
rc.bottom -= rc.top;
DWORD XWidth = GetSystemMetrics(SM_CXSCREEN);
DWORD YHeight = GetSystemMetrics(SM_CYSCREEN);
ShowCursor(TRUE);
}

// Change state to Normal Render
if (ReturnVal)
bResetting = false;

return ReturnVal;
}



Hope this helps,
Chris

Share this post


Link to post
Share on other sites
Lots of helpful info in there. I guess the code is fairly similar to mine.

I am calling the Reset function improperly. I know this because I tried a

if(FAILED(device->Reset())
MessageBox(xxxx)

which ended up showing the message box.

From my code above I use d3dpool textures and I don't have fonts or anything that need to be reseted.

I appreciate all the help, but
I'm about to give up on this and just ignore it. I know in OpenGL this is done for you, you don't have to worry about it. I think another reason for the problem is because the tutorials were done using D3DX, and the code other people have used to explain their solution doesn't seem to be in D3DX(make difference?).

I'll try a couple more things.

Edit : One thing i did try is g_pVB->Release() ;, I then called the function that recreates it, but with no luck.

The screen is black

[Edited by - Toonkides on October 24, 2004 4:47:01 PM]

Share this post


Link to post
Share on other sites
Your vertex buffer was not managed, so you have to release it and recreate it. That would go as follows.

g_vb->Release();
g_pd3dDevice->Reset();
Create(g_vb);

Is this how you did it? And it made the screen black?

Chris

Share this post


Link to post
Share on other sites
Aye, that's exactly what did it.

I released the VB then the g_pd3dDevice.

Now the create of the VB in the tutorial was from the InitGeometry() function which has the code :


HRESULT InitGeometry()
{
// use D3DX to create a texture from a file based image
if(FAILED(D3DXCreateTextureFromFile(g_pd3dDevice, "hovigTex.bmp", &g_pTexture)))
return E_FAIL ;
// create the vertex buffer
if(FAILED(g_pd3dDevice->CreateVertexBuffer(100 * sizeof(CUSTOMVERTEX), 0,
D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVB, NULL)))
return E_FAIL ;

// fill the vertex buffer. We are algorithmically generating a cylinder
// here, including the normals, which are used for lighting
CUSTOMVERTEX* pVertices ;
if(FAILED(g_pVB->Lock(0, 0, (void**)&pVertices, 0)))
return E_FAIL ;
for(DWORD i = 0; i < 50; i++)
{
FLOAT theta = (2 * D3DX_PI * i) / 49 ;
pVertices[2 * i + 0].position = D3DXVECTOR3(sinf(theta), -1.0f, cosf(theta)) ;
pVertices[2 * i + 0].color = 0xffffffff ;
#ifndef SHOW_HOW_TO_USE_TCI
pVertices[2 * i + 0].tu = FLOAT(i) / (49) ;
pVertices[2 * i + 0].tv = 1.0f ;
#endif
pVertices[2 * i + 1].position = D3DXVECTOR3(sinf(theta), 1.0f, cosf(theta)) ;
pVertices[2 * i + 1].color = 0xff808080 ;
#ifndef SHOW_HOW_TO_USE_TCI
pVertices[2 * i + 1].tu = FLOAT(i) / (49) ;
pVertices[2 * i + 1].tv = 0.0f ;
#endif
}
g_pVB->Unlock() ;

return S_OK ;
}




Tried that didn't work. Do I need to do something with the device when I reset it?

I even tried releasing the texture and recreating it, still a black screen. I tried looking for DX programs, but they sure do a good job of making sure no one knows how they deal with the resizing of stuff=(
TIA

Share this post


Link to post
Share on other sites
Quote:
Original post by Toonkides
Aye, that's exactly what did it.

I released the VB then the g_pd3dDevice.


I just want to make sure I have the details straight. What you meant to say here was that you released the VB and then called g_pd3dDevice->Reset(), correct?

Quote:

Now the create of the VB in the tutorial was from the InitGeometry() function which has the code :

*** Source Snippet Removed ***

Tried that didn't work. Do I need to do something with the device when I reset it?


If you called InitGeometry, did you test it for failing? I think you meant here that you just took the vertex buffer creation code out. Did you also fill the vertex buffer?

Nope, there shouldn't be anything else to do to the device except reset it.

Good luck,
Chris

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
  • Advertisement
  • Popular Now

  • Advertisement
  • Similar Content

    • By Balma Alparisi
      i got error 1282 in my code.
      sf::ContextSettings settings; settings.majorVersion = 4; settings.minorVersion = 5; settings.attributeFlags = settings.Core; sf::Window window; window.create(sf::VideoMode(1600, 900), "Texture Unit Rectangle", sf::Style::Close, settings); window.setActive(true); window.setVerticalSyncEnabled(true); glewInit(); GLuint shaderProgram = createShaderProgram("FX/Rectangle.vss", "FX/Rectangle.fss"); float vertex[] = { -0.5f,0.5f,0.0f, 0.0f,0.0f, -0.5f,-0.5f,0.0f, 0.0f,1.0f, 0.5f,0.5f,0.0f, 1.0f,0.0f, 0.5,-0.5f,0.0f, 1.0f,1.0f, }; GLuint indices[] = { 0,1,2, 1,2,3, }; GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); GLuint vbo; glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(vertex), vertex, GL_STATIC_DRAW); GLuint ebo; glGenBuffers(1, &ebo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices,GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, false, sizeof(float) * 5, (void*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 2, GL_FLOAT, false, sizeof(float) * 5, (void*)(sizeof(float) * 3)); glEnableVertexAttribArray(1); GLuint texture[2]; glGenTextures(2, texture); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture[0]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); sf::Image* imageOne = new sf::Image; bool isImageOneLoaded = imageOne->loadFromFile("Texture/container.jpg"); if (isImageOneLoaded) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, imageOne->getSize().x, imageOne->getSize().y, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageOne->getPixelsPtr()); glGenerateMipmap(GL_TEXTURE_2D); } delete imageOne; glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture[1]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); sf::Image* imageTwo = new sf::Image; bool isImageTwoLoaded = imageTwo->loadFromFile("Texture/awesomeface.png"); if (isImageTwoLoaded) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, imageTwo->getSize().x, imageTwo->getSize().y, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageTwo->getPixelsPtr()); glGenerateMipmap(GL_TEXTURE_2D); } delete imageTwo; glUniform1i(glGetUniformLocation(shaderProgram, "inTextureOne"), 0); glUniform1i(glGetUniformLocation(shaderProgram, "inTextureTwo"), 1); GLenum error = glGetError(); std::cout << error << std::endl; sf::Event event; bool isRunning = true; while (isRunning) { while (window.pollEvent(event)) { if (event.type == event.Closed) { isRunning = false; } } glClear(GL_COLOR_BUFFER_BIT); if (isImageOneLoaded && isImageTwoLoaded) { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture[0]); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture[1]); glUseProgram(shaderProgram); } glBindVertexArray(vao); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr); glBindVertexArray(0); window.display(); } glDeleteVertexArrays(1, &vao); glDeleteBuffers(1, &vbo); glDeleteBuffers(1, &ebo); glDeleteProgram(shaderProgram); glDeleteTextures(2,texture); return 0; } and this is the vertex shader
      #version 450 core layout(location=0) in vec3 inPos; layout(location=1) in vec2 inTexCoord; out vec2 TexCoord; void main() { gl_Position=vec4(inPos,1.0); TexCoord=inTexCoord; } and the fragment shader
      #version 450 core in vec2 TexCoord; uniform sampler2D inTextureOne; uniform sampler2D inTextureTwo; out vec4 FragmentColor; void main() { FragmentColor=mix(texture(inTextureOne,TexCoord),texture(inTextureTwo,TexCoord),0.2); } I was expecting awesomeface.png on top of container.jpg

    • By khawk
      We've just released all of the source code for the NeHe OpenGL lessons on our Github page at https://github.com/gamedev-net/nehe-opengl. code - 43 total platforms, configurations, and languages are included.
      Now operated by GameDev.net, NeHe is located at http://nehe.gamedev.net where it has been a valuable resource for developers wanting to learn OpenGL and graphics programming.

      View full story
    • By TheChubu
      The Khronos™ Group, an open consortium of leading hardware and software companies, announces from the SIGGRAPH 2017 Conference the immediate public availability of the OpenGL® 4.6 specification. OpenGL 4.6 integrates the functionality of numerous ARB and EXT extensions created by Khronos members AMD, Intel, and NVIDIA into core, including the capability to ingest SPIR-V™ shaders.
      SPIR-V is a Khronos-defined standard intermediate language for parallel compute and graphics, which enables content creators to simplify their shader authoring and management pipelines while providing significant source shading language flexibility. OpenGL 4.6 adds support for ingesting SPIR-V shaders to the core specification, guaranteeing that SPIR-V shaders will be widely supported by OpenGL implementations.
      OpenGL 4.6 adds the functionality of these ARB extensions to OpenGL’s core specification:
      GL_ARB_gl_spirv and GL_ARB_spirv_extensions to standardize SPIR-V support for OpenGL GL_ARB_indirect_parameters and GL_ARB_shader_draw_parameters for reducing the CPU overhead associated with rendering batches of geometry GL_ARB_pipeline_statistics_query and GL_ARB_transform_feedback_overflow_querystandardize OpenGL support for features available in Direct3D GL_ARB_texture_filter_anisotropic (based on GL_EXT_texture_filter_anisotropic) brings previously IP encumbered functionality into OpenGL to improve the visual quality of textured scenes GL_ARB_polygon_offset_clamp (based on GL_EXT_polygon_offset_clamp) suppresses a common visual artifact known as a “light leak” associated with rendering shadows GL_ARB_shader_atomic_counter_ops and GL_ARB_shader_group_vote add shader intrinsics supported by all desktop vendors to improve functionality and performance GL_KHR_no_error reduces driver overhead by allowing the application to indicate that it expects error-free operation so errors need not be generated In addition to the above features being added to OpenGL 4.6, the following are being released as extensions:
      GL_KHR_parallel_shader_compile allows applications to launch multiple shader compile threads to improve shader compile throughput WGL_ARB_create_context_no_error and GXL_ARB_create_context_no_error allow no error contexts to be created with WGL or GLX that support the GL_KHR_no_error extension “I’m proud to announce OpenGL 4.6 as the most feature-rich version of OpenGL yet. We've brought together the most popular, widely-supported extensions into a new core specification to give OpenGL developers and end users an improved baseline feature set. This includes resolving previous intellectual property roadblocks to bringing anisotropic texture filtering and polygon offset clamping into the core specification to enable widespread implementation and usage,” said Piers Daniell, chair of the OpenGL Working Group at Khronos. “The OpenGL working group will continue to respond to market needs and work with GPU vendors to ensure OpenGL remains a viable and evolving graphics API for all its customers and users across many vital industries.“
      The OpenGL 4.6 specification can be found at https://khronos.org/registry/OpenGL/index_gl.php. The GLSL to SPIR-V compiler glslang has been updated with GLSL 4.60 support, and can be found at https://github.com/KhronosGroup/glslang.
      Sophisticated graphics applications will also benefit from a set of newly released extensions for both OpenGL and OpenGL ES to enable interoperability with Vulkan and Direct3D. These extensions are named:
      GL_EXT_memory_object GL_EXT_memory_object_fd GL_EXT_memory_object_win32 GL_EXT_semaphore GL_EXT_semaphore_fd GL_EXT_semaphore_win32 GL_EXT_win32_keyed_mutex They can be found at: https://khronos.org/registry/OpenGL/index_gl.php
      Industry Support for OpenGL 4.6
      “With OpenGL 4.6 our customers have an improved set of core features available on our full range of OpenGL 4.x capable GPUs. These features provide improved rendering quality, performance and functionality. As the graphics industry’s most popular API, we fully support OpenGL and will continue to work closely with the Khronos Group on the development of new OpenGL specifications and extensions for our customers. NVIDIA has released beta OpenGL 4.6 drivers today at https://developer.nvidia.com/opengl-driver so developers can use these new features right away,” said Bob Pette, vice president, Professional Graphics at NVIDIA.
      "OpenGL 4.6 will be the first OpenGL release where conformant open source implementations based on the Mesa project will be deliverable in a reasonable timeframe after release. The open sourcing of the OpenGL conformance test suite and ongoing work between Khronos and X.org will also allow for non-vendor led open source implementations to achieve conformance in the near future," said David Airlie, senior principal engineer at Red Hat, and developer on Mesa/X.org projects.

      View full story
    • By _OskaR
      Hi,
      I have an OpenGL application but without possibility to wite own shaders.
      I need to perform small VS modification - is possible to do it in an alternative way? Do we have apps or driver modifictions which will catch the shader sent to GPU and override it?
    • By xhcao
      Does sync be needed to read texture content after access texture image in compute shader?
      My simple code is as below,
      glUseProgram(program.get());
      glBindImageTexture(0, texture[0], 0, GL_FALSE, 3, GL_READ_ONLY, GL_R32UI);
      glBindImageTexture(1, texture[1], 0, GL_FALSE, 4, GL_WRITE_ONLY, GL_R32UI);
      glDispatchCompute(1, 1, 1);
      // Does sync be needed here?
      glUseProgram(0);
      glBindFramebuffer(GL_READ_FRAMEBUFFER, framebuffer);
      glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
                                     GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, texture[1], 0);
      glReadPixels(0, 0, kWidth, kHeight, GL_RED_INTEGER, GL_UNSIGNED_INT, outputValues);
       
      Compute shader is very simple, imageLoad content from texture[0], and imageStore content to texture[1]. Does need to sync after dispatchCompute?
  • Advertisement