Jump to content
  • Advertisement
Sign in to follow this  
Toonkides

OpenGL Graphical consistency problems when resizing

This topic is 4985 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
Sign in to follow this  

  • Advertisement
  • Advertisement
  • Popular Tags

  • Similar Content

    • By owenjr
      Hi, I'm a Multimedia Engineering student. I am about to finish my dergree and I'm already thinking about what topic to cover in my final college project.
      I'm interested in the procedural animation with c++ and OpenGL of creatures, something like a spider for example. Can someone tell me what are the issues I should investigate to carry it out? I understand that it has some dependence on artificial intelligence but I do not know to what extent. Can someone help me to find information about it? Thank you very much.
       
      Examples: 
      - Procedural multi-legged walking animation
      - Procedural Locomotion of Multi-Legged Characters in Dynamic Environments
    • By Lewa
      So, i'm still on my quest to unterstanding the intricacies of HDR and implementing this into my engine. Currently i'm at the step to implementing tonemapping. I stumbled upon this blogposts:
      http://filmicworlds.com/blog/filmic-tonemapping-operators/
      http://frictionalgames.blogspot.com/2012/09/tech-feature-hdr-lightning.html
      and tried to implement some of those mentioned tonemapping methods into my postprocessing shader.
      The issue is that none of them creates the same results as shown in the blogpost which definitely has to do with the initial range in which the values are stored in the HDR buffer. For simplicity sake i store the values between 0 and 1 in the HDR buffer (ambient light is 0.3, directional light is 0.7)
      This is the tonemapping code:
      vec3 Uncharted2Tonemap(vec3 x) { float A = 0.15; float B = 0.50; float C = 0.10; float D = 0.20; float E = 0.02; float F = 0.30; return ((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F; } This is without the uncharted tonemapping:
      This is with the uncharted tonemapping:
      Which makes the image a lot darker.
      The shader code looks like this:
      void main() { vec3 color = texture2D(texture_diffuse, vTexcoord).rgb; color = Uncharted2Tonemap(color); //gamma correction (use only if not done in tonemapping code) color = gammaCorrection(color); outputF = vec4(color,1.0f); } Now, from my understanding is that tonemapping should bring the range down from HDR to 0-1.
      But the output of the tonemapping function heavily depends on the initial range of the values in the HDR buffer. (You can't expect to set the sun intensity the first time to 10 and the second time to 1000 and excpect the same result if you feed that into the tonemapper.) So i suppose that this also depends on the exposure which i have to implement?
      To check this i plotted the tonemapping curve:
      You can see that the curve goes only up to around to a value of 0.21 (while being fed a value of 1) and then basically flattens out. (which would explain why the image got darker.)
       
      My guestion is: In what range should the values in the HDR buffer be which then get tonemapped? Do i have to bring them down to a range of 0-1 by multiplying with the exposure?
      For example, if i increase the values of the light by 10 (directional light would be 7 and ambient light 3) then i would need to divide HDR values by 10 in order to get a value range of 0-1 which then could be fed into the tonemapping curve. Is that correct?
    • By nOoNEE
      i am reading this book : link
      in the OpenGL Rendering Pipeline section there is a picture like this: link
      but the question is this i dont really understand why it is necessary to turn pixel data in to fragment and then fragment into pixel could please give me a source or a clear Explanation that why it is necessary ? thank you so mu
       
       
    • By Inbar_xz
      I'm using the OPENGL with eclipse+JOGL.
      My goal is to create movement of the camera and the player.
      I create main class, which create some box in 3D and hold 
      an object of PlayerAxis.
      I create PlayerAxis class which hold the axis of the player.
      If we want to move the camera, then in the main class I call to 
      the func "cameraMove"(from PlayerAxis) and it update the player axis.
      That's work good.
      The problem start if I move the camera on 2 axis, 
      for example if I move with the camera right(that's on the y axis)
      and then down(on the x axis) -
      in some point the move front is not to the front anymore..
      In order to move to the front, I do
      player.playerMoving(0, 0, 1);
      And I learn that in order to keep the front move, 
      I need to convert (0, 0, 1) to the player axis, and then add this.
      I think I dont do the convert right.. 
      I will be glad for help!

      Here is part of my PlayerAxis class:
       
      //player coordinate float x[] = new float[3]; float y[] = new float[3]; float z[] = new float[3]; public PlayerAxis(float move_step, float angle_move) { x[0] = 1; y[1] = 1; z[2] = -1; step = move_step; angle = angle_move; setTransMatrix(); } public void cameraMoving(float angle_step, String axis) { float[] new_x = x; float[] new_y = y; float[] new_z = z; float alfa = angle_step * angle; switch(axis) { case "x": new_z = addVectors(multScalar(z, COS(alfa)), multScalar(y, SIN(alfa))); new_y = subVectors(multScalar(y, COS(alfa)), multScalar(z, SIN(alfa))); break; case "y": new_x = addVectors(multScalar(x, COS(alfa)), multScalar(z, SIN(alfa))); new_z = subVectors(multScalar(z, COS(alfa)), multScalar(x, SIN(alfa))); break; case "z": new_x = addVectors(multScalar(x, COS(alfa)), multScalar(y, SIN(alfa))); new_y = subVectors(multScalar(y, COS(alfa)), multScalar(x, SIN(alfa))); } x = new_x; y = new_y; z = new_z; normalization(); } public void playerMoving(float x_move, float y_move, float z_move) { float[] move = new float[3]; move[0] = x_move; move[1] = y_move; move[2] = z_move; setTransMatrix(); float[] trans_move = transVector(move); position[0] = position[0] + step*trans_move[0]; position[1] = position[1] + step*trans_move[1]; position[2] = position[2] + step*trans_move[2]; } public void setTransMatrix() { for (int i = 0; i < 3; i++) { coordiTrans[0][i] = x[i]; coordiTrans[1][i] = y[i]; coordiTrans[2][i] = z[i]; } } public float[] transVector(float[] v) { return multiplyMatrixInVector(coordiTrans, v); }  
      and in the main class i have this:
       
      public void keyPressed(KeyEvent e) { if (e.getKeyCode()== KeyEvent.VK_ESCAPE) { System.exit(0); //player move } else if (e.getKeyCode()== KeyEvent.VK_W) { //front //moveAmount[2] += -0.1f; player.playerMoving(0, 0, 1); } else if (e.getKeyCode()== KeyEvent.VK_S) { //back //moveAmount[2] += 0.1f; player.playerMoving(0, 0, -1); } else if (e.getKeyCode()== KeyEvent.VK_A) { //left //moveAmount[0] += -0.1f; player.playerMoving(-1, 0, 0); } else if (e.getKeyCode()== KeyEvent.VK_D) { //right //moveAmount[0] += 0.1f; player.playerMoving(1, 0, 0); } else if (e.getKeyCode()== KeyEvent.VK_E) { //moveAmount[0] += 0.1f; player.playerMoving(0, 1, 0); } else if (e.getKeyCode()== KeyEvent.VK_Q) { //moveAmount[0] += 0.1f; player.playerMoving(0, -1, 0); //camera move } else if (e.getKeyCode()== KeyEvent.VK_I) { //up player.cameraMoving(1, "x"); } else if (e.getKeyCode()== KeyEvent.VK_K) { //down player.cameraMoving(-1, "x"); } else if (e.getKeyCode()== KeyEvent.VK_L) { //right player.cameraMoving(-1, "y"); } else if (e.getKeyCode()== KeyEvent.VK_J) { //left player.cameraMoving(1, "y"); } else if (e.getKeyCode()== KeyEvent.VK_O) { //right round player.cameraMoving(-1, "z"); } else if (e.getKeyCode()== KeyEvent.VK_U) { //left round player.cameraMoving(1, "z"); } }  
      finallt found it.... i confused with the transformation matrix row and col. thanks anyway!
    • By Lewa
      So, i'm currently trying to implement an SSAO shader from THIS tutorial and i'm running into a few issues here.
      Now, this SSAO method requires view space positions and normals. I'm storing the normals in my deferred renderer in world-space so i had to do a conversion and reconstruct the position from the depth buffer.
      And something there goes horribly wrong (which has probably to do with worldspace to viewspace transformations).
      (here is the full shader source code if someone wants to take a look at it)
      Now, i suspect that the normals are the culprit.
      vec3 normal = ((uNormalViewMatrix*vec4(normalize(texture2D(sNormals, vTexcoord).rgb),1.0)).xyz); "sNormals" is a 2D texture which stores the normals in world space in a RGB FP16 buffer.
      Now i can't use the camera viewspace matrix to transform the normals into viewspace as the cameras position isn't set at (0,0,0), thus skewing the result.
      So what i did is to create a new viewmatrix specifically for this normal without the position at vec3(0,0,0);
      //"camera" is the camera which was used for rendering the normal buffer renderer.setUniform4m(ressources->shaderSSAO->getUniform("uNormalViewMatrix"), glmExt::createViewMatrix(glm::vec3(0,0,0),camera.getForward(),camera.getUp())//parameters are (position,forwardVector,upVector) ); Though i have the feeling this is the wrong approach. Is this right or is there a better/correct way of transforming a world space normal into viewspace?
    • By HawkDeath
      Hi,
      I'm trying mix two textures using own shader system, but I have a problem (I think) with uniforms.
      Code: https://github.com/HawkDeath/shader/tree/test
      To debug I use RenderDocs, but I did not receive good results. In the first attachment is my result, in the second attachment is what should be.
      PS. I base on this tutorial https://learnopengl.com/Getting-started/Textures.


    • By norman784
      I'm having issues loading textures, as I'm clueless on how to handle / load images maybe I missing something, but the past few days I just google a lot to try to find a solution. Well theres two issues I think, one I'm using Kotlin Native (EAP) and OpenGL wrapper / STB image, so I'm not quite sure wheres the issue, if someone with more experience could give me some hints on how to solve this issue?
      The code is here, if I'm not mistaken the workflow is pretty straight forward, stbi_load returns the pixels of the image (as char array or byte array) and you need to pass those pixels directly to glTexImage2D, so a I'm missing something here it seems.
      Regards
    • By Hashbrown
      I've noticed in most post processing tutorials several shaders are used one after another: one for bloom, another for contrast, and so on. For example: 
      postprocessing.quad.bind() // Effect 1 effect1.shader.bind(); postprocessing.texture.bind(); postprocessing.quad.draw(); postprocessing.texture.unbind(); effect1.shader.unbind(); // Effect 2 effect2.shader.bind(); // ...and so on postprocessing.quad.unbind() Is this good practice, how many shaders can I bind and unbind before I hit performance issues? I'm afraid I don't know what the good practices are in open/webGL regarding binding and unbinding resources. 
      I'm guessing binding many shaders at post processing is okay since the scene has already been updated and I'm just working on a quad and texture at that moment. Or is it more optimal to put shader code in chunks and bind less frequently? I'd love to use several shaders at post though. 
      Another example of what I'm doing at the moment:
      1) Loop through GameObjects, bind its phong shader (send color, shadow, spec, normal samplers), unbind all.
      2) At post: bind post processor quad, and loop/bind through different shader effects, and so on ...
      Thanks all! 
    • By phil67rpg
      void collision(int v) { collision_bug_one(0.0f, 10.0f); glutPostRedisplay(); glutTimerFunc(1000, collision, 0); } void coll_sprite() { if (board[0][0] == 1) { collision(0); flag[0][0] = 1; } } void erase_sprite() { if (flag[0][0] == 1) { glColor3f(0.0f, 0.0f, 0.0f); glBegin(GL_POLYGON); glVertex3f(0.0f, 10.0f, 0.0f); glVertex3f(0.0f, 9.0f, 0.0f); glVertex3f(1.0f, 9.0f, 0.0f); glVertex3f(1.0f, 10.0f, 0.0f); glEnd(); } } I am using glutTimerFunc to wait a small amount of time to display a collision sprite before I black out the sprite. unfortunately my code only blacks out the said sprite without drawing the collision sprite, I have done a great deal of research on the glutTimerFunc and  animation.
    • By Lewa
      So, i stumbled upon the topic of gamma correction.
      https://learnopengl.com/Advanced-Lighting/Gamma-Correction
      So from what i've been able to gather: (Please correct me if i'm wrong)
      Old CRT monitors couldn't display color linearly, that's why gamma correction was nessecary. Modern LCD/LED monitors don't have this issue anymore but apply gamma correction anyway. (For compatibility reasons? Can this be disabled?) All games have to apply gamma correction? (unsure about that) All textures stored in file formats (.png for example) are essentially stored in SRGB color space (as what we see on the monitor is skewed due to gamma correction. So the pixel information is the same, the percieved colors are just wrong.) This makes textures loaded into the GL_RGB format non linear, thus all lighting calculations are wrong You have to always use the GL_SRGB format to gamma correct/linearise textures which are in SRGB format  
      Now, i'm kinda confused how to proceed with applying gamma correction in OpenGL.
      First of, how can i check if my Monitor is applying gamma correction? I noticed in my monitor settings that my color format is set to "RGB" (can't modify it though.) I'm connected to my PC via a HDMI cable. I'm also using the full RGB range (0-255, not the 16 to ~240 range)
       
      What i tried to do is to apply a gamma correction shader shown in the tutorial above which looks essentially like this: (it's a postprocess shader which is applied at the end of the renderpipeline)
      vec3 gammaCorrection(vec3 color){ // gamma correction color = pow(color, vec3(1.0/2.2)); return color; } void main() { vec3 color; vec3 tex = texture2D(texture_diffuse, vTexcoord).rgb; color = gammaCorrection(tex); outputF = vec4(color,1.0f); } The results look like this:
      No gamma correction:
      With gamma correction:
       
      The colors in the gamma corrected image look really wased out. (To the point that it's damn ugly. As if someone overlayed a white half transparent texture. I want the colors to pop.)
      Do i have to change the textures from GL_RGB to GL_SRGB in order to gamma correct them in addition to applying the post process gamma correction shader? Do i have to do the same thing with all FBOs? Or is this washed out look the intended behaviour?
  • Advertisement
  • Popular Now

  • Forum Statistics

    • Total Topics
      631374
    • Total Posts
      2999661
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!