• Advertisement
Sign in to follow this  

OpenGL Problem with glBegin(GL_TRIANGLES)

This topic is 4825 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 trying to learn OpenGL so I was using NeHe's guide to help. So I'm on lesson #2, and I just recently compiled the code to see if everything works so far. Now, using Dev-C++ 4.9.9.1 I get an error from the following code:
    glBegin(GL_TRIANGLES);                               //Drawing using triangles
            glVertex3f(0.0f,1.0f,0.0f);                  //Top
            glVertex3f(-1.0f,-1.0f,0.0f);                //Bottom left
            glVertex3f(1.0f,-1.0f,0.0f);                 //Bottomg right
    glEnd();  
It says that there is a syntax error in glBegin() before the '(' token. Does anybody know what is wrong with this? I have it exzctly as it says in the tuturial and it simply will not accept that line of code ... EDIT: Ugh I'm so stupid, I had an error like 3 lines before it where I forgot the ";" :( EDIT #2: Ok I figured now would be a good time to ask this question as well. I get en error with the:
	gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);
part. A undefined refrence error @32. Here is the total code (some written, some copied and pasted)
/*
 *		This Code Was Created By Jeff Molofee 2000
 *		A HUGE Thanks To Fredric Echols For Cleaning Up
 *		And Optimizing This Code, Making It More Flexible!
 *		If You've Found This Code Useful, Please Let Me Know.
 *		Visit My Site At nehe.gamedev.net
 */

#include <windows.h>		// Header File For Windows
#include <gl\gl.h>			// Header File For The OpenGL32 Library
#include <gl\glu.h>			// Header File For The GLu32 Library
//#include <gl\glaux.h>		// Header File For The Glaux Library

HDC			hDC=NULL;		// Private GDI Device Context
HGLRC		hRC=NULL;		// Permanent Rendering Context
HWND		hWnd=NULL;		// Holds Our Window Handle
HINSTANCE	hInstance;		// Holds The Instance Of The Application

bool	keys[256];			// Array Used For The Keyboard Routine
bool	active=TRUE;		// Window Active Flag Set To TRUE By Default
bool	fullscreen=TRUE;	// Fullscreen Flag Set To Fullscreen Mode By Default

LRESULT	CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);	// Declaration For WndProc

GLvoid ReSizeGLScene(GLsizei width, GLsizei height)		// Resize And Initialize The GL Window
{
	if (height==0)										// Prevent A Divide By Zero By
	{
		height=1;										// Making Height Equal One
	}

	glViewport(0,0,width,height);						// Reset The Current Viewport

	glMatrixMode(GL_PROJECTION);						// Select The Projection Matrix
	glLoadIdentity();									// Reset The Projection Matrix

	// Calculate The Aspect Ratio Of The Window
	gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);

	glMatrixMode(GL_MODELVIEW);							// Select The Modelview Matrix
	glLoadIdentity();									// Reset The Modelview Matrix
}
//setup for OpenGL
int InitGL(GLvoid)
{
    glShadeModel(GL_SMOOTH);
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glClearDepth(1.0f);            //Depth Buffer Setup
    glEnable(GL_DEPTH_TEST);       //Enables Depth Testing
    glDepthFunc(GL_LEQUAL);        //The type of depth test to do
    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
   	return TRUE;				  // Initialization Went OK
}

int DrawGLScene(GLvoid)
{
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);    //Clear the screen and the depth buffer
    glLoadIdentity();                                    //Reset the view
    glTranslatef(-1.5f,0.0f,-6.0f);                      //Move left 1.5 units and into the screen 6.0 units
    glBegin(GL_TRIANGLES);                               //Drawing using triangles
            glVertex3f(0.0f,1.0f,0.0f);                  //Top
            glVertex3f(-1.0f,-1.0f,0.0f);                //Bottom left
            glVertex3f(1.0f,-1.0f,0.0f);                 //Bottomg right
    glEnd();                                             //Finished drawing the triangle
    glTranslatef(3.0f,0.0f,0.0f);                        //Move right 3 units
    glBegin(GL_QUADS);                                   //Draw a Quad
            glVertex3f(-1.0f,1.0f,0.0f);                 //Top Left
            glVertex3f(1.0f,1.0f,0.0f);                  //Top Right
            glVertex3f(1.0f,-1.0f,0.0f);                 //Bottom Left
            glVertex3f(-1.0f,-1.0f,0.0f);                //Bottom Right
    glEnd();                                             //Finished Drawing the triangle
    return TRUE;                                         //Keep going
}

void KillGLWindow(GLvoid)
{
    if (fullscreen)
    {
        ChangeDisplaySettings(NULL,0);
        ShowCursor(TRUE);
    }
    
    if (hRC)
    {
        if (!wglMakeCurrent(NULL,NULL))
        {
                MessageBox(NULL,"Release of DC and RC failes.","SHUTDOWN ERROR",
                MB_OK | MB_ICONINFORMATION);
        }
        
        if (!wglDeleteContext(hRC))
        {
                MessageBox(NULL,"Release of Rendering Context Failed.","Shutdown Error",
                MB_OK | MB_ICONINFORMATION);
        }
        hRC=NULL;
    }
    
    if (hDC && !ReleaseDC(hWnd,hDC))
    {
        MessageBox(NULL,"Release Device Context Failed.","SHUTDOWN ERR",
        MB_OK | MB_ICONINFORMATION);
        hDC=NULL;
    }
    
    if (hWnd && !DestroyWindow(hWnd))
    {
        MessageBox(NULL,"Could NOt Release hWnd.","SHUTDOWN ERR",
        MB_OK | MB_ICONINFORMATION);
        hWnd=NULL;
    }
    
    if (!UnregisterClass("OpenGL",hInstance))
    {
        MessageBox(NULL,"Couldn't unregister class.","SHUTDOWN ERR",
        MB_OK | MB_ICONINFORMATION);
        hInstance=NULL;
    }
}

//not to create the godblessed window
/*BEGIN BOOL CREATEGLWINDOW()*/
BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag)
{
    GLuint  PixelFormat;        //holds the results after searing for a match
    WNDCLASS	wc;
    DWORD    dwExstyle;          //Window Extended style
    DWORD    dwstyle;            //window style
    RECT WindowRect;            //Grabs rectangle upper left/lower right values
    WindowRect.left=(long)0;    //set left value to 0
    WindowRect.right=(long)width;    //set right value to requested width
    WindowRect.top=(long)0;    //set top value to 0
    WindowRect.bottom=(long)height;    //set bottom value to requested height
    fullscreen=fullscreenflag;        //set the global fullscreen flag
    
    hInstance    = GetModuleHandle(NULL);    //Grab an instnace for our window
    wc.style			= CS_HREDRAW | CS_VREDRAW | CS_OWNDC;    //Redraw on Move, and Own DC for window
    wc.lpfnWndProc    = (WNDPROC) WndProc;    //WndProc Handles messages
    wc.cbClsExtra    = 0;    //No extra window data
    wc.cbWndExtra    = 0;    //no extra window daya
    wc.hInstance    = hInstance;    //Set the instance
    wc.hIcon    = LoadIcon(NULL, IDI_WINLOGO); //Load the default icon
    wc.hCursor    = LoadCursor(NULL, IDC_ARROW); //Load Arrow Pointer
    wc.hbrBackground    =NULL;    //No background required for GL
    wc.lpszMenuName    =NULL;    //we dont want a menu
    wc.lpszClassName    ="OpenGL";    //Set the Class Name
    
    //The Following code will result in an error message in the even anything goes wrong
    //If it does go wrong, pressing the OK box will close the program
    //+++BEGIN ERROR MESSAGE BOX CODE+++
    if (!RegisterClass(&wc))    //This will tell us if the attempt to register the class failed
    {
        MessageBox(NULL,"Failed to Register the Window CLass.","ERROR",MB_OK|MB_ICONEXCLAMATION);
        return FALSE;
    }
    //+++END ERROR MESSAGE BOX CODE+++
    
    //Checks if the program should run in fullscreen or windowed mode, should go into full screen
    //+++BEGIN FULLSCREEN CHECK+++
    if (fullscreen)    //Attempt Fullscreen mode?
    {
        DEVMODE dmScreenSettings;    //Device mode
        memset(&dmScreenSettings,0,sizeof(dmScreenSettings));	// Makes Sure Memory's Cleared
        dmScreenSettings.dmSize=sizeof(dmScreenSettings);        //Size of the Devmode Structure
        dmScreenSettings.dmPelsWidth=width;        //Selected Sceen Width
        dmScreenSettings.dmPelsHeight=height;        //selected screen height
        dmScreenSettings.dmBitsPerPel=bits;        //selected Bits per pixel
        dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;
        //Try to set selected mode and get results. NOTE: CDS_FULLSCREEN gets rid of start bar.
        if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN) !=DISP_CHANGE_SUCCESSFUL)
        {
                //if the mode fails, offer two options. Quit or Run in a window.
                if (MessageBox(NULL,"Use Windowed mode instead?","NEHE GL", MB_YESNO|MB_ICONEXCLAMATION)==IDYES)
                {
                        fullscreen=FALSE;                //Selected Window mode (FULLSCREEN=FALSE)
                }
                else
                {
                        //Pop up a messagebox to let user know program is going byebye
                        MessageBox(NULL,"Program is going byebye now.","Sucker...",MB_OK|MB_ICONSTOP);
                        return FALSE;                        //exist and return FALSE, GG noob comp
                }
        }
    }
	if (fullscreen)												// Are We Still In Fullscreen Mode?
	{
		dwExstyle=WS_EX_APPWINDOW;								// Window Extended style
		dwstyle=WS_POPUP;										// Windows style
		ShowCursor(FALSE);										// Hide Mouse Pointer
	}
	else
	{
		dwExstyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;			// Window Extended style
		dwstyle=WS_OVERLAPPEDWINDOW;							// Windows style
	}
    //Makes all things the speacified resolution
    AdjustWindowRectEx(&WindowRect, dwstyle, FALSE, dwExstyle);       //Adjust window to true requested size
    if (!(hWnd=CreateWindowEx(    dwExstyle,                 //Extended style for windows
                                  "OpenGL",                  //CLass name
                                  title,                     //Window Title
                                  WS_CLIPSIBLINGS |          //Required Window style
                                  WS_CLIPCHILDREN |          //Required Window style
                                  dwstyle,                   //Selected Window Stlye
                                  0, 0,                      //Window Postion
                                  WindowRect.right-WindowRect.left,                 //Calculage Adjusted Window Width
                                  WindowRect.bottom-WindowRect.top,                 //Calculate Adjusted Window Height
                                  NULL,                                             //No Parent Window
                                  NULL,                                             //No Menu
                                  hInstance,                                        //Instance
                                  NULL)))                                           //Dont pass anything to WM_CREATE
    {
        KillGLWindow();                                  //Reset the display
        MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION);
        return FALSE;
    }
    /*++END THE FULLSCREEN CHECK+++*/
    /*04/12/04 16:00*/
    
    /*This section of code describes a Pixel Format. Using a format that supports OPenGL and double buffering
     * We try to find a pixel format that matches the bits we deced on (16,24,32). Finally we set up a 16bit z-buffer.
     *The remaining paramets are eighre not used or not important
     */
    static PIXELFORMATDESCRIPTOR pfd=     //pfd tells the windows how we want stuff to be
    {
        sizeof(PIXELFORMATDESCRIPTOR),    //size of this pixel format dexriptor
        1,                                //Verstion of number
        PFD_DRAW_TO_WINDOW|               //FOrmat must support window
        PFD_SUPPORT_OPENGL|               //Format must support OpenGL
        PFD_DOUBLEBUFFER,                //Must support Double Buffering
        PFD_TYPE_RGBA,                   //Requests  an RGBA format
        bits,                           //Select our color depth
        0, 0, 0, 0, 0, 0,                //Color bits ignored
        0,                                //No alpha buffer
        0,                                //shift bits ignored
        0,                                //No accumilation buffer
        0, 0, 0, 0,                        //Accumulation bits ignored
        16,                                //16bit Z-Buffer (depth buffer)
        0,                                //No Stencil Buffer
        0,                                //No auxiliary buffer
        PFD_MAIN_PLANE,                   //Main drawing later
        0,                                //Reserved
        0,0,0                             //Layer masks ignroed
    };
    /*If there were no erros while creating the window, we'll attempt to get an OpenGL device context
     *if we cant get a DC an error messae will pop up and program will quit*/
     if(!(hDC=GetDC(hWnd)))     //Did we get a device context?
     {
          KillGLWindow();     //Reset the display'
          MessageBox(NULL,"CANT CREAT A GL DEVICE CONTEXT.","ERR",MB_OK|MB_ICONEXCLAMATION);
          return FALSE;          //Return false and close the program
     }
     /***IF we managed to get a device context for our OpenGL window we'll try to find a pixel forma that matches the one
      *described above. If Windows can't find a mataching pixel format, an error message will pop up and the program will
      *quit (return false)***/
     if(!(PixelFormat=ChoosePixelFormat(hDC,&pfd)))      //Did windows find a mataching pixel format?
     {
          KillGLWindow();     //Reset the display
          MessageBox(NULL,"Can't find a suitable PixelFormat.","ERR",MB_OK|MB_ICONEXCLAMATION);
          return FALSE;          //Return False (duh?)
     }
     /***If windows found a pixel format we'll try setting the pixel format, blah blah blah error etc.***/
     if(!SetPixelFormat(hDC,PixelFormat,&pfd))     //Are we able to set the Pixel Format?
     {
          KillGLWindow();     //Reset the display
          MessageBox(NULL,"Can't set the PixelFormat.","ERR",MB_OK|MB_ICONEXCLAMATION);
          return FALSE;
     }
     /*If pixel format was set properly we'll try to get a rednering context. If we can't get a rendering context ANOTHER
      *ERROR will pop up and the program will, once again, close*/
     if(!(hRC=wglCreateContext(hDC)))      //Are we able to get a rendering Context?
     {
          KillGLWindow();     //Reset the display
          MessageBox(NULL,"Cant create a GL Rendering Context.","ERR",MB_OK|MB_ICONEXCLAMATION);
          return FALSE;
     }
     /*IF there are no errors so far, and we've manated to create both a Device Context and a rednering context all we have
      *to do now is make the rendering context active. If we can't make the rendering context active an error message will
      *pop up on the screen and the program will quit*/
     if(!wglMakeCurrent(hDC,hRC))      //Try to active the rendering context
     {
          KillGLWindow();     //Reset the display
          MessageBox(NULL,"Can't activate the GL Rendering Context.","ERR",MB_OK|MB_ICONEXCLAMATION);
          return FALSE;
     }
     /*If everything went somoothly, and our OpenGL window was created we'll show the window, set it to be the foreground,
      *and set the focus on that window, then we'll call ReSizeG:SCene passing the screen width and height to set up our
      *perspective OpenGL sceren*/
     ShowWindow(hWnd,SW_SHOW);      //show the window
     SetForegroundWindow(hWnd);     //Slighlt higher priority
     SetFocus(hWnd);               //Sets the keboad focus to the window
     ReSizeGLScene(width, height); //set up our perspective GL Screen
     /*FINALLY, we jump to InitGL() where can set up lighting, texture, and anything else that needs to be setup. */
     if(!InitGL())     //Initialize our newly created GL Window
     {
          KillGLWindow();     //Reset the display
          MessageBox(NULL,"Initialization Failed.","ERR",MB_OK|MB_ICONEXCLAMATION);
          return FALSE;          //Return False
     }
     /*If it has gone this far, it is safe to assume window creation was succesful, we return true to WinMain() preventing it
      *(the program) from crashing*/
     return TRUE;      //Success!
}
/*END BOOL CREATEGLWINDOW()*/
//05/12/04 12:40
/*The next part is where all the window messages are dealth with. When we registeeed the window class we told it to come here 
 *to deal with window message */
/*+++BEGIN CASES+++*/
LRESULT CALLBACK WndProc(     HWND      hWnd,    //Handle for this window
                              UINT      uMsg,    //Message for this window
                              WPARAM    wParam,  //Additional message Information
                              LPARAM    lParam)  //Additional Message Information
{
     switch (uMsg)            //Check for winows messages
     {
            case WM_ACTIVATE: //watch for window activate message
            {
                 if(!HIWORD(wParam))  //Check for Minimization state
                 {
                      active=TRUE;  //Program is active
                 }
                 else
                 {
                     active=FALSE;  //Program is no longer active
                 }
                 
                 return 0;
            }
            case WM_SYSCOMMAND:     //intercept System COmmands
            {
                 switch (wParam)    //Check system calls
                 {
                        case SC_SCREENSAVE: //Screensaver is trying to start
                        case SC_MONITORPOWER:             //Monitor trying to enter powersave?
                        return 0;                         //prevent from happenning
                 }
                 break;
            }
            case WM_CLOSE:     //Did we receive a cloase message?
            {
                 PostQuitMessage(0); //Send a quit message
                 return 0;           //Jump back
            }
            case WM_KEYDOWN:         //Is a key being held down?
            {
                 keys[wParam]=TRUE;  //if so mark it as TRUE
                 return 0;           //Jump back
            }
            case WM_SIZE:            //Resize the OpenGL Window
            {
                 ReSizeGLScene(LOWORD(lParam),HIWORD(lParam)); //LoWord=width, Hiord=Height
                 return 0;                                     //jump back
            }
     }
     //pass all unhandled mesages to DefWindowProc
     return DefWindowProc(hWnd,uMsg,wParam,lParam);
}
/*+++END CASES+++*/

/*This is the entry point of our Windows Application. This is where we call our window creation routine, deal with window
 messages, and watch for human interaction.*/
/*+++BEGIN WINAPI WINMAIN()+++*/ 
int WINAPI WinMain(  HINSTANCE     hInstance,     //Instance
                     HINSTANCE     hPrevInstance, //Previous Instance
                     LPSTR         lpCmdLine,     //Command Line Parameters
                     int           nCmdShow)      //Window Show State
{
     MSG msg;        //Windows Message Structure
     BOOL done=FALSE;//Bool variablo to exit loop
     //Ask the user which screen mode they prefer
     if(MessageBox(NULL,"Would you like to run in Fullscreen mode?","Start Fullscreen?",MB_YESNO|MB_ICONQUESTION)==IDNO)
     {
          fullscreen=FALSE;    //Windowed Mode
     }
     //Create our openGL window
     if(!CreateGLWindow("NeHe's OpenGL Freamework",640,480,16,fullscreen))
     {
          return 0;             //Windowed Mode
     }
     while(!done)               //Loop that runs until done=TRUE
     {
          if(PeekMessage(&msg,NULL,0,0,PM_REMOVE))     //is there a message waiting?
          {
               if (msg.message==WM_QUIT)     //Have we received a quit message?
               {
                   done=TRUE;                //If so done=TRUE
               }
               else                          //If not, deal with window messages
               {
                    TranslateMessage(&msg); //Translate the message
                    DispatchMessage(&msg);   //Dispatch the message
               }
          }
          else     //If there are no messages
          {
                   //Draw the scene. Watch for ESC KEY and quit messages form DrawGLScene()
                   if (active)       //Program active?
                   {
                        if(keys[VK_ESCAPE])    //Was ESC pressed?
                        {
                             done=TRUE;        //ESC signalled a quit
                        }
                             else              //Not time to quit, update screne
                             {
                                  DrawGLScene();     //Draw The Scene 
                                  SwapBuffers(hDC);  //Swap Buffers
                             }
                        }
                        //now to allow for switching between fullscreen and windoed
			if (keys[VK_F1])						// Is F1 Being Pressed?
			{
				keys[VK_F1]=FALSE;					// If So Make Key FALSE
				KillGLWindow();						// Kill Our Current Window
				fullscreen=!fullscreen;				// Toggle Fullscreen / Windowed Mode
				// Recreate Our OpenGL Window
				if (!CreateGLWindow("NeHe's OpenGL Framework",640,480,16,fullscreen))
				{
					return 0;						// Quit If Window Was Not Created
				}
			}
		}
	}
          
         //if Done=TRUE program should quit
          //shutdown
          KillGLWindow();        //Kill the window
          return(msg.wParam);   //Exit the program
}

Share this post


Link to post
Share on other sites
Advertisement
Show us the whole function, not just the line where it says the error is. Also, are you remembering to include gl.h?

Share this post


Link to post
Share on other sites
EDITED: Sorry, no I didnt :( Man this is confusing me...
Does anybody know what a: [Linker error] undefined reference to `gluPerspective@32' is supposed to mean?

Share this post


Link to post
Share on other sites
The linker error most likely means you've forgotten to link glu32.lib when building the program.

Share this post


Link to post
Share on other sites
Quote:
Original post by Flax
The linker error most likely means you've forgotten to link glu32.lib when building the program.
Thank you! I got it to compile, thank you so much!

Share this post


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

  • Advertisement
  • Advertisement
  • Popular Tags

  • Advertisement
  • Popular Now

  • Similar Content

    • By LifeArtist
      Good Evening,
      I want to make a 2D game which involves displaying some debug information. Especially for collision, enemy sights and so on ...
      First of I was thinking about all those shapes which I need will need for debugging purposes: circles, rectangles, lines, polygons.
      I am really stucked right now because of the fundamental question:
      Where do I store my vertices positions for each line (object)? Currently I am not using a model matrix because I am using orthographic projection and set the final position within the VBO. That means that if I add a new line I would have to expand the "points" array and re-upload (recall glBufferData) it every time. The other method would be to use a model matrix and a fixed vbo for a line but it would be also messy to exactly create a line from (0,0) to (100,20) calculating the rotation and scale to make it fit.
      If I proceed with option 1 "updating the array each frame" I was thinking of having 4 draw calls every frame for the lines vao, polygons vao and so on. 
      In addition to that I am planning to use some sort of ECS based architecture. So the other question would be:
      Should I treat those debug objects as entities/components?
      For me it would make sense to treat them as entities but that's creates a new issue with the previous array approach because it would have for example a transform and render component. A special render component for debug objects (no texture etc) ... For me the transform component is also just a matrix but how would I then define a line?
      Treating them as components would'nt be a good idea in my eyes because then I would always need an entity. Well entity is just an id !? So maybe its a component?
      Regards,
      LifeArtist
    • By QQemka
      Hello. I am coding a small thingy in my spare time. All i want to achieve is to load a heightmap (as the lowest possible walking terrain), some static meshes (elements of the environment) and a dynamic character (meaning i can move, collide with heightmap/static meshes and hold a varying item in a hand ). Got a bunch of questions, or rather problems i can't find solution to myself. Nearly all are deal with graphics/gpu, not the coding part. My c++ is on high enough level.
      Let's go:
      Heightmap - i obviously want it to be textured, size is hardcoded to 256x256 squares. I can't have one huge texture stretched over entire terrain cause every pixel would be enormous. Thats why i decided to use 2 specified textures. First will be a tileset consisting of 16 square tiles (u v range from 0 to 0.25 for first tile and so on) and second a 256x256 buffer with 0-15 value representing index of the tile from tileset for every heigtmap square. Problem is, how do i blend the edges nicely and make some computationally cheap changes so its not obvious there are only 16 tiles? Is it possible to generate such terrain with some existing program?
      Collisions - i want to use bounding sphere and aabb. But should i store them for a model or entity instance? Meaning i have 20 same trees spawned using the same tree model, but every entity got its own transformation (position, scale etc). Storing collision component per instance grats faster access + is precalculated and transformed (takes additional memory, but who cares?), so i stick with this, right? What should i do if object is dynamically rotated? The aabb is no longer aligned and calculating per vertex min/max everytime object rotates/scales is pretty expensive, right?
      Drawing aabb - problem similar to above (storing aabb data per instance or model). This time in my opinion per model is enough since every instance also does not have own vertex buffer but uses the shared one (so 20 trees share reference to one tree model). So rendering aabb is about taking the model's aabb, transforming with instance matrix and voila. What about aabb vertex buffer (this is more of a cosmetic question, just curious, bumped onto it in time of writing this). Is it better to make it as 8 points and index buffer (12 lines), or only 2 vertices with min/max x/y/z and having the shaders dynamically generate 6 other vertices and draw the box? Or maybe there should be just ONE 1x1x1 cube box template moved/scaled per entity?
      What if one model got a diffuse texture and a normal map, and other has only diffuse? Should i pass some bool flag to shader with that info, or just assume that my game supports only diffuse maps without fancy stuff?
      There were several more but i forgot/solved them at time of writing
      Thanks in advance
    • By RenanRR
      Hi All,
      I'm reading the tutorials from learnOpengl site (nice site) and I'm having a question on the camera (https://learnopengl.com/Getting-started/Camera).
      I always saw the camera being manipulated with the lookat, but in tutorial I saw the camera being changed through the MVP arrays, which do not seem to be camera, but rather the scene that changes:
      Vertex Shader:
      #version 330 core layout (location = 0) in vec3 aPos; layout (location = 1) in vec2 aTexCoord; out vec2 TexCoord; uniform mat4 model; uniform mat4 view; uniform mat4 projection; void main() { gl_Position = projection * view * model * vec4(aPos, 1.0f); TexCoord = vec2(aTexCoord.x, aTexCoord.y); } then, the matrix manipulated:
      ..... glm::mat4 projection = glm::perspective(glm::radians(fov), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); ourShader.setMat4("projection", projection); .... glm::mat4 view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp); ourShader.setMat4("view", view); .... model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f)); ourShader.setMat4("model", model);  
      So, some doubts:
      - Why use it like that?
      - Is it okay to manipulate the camera that way?
      -in this way, are not the vertex's positions that changes instead of the camera?
      - I need to pass MVP to all shaders of object in my scenes ?
       
      What it seems, is that the camera stands still and the scenery that changes...
      it's right?
       
       
      Thank you
       
    • By dpadam450
      Sampling a floating point texture where the alpha channel holds 4-bytes of packed data into the float. I don't know how to cast the raw memory to treat it as an integer so I can perform bit-shifting operations.

      int rgbValue = int(textureSample.w);//4 bytes of data packed as color
      // algorithm might not be correct and endianness might need switching.
      vec3 extractedData = vec3(  rgbValue & 0xFF000000,  (rgbValue << 8) & 0xFF000000, (rgbValue << 16) & 0xFF000000);
      extractedData /= 255.0f;
    • By Devashish Khandelwal
      While writing a simple renderer using OpenGL, I faced an issue with the glGetUniformLocation function. For some reason, the location is coming to be -1.
      Anyone has any idea .. what should I do?
  • Advertisement