void createBufferObjects() { glGenBuffers(1, VboId); DrawingZone->createBufferObjects(); EditZone->createBufferObjects(); glBindBuffer(GL_UNIFORM_BUFFER, VboId[0]); glBufferData(GL_UNIFORM_BUFFER, sizeof(glm::mat4)*2, 0, GL_STREAM_DRAW); glBindBufferBase(GL_UNIFORM_BUFFER, UBO_BP, VboId[0]); glBindBuffer(GL_UNIFORM_BUFFER, 0); checkOpenGLError("ERROR: Could not create VAOs and VBOs."); }
ShaderDescription::ShaderDescription(const ShaderStage &vertex, const ShaderStage &fragment) { program = glCreateProgram(); glAttachShader(program, vertex.shader); glAttachShader(program, fragment.shader); glLinkProgram(program); GLint isLinked; glGetProgramiv(program, GL_LINK_STATUS, &isLinked); assert(isLinked == GL_TRUE); checkOpenGLError(); printShaderInfoLog(program); sampler = glGetUniformLocation(program, "color_map"); }
GuiShaderDescription::GuiShaderDescription(const ShaderStage &vertex, const ShaderStage &fragment) : ShaderDescription(vertex, fragment) { offset = glGetUniformLocation(program, "offset"); factor = glGetUniformLocation(program, "factor"); glBindAttribLocation(program, vertex_attribs::position, "position"); glBindAttribLocation(program, vertex_attribs::color, "color"); glLinkProgram(program); GLint isLinked; glGetProgramiv(program, GL_LINK_STATUS, &isLinked); assert(isLinked == GL_TRUE); checkOpenGLError(); printShaderInfoLog(program); }
int downloadOpenGLDepthFromTexture(const char * filename , unsigned int tex , unsigned int width , unsigned int height) { float * pixelsF = (float * ) malloc(sizeof(float) * width * height); if (pixelsF!=0) { glBindTexture(GL_TEXTURE_2D, tex); glGetTexImage ( GL_TEXTURE_2D, tex, GL_DEPTH_COMPONENT, GL_FLOAT, pixelsF); checkOpenGLError(__FILE__, __LINE__); glBindTexture(GL_TEXTURE_2D, 0); char * pixelsC = (char * ) malloc(sizeof(char) * 3 * width * height); if (pixelsC!=0) { float * pixelsFPTR = pixelsF; char * pixelPTR = pixelsC; char * pixelLimit = pixelsC+(3 * width * height); while (pixelPTR<pixelLimit) { *pixelPTR = (unsigned char) *pixelsFPTR; pixelPTR++; *pixelPTR = (unsigned char) *pixelsFPTR; pixelPTR++; *pixelPTR = (unsigned char) *pixelsFPTR; pixelPTR++; pixelsFPTR++; } saveRawImageToFileOGLR( filename, pixelsC , width, height, 1, 16 ); free(pixelsC); return 1; } free(pixelsF); } return 0; }
int downloadOpenGLColorFromTexture(const char * filename , unsigned int tex, unsigned int width , unsigned int height) { char * pixels3C = (char* ) malloc(sizeof(char) * 4 * width * height); if (pixels3C!=0) { glPixelStorei(GL_PACK_ALIGNMENT, 1); glBindTexture(GL_TEXTURE_2D, tex); glGetTexImage ( GL_TEXTURE_2D, tex, GL_RGB, GL_UNSIGNED_BYTE, pixels3C); checkOpenGLError(__FILE__, __LINE__); glBindTexture(GL_TEXTURE_2D, 0); char * pixelsC = (char * ) malloc(sizeof(char) * 3 * width * height); if (pixelsC!=0) { float * pixels3CPTR = pixels3C; char * pixelPTR = pixelsC; char * pixelLimit = pixelsC+(3 * width * height); while (pixelPTR<pixelLimit) { *pixelPTR = (unsigned char) *pixels3CPTR; pixelPTR++; pixels3CPTR++; *pixelPTR = (unsigned char) *pixels3CPTR; pixelPTR++; pixels3CPTR++; *pixelPTR = (unsigned char) *pixels3CPTR; pixelPTR++; pixels3CPTR++; } saveRawImageToFileOGLR( filename, pixelsC , width, height, 3, 8 ); free(pixelsC); return 1; } free(pixels3C); } return 0; }
int downloadOpenGLZBuffer(unsigned short * depth , unsigned int x,unsigned int y,unsigned int width,unsigned int height,float depthScale) { double depth_bias=0.0; double depth_scale=1.0; glGetDoublev(GL_DEPTH_BIAS, &depth_bias); // Returns 0.0 glGetDoublev(GL_DEPTH_SCALE, &depth_scale); // Returns 1.0 float * zbuffer = (float *) malloc((width-x)*(height-y)*sizeof(float)); if (zbuffer==0) { fprintf(stderr,"Could not allocate a zbuffer to read depth\n"); return 0; } glReadPixels(x + X_OFFSET , y, width, height, GL_DEPTH_COMPONENT, GL_FLOAT,zbuffer); //checkFrameGettersForError("Z-Buffer Getter"); /* Not sure I am calculating the correct depth here.. */ memset(depth,0 , (width-x)*(height-y)*2 ); #if FLIP_OPEN_GL_IMAGES unsigned int yp = 0; unsigned int i=0; unsigned int stride = (width-x)*1; float tmpF; for (yp=0; yp<height; yp++) { for ( i =0 ; i < (width-x); i ++ ) { //float tmpF=zbuffer[(height-1-yp)*stride+i]; tmpF = (1.0f - zbuffer[(height-1-yp)*stride+i]) * 65534.0; unsigned short tmp = (unsigned short) tmpF; depth[yp*stride+i]= tmp ; } } #else int i=0; for ( i =0 ; i < (width-x)*(height-y); i ++ ) { float tmpF = (1.0f - zbuffer[i]) * 65534.0; unsigned short tmp = (unsigned short) tmpF; depth[i]= tmp; } #endif if (zbuffer!=0) { free(zbuffer); zbuffer=0; } if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"OpenGL error after getOpenGLZBuffer() \n"); } return 1; }
SpriteShaderDescription::SpriteShaderDescription(const ShaderStage &vertex, const ShaderStage &fragment) : ShaderDescription(vertex, fragment) { model_view = glGetUniformLocation(program, "modelView"); projection = glGetUniformLocation(program, "projection"); glBindAttribLocation(program, vertex_attribs::position, "position"); glBindAttribLocation(program, vertex_attribs::corner_offset, "cornerOffset"); glBindAttribLocation(program, vertex_attribs::tex_coord, "texCoord"); glLinkProgram(program); GLint isLinked; glGetProgramiv(program, GL_LINK_STATUS, &isLinked); assert(isLinked == GL_TRUE); checkOpenGLError(); printShaderInfoLog(program); }
void drawScene() { glBindBuffer(GL_UNIFORM_BUFFER, VboId[0]); glViewport(0, 0, 640, 640); SimpleShader->useShaderProgram(); DrawingZone->draw(); glViewport(640, 0, 260, 640); SimpleShader->useShaderProgram(); EditZone->draw(); glBindBuffer(GL_UNIFORM_BUFFER, 0); glUseProgram(0); //TODO: Use ShaderProgram checkOpenGLError("ERROR: Could not draw scene."); }
// ----------------------------------------------------------------------------- SceneManager::SceneManager(const glm::ivec2 screenSize, SceneContainer *container) : m_world(container->getWorld()), m_camera(container->getCamera()), #ifndef WINDOWS m_textManager(TextManager(FONT_PATH + FONT_FILE, FONT_HEIGHT, screenSize)), #endif m_drawer(screenSize), m_shadowManager(screenSize), m_BACKGROUND_COLOR(container->getBackgroundColor()), m_positionMutex(SDL_CreateMutex()) { m_lightMask = (2 << (m_world->getLightsNumber() - 1)) - 1; setupProjection(screenSize); initGPU(container); glClearColor(m_BACKGROUND_COLOR.x, m_BACKGROUND_COLOR.y, m_BACKGROUND_COLOR.z, m_BACKGROUND_COLOR.w); checkOpenGLError("GLInitializer: glClearColor"); }
TextShaderDescription::TextShaderDescription(const ShaderStage &vertex, const ShaderStage &fragment) : ShaderDescription(vertex, fragment) { glBindAttribLocation(program, vertex_attribs::position, "position"); glBindAttribLocation(program, vertex_attribs::color, "color"); glBindAttribLocation(program, vertex_attribs::tex_coord, "texCoord"); glLinkProgram(program); GLint isLinked; glGetProgramiv(program, GL_LINK_STATUS, &isLinked); assert(isLinked == GL_TRUE); checkOpenGLError(); printShaderInfoLog(program); screenSize = glGetUniformLocation(program, "screenSize"); }
void Uniform::Bind(const Program& program, const std::string& name, const Vector4& value) { GLint location = program[name]; if (location != -1) { if (Program::msCurrentlyInUse == program.mProgram) glUniform4fv(location, 1, value); else { GLint current; glGetIntegerv(GL_CURRENT_PROGRAM, ¤t); program.Use(); glUniform3fv(location, 1, value); glUseProgram(current); Program::msCurrentlyInUse = current; } } checkOpenGLError("Failed to bind uniform " + name); }
UnlitShaderDescription::UnlitShaderDescription(const ShaderStage &vertex, const ShaderStage &fragment) : ShaderDescription(vertex, fragment) { glBindAttribLocation(program, VertexAttribs::Position, "position"); glBindAttribLocation(program, VertexAttribs::Color, "color"); glBindAttribLocation(program, VertexAttribs::TexCoord, "texCoord"); glBindAttribLocation(program, VertexAttribs::Normal, "normal"); glBindAttribLocation(program, VertexAttribs::MatrixIndex, "matrixIndex"); glLinkProgram(program); GLint isLinked; glGetProgramiv(program, GL_LINK_STATUS, &isLinked); assert(isLinked == GL_TRUE); checkOpenGLError(); printShaderInfoLog(program); model_view_projection = glGetUniformLocation(program, "modelViewProjection"); }
void initializeDefaultLighting() { GLfloat light_ambient[] = { 0.8f, 0.8f, 0.8f, 1.0f }; GLfloat light0_diffuse[] = {0.5f, 0.5f, 0.5f, 1.0f}; GLfloat light0_specular[] = {0.0f, 0.0f, 0.0f, 1.0f}; GLfloat light0_position[] = {-100.0, 100.0, -100.0, 0.0}; GLfloat light1_diffuse[] = {0.5f, 0.5f, 0.5f, 1.0f}; GLfloat light1_specular[] = {0.0f, 0.0f, 0.0f, 1.0f}; GLfloat light1_position[] = {100.0, 100.0, 100.0, 0.0}; glEnable(GL_LIGHTING); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, light_ambient); glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, true); glLightfv(GL_LIGHT0, GL_DIFFUSE, light0_diffuse); glLightfv(GL_LIGHT0, GL_SPECULAR, light0_specular); glLightfv(GL_LIGHT0, GL_POSITION, light0_position); glEnable(GL_LIGHT0); glLightfv(GL_LIGHT1, GL_DIFFUSE, light1_diffuse); glLightfv(GL_LIGHT1, GL_SPECULAR, light1_specular); glLightfv(GL_LIGHT1, GL_POSITION, light1_position); glEnable(GL_LIGHT1); checkOpenGLError(201); }
int downloadOpenGLColor(unsigned char * color , unsigned int x,unsigned int y,unsigned int width,unsigned int height) { GLint ext_format, ext_type; #warning "GL_IMPLEMENTATION_COLOR_READ_TYPE manually declared .." #define GL_IMPLEMENTATION_COLOR_READ_TYPE 0x8B9A #define GL_IMPLEMENTATION_COLOR_READ_FORMAT 0x8B9B glGetIntegerv(GL_IMPLEMENTATION_COLOR_READ_FORMAT, &ext_format); glGetIntegerv(GL_IMPLEMENTATION_COLOR_READ_TYPE, &ext_type); #if FLIP_OPEN_GL_IMAGES char * inverter = (char *) malloc(3*(width-x)*(height-y)*sizeof(char)); if (inverter==0) { fprintf(stderr,"Could not allocate a buffer to read inverted color\n"); return 0; } glReadPixels(x + X_OFFSET, y, width, height, GL_RGB, GL_UNSIGNED_BYTE,inverter); //checkFrameGettersForError("Flipped Color Getter"); //SLOW INVERSION CODE :P unsigned int yp = 0; unsigned int stride = (width-x)*3; for (yp=0; yp<height; yp++) { char * where_to = &color[yp*stride]; char * where_from = &inverter[(height-1-yp)*stride]; memcpy(where_to , where_from , stride * sizeof(char)); } free(inverter); #else glReadPixels(x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE,color); checkFrameGettersForError("Normal Color Getter"); #endif if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"OpenGL error after getOpenGLColor() \n"); } return 1; }
void updateViewMy(int uploadIt) { int viewport[4]={0}; glm::mat4 Projection = glm::perspective(fov, 1.0f, near , far); buildOpenGLProjectionForIntrinsics ( projectionMatrix , viewport , fx, fy, 0.0 , // SKEW windowWidth/2.0, windowHeight/2.0, windowWidth, windowHeight, near, far ); glmMatToFloat(projectionMatrix, Projection); float rotation[16]; float translation[16]; MatrixF4x42Quaternion(camera.angle,qXqYqZqW,rotation); create4x4IdentityFMatrix(rotation); create4x4TranslationMatrix(translation , camera.pos[0] , camera.pos[1] , camera.pos[2]); multiplyTwo4x4FMatrices(modelViewMatrix, translation , rotation ); multiplyTwo4x4FMatrices(modelViewProjectionMatrix, modelViewMatrix , projectionMatrix ); transpose4x4MatrixF(modelViewMatrix); transpose4x4MatrixF(modelViewProjectionMatrix); if (uploadIt) { glUniformMatrix4fv(modelViewProjectionMatrixLocation , 1 /*Only setting one matrix*/ , GL_FALSE /* dont transpose */, (const float * ) modelViewProjectionMatrix); checkOpenGLError(__FILE__, __LINE__); } }
GLhandleARB prepareShader (GLhandleARB vert, GLhandleARB frag, const char * path_vert, const char * path_frag) { GLint local_linked; GLhandleARB local; // create a vertex shader object and a fragment shader object vert = glCreateShaderObjectARB ( GL_VERTEX_SHADER_ARB ); frag = glCreateShaderObjectARB ( GL_FRAGMENT_SHADER_ARB ); // load source code strings into shaders if ( !loadShader ( vert, path_vert ) ) exit ( 1 ); if ( !loadShader ( frag, path_frag ) ) exit ( 1 ); // create a program object and attach the // two compiled shaders local = glCreateProgramObjectARB (); glAttachObjectARB ( local, vert ); glAttachObjectARB ( local, frag ); // link the program object and print out the info log glLinkProgramARB ( local ); if ( !checkOpenGLError() ) // check for OpenGL errors exit ( 1 ); glGetObjectParameterivARB ( local, GL_OBJECT_LINK_STATUS_ARB, &local_linked ); printInfoLog ( local); if ( !local_linked ) exit(0); return local; }
void pushObjectToBufferData( const float * vertices , unsigned int verticesLength , const float * normals , unsigned int normalsLength , const float * colors , unsigned int colorsLength ) { NumVertices+=(unsigned int ) verticesLength/(3*sizeof(float)); fprintf(stderr,GREEN "Will DrawArray(GL_TRIANGLES,0,%u)\n" NORMAL ,NumVertices); fprintf(stderr,GREEN "Pushing %u vertices (%u bytes) and %u normals (%u bytes) as our object \n" NORMAL ,verticesLength/sizeof(float),verticesLength,normalsLength/sizeof(float),normalsLength); glBufferData( GL_ARRAY_BUFFER, verticesLength + normalsLength + colorsLength ,NULL, GL_STATIC_DRAW ); checkOpenGLError(__FILE__, __LINE__); glBufferSubData( GL_ARRAY_BUFFER, 0 , verticesLength , vertices ); checkOpenGLError(__FILE__, __LINE__); glBufferSubData( GL_ARRAY_BUFFER, verticesLength , normalsLength , normals ); checkOpenGLError(__FILE__, __LINE__); if ( (colors!=0) && (colorsLength!=0) ) { glBufferSubData( GL_ARRAY_BUFFER, verticesLength + normalsLength , colorsLength , colors ); checkOpenGLError(__FILE__, __LINE__); } vPosition = glGetAttribLocation( program, "vPosition" ); checkOpenGLError(__FILE__, __LINE__); glEnableVertexAttribArray( vPosition ); checkOpenGLError(__FILE__, __LINE__); glVertexAttribPointer( vPosition, 3, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET(0) ); checkOpenGLError(__FILE__, __LINE__); vNormal = glGetAttribLocation( program, "vNormal" ); checkOpenGLError(__FILE__, __LINE__); glEnableVertexAttribArray( vNormal ); checkOpenGLError(__FILE__, __LINE__); glVertexAttribPointer( vNormal, 3, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET(verticesLength) ); checkOpenGLError(__FILE__, __LINE__); if ( (colors!=0) && (colorsLength!=0) ) { vColor = glGetAttribLocation( program, "vColor" ); glEnableVertexAttribArray( vColor ); glVertexAttribPointer( vColor, 3, GL_FLOAT, GL_FALSE, 0,BUFFER_OFFSET( verticesLength + normalsLength ) ); checkOpenGLError(__FILE__, __LINE__); } }
void drawOBJMesh(struct OBJ_Model * obj) { glPushAttrib(GL_ALL_ATTRIB_BITS); //We dont want the attributes we use here to poison the rest of the drawing if (obj == 0 ) { fprintf(stderr,"drawOBJMesh called with unloaded object \n"); return; } long unsigned int i,j; glDisable(GL_CULL_FACE); if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"Initial Error while @ drawOBJMesh\n"); } //for every group for(i=0; i<obj->numGroups; i++) { if (obj->matList!=0) { //We might not have a material with our object! //if there is a bmp file to load the texture from, in the mtl file if( obj->matList[obj->groups[i].material].hasTex ) { if( obj->matList[obj->groups[i].material].ldText>0) { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, obj->matList[ obj->groups[i].material].ldText); } } else { /*glDisable(GL_TEXTURE_2D);*/ } if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"Error before setting up material @ drawOBJMesh\n"); } GLenum faces=GL_FRONT;//GL_FRONT_AND_BACK; glMaterialfv(faces, GL_AMBIENT, obj->matList[ obj->groups[i].material].ambient); glMaterialfv(faces, GL_DIFFUSE, obj->matList[ obj->groups[i].material].diffuse); glMaterialfv(faces, GL_SPECULAR, obj->matList[ obj->groups[i].material].specular); if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"Error after setting up material for specularity @ drawOBJMesh\n"); } #if DISABLE_SHININESS glMaterialf(faces, GL_SHININESS, 0.0 ); #else glMaterialfv(faces, GL_SHININESS, obj->matList[ obj->groups[i].material].shine); #endif if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"Error after setting up material for shininess @ drawOBJMesh\n"); } //if the group has texture coordinates if( ( obj->groups[i].hasTex) ==0 ) { InitAutoTex(); } else { glDisable(GL_TEXTURE_GEN_S); glDisable(GL_TEXTURE_GEN_T); } if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"Error after setting up material @ drawOBJMesh\n"); } } else { //No Matterials , No Textures glDisable(GL_TEXTURE_GEN_S); glDisable(GL_TEXTURE_GEN_T); glDisable(GL_TEXTURE_2D); } if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"Error before starting drawing triangles @ drawOBJMesh\n"); } doOBJDrawCallsForGroup(obj,i); if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"Initial Error after drawing triangles @ drawOBJMesh\n"); } }//FOR I glPopAttrib(); }
void installShaders(void) { // // (1) Create shader objects // vertexShader = glCreateShader(GL_VERTEX_SHADER); fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); // // (2) Load source code into shader objects. // const GLchar *vertexShaderSource = getShaderSource("vertex.vs"); const GLchar *fragmentShaderSource = getShaderSource("fragment.fs"); glShaderSource(vertexShader, 1, &vertexShaderSource, NULL); glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL); // // (3) Compile shaders. // glCompileShader(vertexShader); GLint success; glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success); if (!success) { GLchar infoLog[200]; GLint charsWritten; glGetShaderInfoLog(vertexShader, sizeof(infoLog), &charsWritten, infoLog); fprintf(stderr, "vertex shader info log:\n%s\n\n", infoLog); } checkOpenGLError(__LINE__); glCompileShader(fragmentShader); glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success); if (!success) { GLchar infoLog[200]; GLint charsWritten; glGetShaderInfoLog(fragmentShader, sizeof(infoLog), &charsWritten, infoLog); fprintf(stderr, "fragment shader info log:\n%s\n\n", infoLog); } checkOpenGLError(__LINE__); // // (4) Create program object and attach vertex and fragment shader. // program = glCreateProgram(); glAttachShader(program, vertexShader); glAttachShader(program, fragmentShader); checkOpenGLError(__LINE__); // // (5) Link program. // glLinkProgram(program); glGetProgramiv(program, GL_LINK_STATUS, &success); if (!success) { GLchar infoLog[200]; GLint charsWritten; glGetProgramInfoLog(program, sizeof(infoLog), &charsWritten, infoLog); fprintf(stderr, "program info log:\n%s\n\n", infoLog); } checkOpenGLError(__LINE__); // // (7) Get vertex attribute locations // vertexPositionAttr = glGetAttribLocation(program, "vertexPosition"); vertexNormalAttr = glGetAttribLocation(program, "vertexNormal"); // vertexTexCoordAttr = glGetAttribLocation(program, "vertexTexCoord"); if (vertexPositionAttr == -1 || vertexNormalAttr == -1) { fprintf(stderr, "Error fetching vertex position or normal attribute !\n"); } // // (8) Fetch handles for uniform variables in program. // ModelViewProjectionUniform = glGetUniformLocation(program, "ModelViewProjection"); if (ModelViewProjectionUniform == -1) { fprintf(stderr, "Error fetching modelViewProjectionUniform !\n"); // exit(-1); } ModelViewMatrixUniform = glGetUniformLocation(program, "ModelViewMatrix"); if (ModelViewMatrixUniform == -1) { fprintf(stderr, "Error fetching modelViewMatrixUniform!\n"); // exit(-1); } NormalMatrixUniform = glGetUniformLocation(program, "NormalMatrix"); if (NormalMatrixUniform == -1) { fprintf(stderr, "Error fetching normalMatrixUniform!\n"); // exit(-1); } ambientLightUniform = glGetUniformLocation(program, "ambientLight"); if (ambientLightUniform == -1) { fprintf(stderr, "Error fetching ambientLightUniform!\n"); exit(-1); } light0ColorUniform = glGetUniformLocation(program, "light0Color"); if (light0ColorUniform == -1) { fprintf(stderr, "Error fetching light0ColorUniform!\n"); // exit(-1); } light0PositionUniform = glGetUniformLocation(program, "light0Position"); if (light0PositionUniform == -1) { fprintf(stderr, "Error fetching light0PositionUniform!\n"); // exit(-1); } materialAmbientUniform = glGetUniformLocation(program, "materialAmbient"); if (materialAmbientUniform == -1) { fprintf(stderr, "Error fetching materialAmbientUniform!\n"); // exit(-1); } materialDiffuseUniform = glGetUniformLocation(program, "materialDiffuse"); if (materialDiffuseUniform == -1) { fprintf(stderr, "Error fetching materialDiffuseUniform!\n"); //exit(-1); } materialSpecularUniform = glGetUniformLocation(program, "materialSpecular"); materialShininessUniform = glGetUniformLocation(program, "materialShininess"); nearPlaneUniform = glGetUniformLocation(program, "nearPlane"); farPlaneUniform = glGetUniformLocation(program, "farPlane"); // // (9) Tell GL to use our program // glUseProgram(program); }
void createShaderProgram() { Shader = new ShaderProgram(); Shader->setProgramId(); Shader->addShaderFromFile(VERTEX_SHADER_FILE, GL_VERTEX_SHADER); Shader->addShaderFromFile(FRAGMENT_SHADER_FILE, GL_FRAGMENT_SHADER); Shader->bindAttribLocation(VERTICES, "in_Position"); Shader->bindAttribLocation(TEXTURES, "in_Texcoord"); Shader->bindAttribLocation(NORMALS, "in_Normal"); Shader->linkShaderProgram(); UboId = glGetUniformBlockIndex(Shader->getProgramId(), "SharedMatrices"); //TODO: Use ShaderProgram glUniformBlockBinding(Shader->getProgramId(), UboId, UBO_BP); ReflectionX = new ShaderProgram(); ReflectionX->setProgramId(); ReflectionX->addShaderFromFile("../src/shaders/ReflectionXShader.glsl", GL_VERTEX_SHADER); ReflectionX->addShaderFromFile(FRAGMENT_SHADER_FILE, GL_FRAGMENT_SHADER); ReflectionX->bindAttribLocation(VERTICES, "in_Position"); ReflectionX->bindAttribLocation(COLORS, "in_Color"); ReflectionX->bindAttribLocation(TEXTURES, "in_Texcoord"); ReflectionX->bindAttribLocation(NORMALS, "in_Normal"); ReflectionX->linkShaderProgram(); UboId = glGetUniformBlockIndex(ReflectionX->getProgramId(), "SharedMatrices"); //TODO: Use ShaderProgram glUniformBlockBinding(ReflectionX->getProgramId(), UboId, UBO_BP); ReflectionZ = new ShaderProgram(); ReflectionZ->setProgramId(); ReflectionZ->addShaderFromFile("../src/shaders/ReflectionZShader.glsl", GL_VERTEX_SHADER); ReflectionZ->addShaderFromFile(FRAGMENT_SHADER_FILE, GL_FRAGMENT_SHADER); ReflectionZ->bindAttribLocation(VERTICES, "in_Position"); ReflectionZ->bindAttribLocation(COLORS, "in_Color"); ReflectionZ->bindAttribLocation(TEXTURES, "in_Texcoord"); ReflectionZ->bindAttribLocation(NORMALS, "in_Normal"); ReflectionZ->linkShaderProgram(); UboId = glGetUniformBlockIndex(ReflectionZ->getProgramId(), "SharedMatrices"); //TODO: Use ShaderProgram glUniformBlockBinding(ReflectionZ->getProgramId(), UboId, UBO_BP); ReflectionO = new ShaderProgram(); ReflectionO->setProgramId(); ReflectionO->addShaderFromFile("../src/shaders/ReflectionOShader.glsl", GL_VERTEX_SHADER); ReflectionO->addShaderFromFile(FRAGMENT_SHADER_FILE, GL_FRAGMENT_SHADER); ReflectionO->bindAttribLocation(VERTICES, "in_Position"); ReflectionO->bindAttribLocation(COLORS, "in_Color"); ReflectionO->bindAttribLocation(TEXTURES, "in_Texcoord"); ReflectionO->bindAttribLocation(NORMALS, "in_Normal"); ReflectionO->linkShaderProgram(); UboId = glGetUniformBlockIndex(ReflectionO->getProgramId(), "SharedMatrices"); //TODO: Use ShaderProgram glUniformBlockBinding(ReflectionO->getProgramId(), UboId, UBO_BP); SimpleShader = new ShaderProgram(); SimpleShader->setProgramId(); SimpleShader->addShaderFromFile("../src/shaders/SimpleVertexShader.glsl", GL_VERTEX_SHADER); SimpleShader->addShaderFromFile("../src/shaders/SimpleFragmentShader.glsl", GL_FRAGMENT_SHADER); SimpleShader->bindAttribLocation(VERTICES, "in_Position"); SimpleShader->bindAttribLocation(COLORS, "in_Color"); SimpleShader->linkShaderProgram(); UboId = glGetUniformBlockIndex(SimpleShader->getProgramId(), "SharedMatrices"); //TODO: Use ShaderProgram glUniformBlockBinding(SimpleShader->getProgramId(), UboId, UBO_BP); checkOpenGLError("ERROR: Could not create shaders."); }
int downloadOpenGLDepth(unsigned short * depth , unsigned int x,unsigned int y,unsigned int width,unsigned int height,float depthScale) { double depth_bias=0.0; double depth_scale=1.0; glGetDoublev(GL_DEPTH_BIAS, &depth_bias); // Returns 0.0 glGetDoublev(GL_DEPTH_SCALE, &depth_scale); // Returns 1.0 if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"getOpenGLDepth() : Error getting depth bias/scale \n"); } float * zbuffer = (float *) malloc((width-x)*(height-y)*sizeof(float)); if (zbuffer==0) { fprintf(stderr,"Could not allocate a zbuffer to read depth\n"); return 0; } memset(zbuffer,0,(width-x)*(height-y)*sizeof(float)); glReadPixels(x, y, width, height, GL_DEPTH_COMPONENT, GL_FLOAT,zbuffer); //checkFrameGettersForError("Depth Getter"); /* Not sure I am calculating the correct depth here.. */ memset(depth,0 , (width-x)*(height-y)*2 ); GLint viewport[4]; GLdouble modelview[16]; GLdouble projection[16]; GLdouble posX, posY, posZ=0.0; glGetDoublev( GL_MODELVIEW_MATRIX, modelview ); glGetDoublev( GL_PROJECTION_MATRIX, projection ); glGetIntegerv( GL_VIEWPORT, viewport ); float scaleDepthTo = depthScale;// sceneGetDepthScalingPrameter(); unsigned int xp = 0, yp = 0; for (yp=0; yp<height; yp++) { for ( xp=0 ; xp<width; xp++) { float tmpF=zbuffer[yp*width+xp]; #if OPTIMIZE_DEPTH_EXTRACTION if (tmpF==0) { //Do nothing , fast path } else #endif // OPTIMIZE_DEPTH_EXTRACTION if (tmpF<depth_scale) { gluUnProject((double) xp , (double) yp, (double) tmpF , modelview, projection, viewport, &posX, &posY, &posZ); #if REAL_DEPTH tmpF = sqrt( (posX*posX) + (posY*posY) + (posZ*posZ) ) * scaleDepthTo; depth[(height-yp-1)*width+xp]=(unsigned short) tmpF; #if SCALE_REAL_DEPTH_OUTPUT depth[(height-yp-1)*width+xp]*=depthMemoryOutputScale; #endif // SCALE_REAL_DEPTH_OUTPUT #else depth[(height-yp-1)*width+xp]=(unsigned short) posZ * scaleDepthTo; #endif // REAL_DEPTH } } } if (zbuffer!=0) { free(zbuffer); zbuffer=0; } if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"OpenGL error after getOpenGLDepth() \n"); } return 1; }
int setupSceneCameraBeforeRendering(struct VirtualStream * scene) { int result = 0; if ( (scene!=0) && ( scene->modelViewMatrixDeclared ) ) { //Scene configuration overwrites local configuration glLoadMatrixd( scene->modelViewMatrix ); // we load a matrix of Doubles copy4x4DMatrix(scene->activeModelViewMatrix , scene->modelViewMatrix); if (scene->useCustomModelViewMatrix) { fprintf(stderr,"Please not that the model view matrix has been overwritten by the scene configuration parameter\n"); print4x4DMatrix("Scene declared modelview matrix", scene->modelViewMatrix , 0); } checkOpenGLError(__FILE__, __LINE__); result = 1; return 1; } if (scene->useCustomModelViewMatrix) { //We load the matrix produced by convertRodriguezAndTranslationToOpenGL4x4DMatrix copy4x4DMatrix(scene->activeModelViewMatrix , scene->customModelViewMatrix); glLoadMatrixd((const GLdouble*) scene->customModelViewMatrix); /* We flip our coordinate system so it comes straight glRotatef(90,-1.0,0,0); //TODO FIX THESE glScalef(1.0,1.0,-1.0); //These are now taken into account using scene files ( see SCALE_WORLD , MAP_ROTATIONS ) glRotatef(180,0.0,0,-1.0); checkOpenGLError(__FILE__, __LINE__); */ result = 1; } else // we create a modelview matrix on the fly by using the camera declared in trajectory parser { /* fprintf(stderr,"Using on the fly rotate/translate rot x,y,z ( %0.2f,%0.2f,%0.2f ) trans x,y,z, ( %0.2f,%0.2f,%0.2f ) \n", camera_angle_x,camera_angle_y,camera_angle_z, camera_pos_x,camera_pos_y,camera_pos_z ); */ create4x4CameraModelViewMatrixForRendering( scene->activeModelViewMatrix , //Rotation Component scene->cameraPose.angleX, scene->cameraPose.angleY, scene->cameraPose.angleZ, //Translation Component scene->cameraPose.posX, scene->cameraPose.posY, scene->cameraPose.posZ ); transpose4x4MatrixD(scene->activeModelViewMatrix); glLoadMatrixd(scene->activeModelViewMatrix); /* glLoadIdentity(); if (camera_angle_x!=0.0) { glRotatef(camera_angle_x,-1.0,0,0); }// Rotate around x if (camera_angle_y!=0.0) { glRotatef(camera_angle_y,0,-1.0,0); }// Rotate around y if (camera_angle_z!=0.0) { glRotatef(camera_angle_z,0,0,-1.0); }// Rotate around z glTranslatef(-camera_pos_x, -camera_pos_y, -camera_pos_z); checkOpenGLError(__FILE__, __LINE__); */ result = 1; } return result; }
int startOGLRendering() { if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"OpenGL error while initializing scene\n"); } glEnable(GL_DEPTH_TEST); /* enable depth buffering */ glDepthFunc(GL_LESS); /* pedantic, GL_LESS is the default */ glDepthMask(GL_TRUE); glClearDepth(1.0); /* pedantic, 1.0 is the default */ //HQ settings glEnable(GL_NORMALIZE); glShadeModel(GL_SMOOTH); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST); if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"OpenGL error while initializing HQ settings\n"); } /* frame buffer clears should be to black */ glClearColor(0.0, 0.0, 0.0, 0.0); /* set up projection transform */ glMatrixMode(GL_PROJECTION); updateProjectionMatrix(); if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"OpenGL error after updating projection matrix\n"); } /* establish initial viewport */ /* pedantic, full window size is default viewport */ #warning "GL_COLOR does not even exist" //glEnable(GL_COLOR); //if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"OpenGL error after enabling color \n"); } glEnable(GL_COLOR_MATERIAL); if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"OpenGL error after enabling color material\n"); } #if USE_LIGHTS glEnable(GL_LIGHT0); glEnable(GL_LIGHTING); if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"OpenGL error after enabling lighting\n"); } glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient); glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse); glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular); glLightfv(GL_LIGHT0, GL_POSITION, light_position); if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"OpenGL error after setting up lights\n"); } GLenum faces=GL_FRONT;//GL_FRONT_AND_BACK; glMaterialfv(faces, GL_AMBIENT, mat_ambient); glMaterialfv(faces, GL_DIFFUSE, mat_diffuse); glMaterialfv(faces, GL_SPECULAR, mat_specular); glMaterialfv(faces, GL_SHININESS, mat_shininess); // <- this was glMateriali if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"OpenGL error after setting up Front/Back lights\n"); } #else fprintf(stderr,"Please note that lighting is disabled via the USE_LIGHTS precompiler define\n"); #endif // USE_LIGHTS if ( ( selectedFragmentShader != 0) || ( selectedVertexShader != 0 ) ) { loadedShader = loadShader(selectedVertexShader,selectedFragmentShader); } //This is not needed -> :P glCullFace(GL_FRONT_AND_BACK); //Enable Culling if (doCulling) { glFrontFace(GL_CCW); //GL_CW / GL_CCW if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"OpenGL error glFrontFace(GL_CCW); \n"); } glCullFace(GL_BACK); if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"OpenGL error glCullFace(GL_BACK); \n"); } glEnable(GL_CULL_FACE); if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"OpenGL error glEnable(GL_CULL_FACE); \n"); } } }
void initScene() { print4x4FMatrix("modelViewMatrix",modelViewMatrix); int viewport[4]={0}; buildOpenGLProjectionForIntrinsics ( projectionMatrix , viewport , fx, fy, 0.0 , // SKEW windowWidth/2.0, windowHeight/2.0, windowWidth, windowHeight, near, far ); print4x4FMatrix("projectionMatrix",projectionMatrix); lightPosition[0]=2; lightPosition[1]=2; lightPosition[2]=2; //create4x4RotationMatrix(modelViewProjection , 30 , 1.0, 1.0 , 1.0 ); camera.pos[0]=0; camera.pos[1]=0; camera.pos[2]=-3; camera.angle[0]=0; camera.angle[1]=0; camera.angle[2]=0; camera.angle[3]=0; updateView(0); //generate and bind a VAO for the 3D axes glGenVertexArrays(1, &vao); checkOpenGLError(__FILE__, __LINE__); glBindVertexArray(vao); checkOpenGLError(__FILE__, __LINE__); //colorcube(); // Load shaders and use the resulting shader program #if USE_SIMPLE_SHADERS fprintf(stderr,GREEN "Loading simple shader set \n" NORMAL); program = LoadShaders( "simple.vert", "simple.frag" ); checkOpenGLError(__FILE__, __LINE__); #else fprintf(stderr,GREEN "Loading complex shader set \n" NORMAL); program = LoadShaders( "test.vert", "test.frag" ); checkOpenGLError(__FILE__, __LINE__); #endif // USE_SIMPLE_SHADERS glUseProgram( program ); checkOpenGLError(__FILE__, __LINE__); // Create and initialize a buffer object on the server side (GPU) glGenBuffers( 1, &buffer ); checkOpenGLError(__FILE__, __LINE__); glBindBuffer( GL_ARRAY_BUFFER, buffer ); checkOpenGLError(__FILE__, __LINE__); NumVertices=0; //pushObjectToBufferData( heartVertices , sizeof(heartVertices) , heartNormals , sizeof(heartNormals) , 0 , 0 ); //pushObjectToBufferData( cubeCoords , sizeof(cubeCoords) , cubeNormals , sizeof(cubeNormals) , 0 , 0 ); //pushObjectToBufferData( planeCoords , sizeof(planeCoords) , planeNormals , sizeof(planeNormals) , 0 , 0 ); pushObjectToBufferData( pyramidCoords , sizeof(pyramidCoords) , pyramidNormals , sizeof(pyramidNormals) , 0 , 0 ); lightPositionLocation = glGetUniformLocation( program, "lightPosition" ); checkOpenGLError(__FILE__, __LINE__); fogLocation = glGetUniformLocation( program, "fogColorAndScale" ); checkOpenGLError(__FILE__, __LINE__); lightColorLocation = glGetUniformLocation( program, "lightColor" ); checkOpenGLError(__FILE__, __LINE__); lightMaterialsLocation = glGetUniformLocation( program, "lightMaterials" ); checkOpenGLError(__FILE__, __LINE__); normalTransformationLocation = glGetUniformLocation(program, "normalTransformation"); checkOpenGLError(__FILE__, __LINE__); modelViewProjectionMatrixLocation = glGetUniformLocation(program, "modelViewProjection"); checkOpenGLError(__FILE__, __LINE__); modelViewMatrixLocation = glGetUniformLocation(program, "modelViewMatrix"); checkOpenGLError(__FILE__, __LINE__); updateView(1); glEnable( GL_DEPTH_TEST ); glClearColor( 0.0, 0.0, 0.0, 1.0 ); checkOpenGLError(__FILE__, __LINE__); // only one VAO can be bound at a time, so disable it to avoid altering it accidentally glBindVertexArray(0); checkOpenGLError(__FILE__, __LINE__); }
int main (int argc, const char * argv[]) { // initialise GLFW int running = GL_TRUE; if (!glfwInit()) { exit(EXIT_FAILURE); } glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 4); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2); glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwOpenWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, 1); GLFWvidmode mode; glfwGetDesktopMode(&mode); if( !glfwOpenWindow(windowWidth, windowHeight, mode.RedBits, mode.GreenBits, mode.BlueBits, 0, 32, 0, GLFW_WINDOW /* or GLFW_FULLSCREEN */) ) { glfwTerminate(); exit(EXIT_FAILURE); } glfwEnable(GLFW_MOUSE_CURSOR); glfwEnable(GLFW_KEY_REPEAT); // Ensure we can capture the escape key being pressed below glfwEnable( GLFW_STICKY_KEYS ); glfwSetMousePos(windowWidth/2, windowHeight/2); glfwSetWindowTitle("basic Cube with GUI"); //init GLEW and basic OpenGL information // VERY IMPORTANT OTHERWISE GLEW CANNOT HANDLE GL3 #ifdef USE_OPENGL32 glewExperimental = true; #endif glewInit(); std::cout<<"\nUsing GLEW "<<glewGetString(GLEW_VERSION)<<std::endl; if (GLEW_VERSION_3_2) { std::cout<<"Yay! OpenGL 3.2 is supported and GLSL 1.5!\n"<<std::endl; } if (glewIsSupported("GL_ARB_vertex_buffer_object")) std::cout<<"ARB VBO's are supported"<<std::endl; else if (glewIsSupported("GL_APPLE_vertex_buffer_object")) std::cout<<"APPLE VBO's are supported"<<std::endl; else std::cout<<"VBO's are not supported,program will not run!!!"<<std::endl; if (glewIsSupported("GL_ARB_vertex_array_object")) std::cout<<"ARB VAO's are supported\n"<<std::endl; else if (glewIsSupported("GL_APPLE_vertex_array_object"))//this is the name of the extension for GL2.1 in MacOSX std::cout<<"APPLE VAO's are supported\n"<<std::endl; else std::cout<<"VAO's are not supported, program will not run!!!\n"<<std::endl; std::cout<<"Vendor: "<<glGetString (GL_VENDOR)<<std::endl; std::cout<<"Renderer: "<<glGetString (GL_RENDERER)<<std::endl; std::cout<<"Version: "<<glGetString (GL_VERSION)<<std::endl; //init AntTweakBar TwInit(TW_OPENGL_CORE, NULL); //OpenGL 3.2 // Set GLFW event callbacks // - Redirect window size changes to the callback function WindowSizeCB glfwSetWindowSizeCallback(WindowSizeCB); // - Directly redirect GLFW mouse button events to AntTweakBar //glfwSetMouseButtonCallback((GLFWmousebuttonfun)TwEventMouseButtonGLFW); glfwSetMouseButtonCallback(OnMouseButton); // - Directly redirect GLFW mouse position events to AntTweakBar //glfwSetMousePosCallback((GLFWmouseposfun)TwEventMousePosGLFW); glfwSetMousePosCallback(OnMousePos); // - Directly redirect GLFW mouse wheel events to AntTweakBar //glfwSetMouseWheelCallback((GLFWmousewheelfun)TwEventMouseWheelGLFW); glfwSetMouseWheelCallback(OnMouseWheel); // - Directly redirect GLFW key events to AntTweakBar //glfwSetKeyCallback((GLFWkeyfun)TwEventKeyGLFW); glfwSetKeyCallback(OnKey); // - Directly redirect GLFW char events to AntTweakBar //glfwSetCharCallback((GLFWcharfun)TwEventCharGLFW); glfwSetCharCallback(OnChar); // Enable depth test glEnable(GL_DEPTH_TEST); // Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS); checkOpenGLError(__FILE__, __LINE__); // init Scene initScene(); //Create tweak bars GUI TwWindowSize(windowWidth, windowHeight); myBar = TwNewBar("myBar"); // Add 'wire' to 'bar': it is a modifable variable of type TW_TYPE_BOOL32 (32 bits boolean). Its key shortcut is [w]. TwAddVarRW(myBar, "wire", TW_TYPE_BOOL32, &wireFrame, " label='Wireframe mode' key=w help='Toggle wireframe display mode.' "); TwAddVarRW(myBar, "useglm", TW_TYPE_BOOL32, &UseGLMMatrices , " label='Use GLM' key=g help='Toggle using GLM for matrices.' "); TwAddVarRW(myBar, "autorotate", TW_TYPE_BOOL32, &autoRotate , " label='AutoRotate' key=r help='Toggle autorotation.' "); // Add 'bgColor' to 'bar': it is a modifable variable of type TW_TYPE_COLOR3F (3 floats color) //TwAddVarRW(myBar, "bgColor", TW_TYPE_COLOR4F, &bgColor, " label='Background color' "); TwAddVarRW(myBar, "bgColor", TW_TYPE_COLOR4F, glm::value_ptr(bgColor), " label='Background color' "); TwAddVarRW(myBar, "fx", TW_TYPE_FLOAT, &fx , " min=0 max=1000 step=0.5 "); TwAddVarRW(myBar, "fy", TW_TYPE_FLOAT, &fy , " min=0 max=1000 step=0.5 "); TwAddVarRW(myBar, "near", TW_TYPE_FLOAT, &near , " min=0 max=1000 step=0.5 "); TwAddVarRW(myBar, "far", TW_TYPE_FLOAT , &far , " min=0 max=1000 step=0.5 "); TwAddVarRW(myBar, "CameraX", TW_TYPE_FLOAT, &camera.pos[0] , " min=-60 max=60 step=0.1 "); TwAddVarRW(myBar, "CameraY", TW_TYPE_FLOAT, &camera.pos[1], " min=-60 max=60 step=0.1 "); TwAddVarRW(myBar, "CameraZ", TW_TYPE_FLOAT, &camera.pos[2], " min=-60 max=60 step=0.1 "); TwAddVarRW(myBar, "LookX", TW_TYPE_FLOAT, &cameraLookAt.pos[0] , " min=-60 max=60 step=0.1 "); TwAddVarRW(myBar, "LookY", TW_TYPE_FLOAT, &cameraLookAt.pos[1], " min=-60 max=60 step=0.1 "); TwAddVarRW(myBar, "LookZ", TW_TYPE_FLOAT, &cameraLookAt.pos[2], " min=-60 max=60 step=0.1 "); TwAddVarRW(myBar, "Camera Rotation", TW_TYPE_QUAT4F, &camera.angle, ""); TwAddVarRW(myBar, "LightX", TW_TYPE_FLOAT, &lightPosition[0] , " min=-20 max=30 step=0.5 "); TwAddVarRW(myBar, "LightY", TW_TYPE_FLOAT, &lightPosition[1] , " min=-20 max=30 step=0.5 "); TwAddVarRW(myBar, "LightZ", TW_TYPE_FLOAT, &lightPosition[2] , " min=-20 max=30 step=0.5 "); TwAddVarRW(myBar, "lightColor", TW_TYPE_COLOR4F, lightColor, " label='Light color ' "); TwAddVarRW(myBar, "MaterialAmbient", TW_TYPE_FLOAT, &lightMaterials[0] , " min=0 max=1.0 step=0.1 "); TwAddVarRW(myBar, "MaterialDiffuse", TW_TYPE_FLOAT, &lightMaterials[1] , " min=0 max=1.0 step=0.1 "); TwAddVarRW(myBar, "MaterialSpecular", TW_TYPE_FLOAT, &lightMaterials[2] , " min=0 max=1.0 step=0.1 "); TwAddVarRW(myBar, "fogColor", TW_TYPE_COLOR4F, fogColorAndScale, " label='Fog color and intensity' "); //TwDefine("myBar alwaystop=true "); // mybar is always on top //GLFW main loop while (running) { glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT ); glClearColor( bgColor.r,bgColor.g,bgColor.b,bgColor.a); checkOpenGLError(__FILE__, __LINE__); // call function to render our scene drawScene(); //restore FILL mode (we don't want the GUI to be drawn in 'wireframe') glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); checkOpenGLError(__FILE__, __LINE__); TwDraw(); checkOpenGLError(__FILE__, __LINE__); glfwSwapBuffers(); //check if ESC was pressed running=!glfwGetKey(GLFW_KEY_ESC) && glfwGetWindowParam(GLFW_OPENED); } //terminate AntTweakBar TwTerminate(); //cleanup VAO, VBO and shaders glDeleteBuffers(1,&buffer); glDeleteProgram(program); glDeleteVertexArrays(1,&vao); //close OpenGL window and terminate GLFW glfwTerminate(); exit(EXIT_SUCCESS); }
int drawAllSceneObjectsAtPositionsFromTrajectoryParser(struct VirtualStream * scene) { if (scene==0) { return 0; } if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"OpenGL error before calling drawAllObjectsAtPositionsFromTrajectoryParser\n"); } //unsigned int timestampToUse = scene->ticks*((unsigned int) 100/scene->rate); unsigned int timestampToUse = scene->timestampToUse; unsigned int i; for (i=1; i<scene->numberOfObjects; i++) { if (scene->object[i].numberOfFrames<=1) { scene->object[i].lastFrame = 0; } else { scene->object[i].lastFrame = scene->ticks % scene->object[i].numberOfFrames; } } doAllEventTriggers(timestampToUse); //This is actually the only visible console output.. if (scene->ticks%10==0) { fprintf(stderr,"\r%0.2f FPS - @ %0.2f sec ( %u ticks * %u microseconds [ rate %0.2f ] ) \r", scene->controls.lastFramerate, (float) timestampToUse/1000, scene->ticks, scene->controls.tickUSleepTime, scene->rate ); } //--------------------------------------------------- /* int viewport[4]; float modelview[16]; float projection[16]; glGetFloatv( GL_MODELVIEW_MATRIX, modelview ); glGetFloatv( GL_PROJECTION_MATRIX, projection ); glGetIntegerv( GL_VIEWPORT, viewport ); print4x4FMatrix("Projection",projection); print4x4FMatrix("ModelView",modelview);*/ int enableTransformedRendering=1; unsigned char noColor=0; float posStackA[7]={0}; float posStackB[7]={0}; float scaleX=1.0,scaleY=1.0,scaleZ=1.0; float R=1.0f , G=1.0f , B=0.0f , trans=0.0f; float * joints=0; //Object 0 is camera , so we draw object 1 To numberOfObjects-1 for (i=1; i<scene->numberOfObjects; i++) { unsigned int objectType_WhichModelToDraw = scene->objectTypes[scene->object[i].type].modelListArrayNumber; unsigned int numberOfBones = scene->objectTypes[scene->object[i].type].numberOfBones; if (objectType_WhichModelToDraw<modelStorage->currentNumberOfModels) { struct Model * mod = &modelStorage->models[objectType_WhichModelToDraw]; //fprintf(stderr,"Drawing model %u/%u ( %s ) \n",objectType_WhichModelToDraw ,modelStorage->currentNumberOfModels,mod->pathOfModel); float * pos = (float*) &posStackA; if (numberOfBones>0) { //The 4x4 Matrix per joint joints=(float *) malloc(sizeof(float) * numberOfBones * 16); //memset(joints,0,sizeof(float) * numberOfBones * 16); //Clear it .. //We initialize Identity Matrices everywhere.. unsigned int z; for (z=0; z<(numberOfBones); z++) { float * mat = &joints[16*z]; mat[0]=1.0; mat[1]=0.0; mat[2]=0.0; mat[3]=0.0; mat[4]=0.0; mat[5]=1.0; mat[6]=0.0; mat[7]=0.0; mat[8]=0.0; mat[9]=0.0; mat[10]=1.0; mat[11]=0.0; mat[12]=0.0; mat[13]=0.0; mat[14]=0.0; mat[15]=1.0; } } if ( calculateVirtualStreamPos(scene,i,timestampToUse,pos,joints,&scaleX,&scaleY,&scaleZ) ) { //This is a stupid way of passing stuff to be drawn R=1.0f; G=1.0f; B=1.0f; trans=0.0f; noColor=0; getObjectColorsTrans(scene,i,&R,&G,&B,&trans,&noColor); //fprintf(stderr,"Object %s should be RGB(%0.2f,%0.2f,%0.2f) , Transparency %0.2f , ColorDisabled %u\n",scene->object[i].name,R,G,B,trans,noColor); setModelColor(mod,&R,&G,&B,&trans,&noColor); mod->scaleX = scaleX;//scene->object[i].scale; mod->scaleY = scaleY;//scene->object[i].scale; mod->scaleZ = scaleZ;//scene->object[i].scale; mod->wireframe = scene->renderWireframe; mod->showSkeleton = scene->showSkeleton; mod->highlight = ( scene->selectedObject == i ); //fprintf(stderr,"Model %s is now RGB(%0.2f,%0.2f,%0.2f) , Transparency %0.2f , ColorDisabled %u\n",scene->object[i].name, mod->colorR, mod->colorG, mod->colorB, mod->transparency,mod->nocolor ); //fprintf(stderr,"Draw OBJ%u(%f %f %f , %f %f %f %f , trans %f )\n",i,pos[0],pos[1],pos[2],pos[3],pos[4],pos[5],pos[6],trans); if (scene->debug) { print3DPoint2DWindowPosition(i , pos[0],pos[1],pos[2] ); } if ( (modelHasASkinTransformation(mod,joints)) && (enableTransformedRendering) ) { //We need to do joint transforms before draw //fprintf(stderr,"Doing joint transforms..!\n"); struct TRI_Model triModelOut={0}; struct TRI_Model *triModelIn=(struct TRI_Model*) mod->modelInternalData; doModelTransform( &triModelOut , triModelIn , joints , numberOfBones , 1/*Autodetect default matrices for speedup*/ , 1/*Direct setting of matrices*/, 1/*Do Transforms, don't just calculate the matrices*/ , 0 /*Default joint convention*/ ); //fprintf(stderr,"TriOUT Indices %u , TriIN Indices %u \n",triModelOut.header.numberOfIndices,triModelIn->header.numberOfIndices); mod->modelInternalData = (void*) &triModelOut; // - - - - // pX pY pZ rX rY rZ if (! drawModelAt(mod,pos[0],pos[1],pos[2],pos[3],pos[4],pos[5],mod->rotationOrder) ) { fprintf(stderr,RED "Could not draw object %u , type %u \n" NORMAL ,i , objectType_WhichModelToDraw ); } // - - - - mod->modelInternalData = (void*) triModelIn; deallocInternalsOfModelTri(&triModelOut); } else { //Regular <fast> drawing of model // pX pY pZ rX rY rZ if (! drawModelAt(mod,pos[0],pos[1],pos[2],pos[3],pos[4],pos[5],mod->rotationOrder) ) { fprintf(stderr,RED "Could not draw object %u , type %u \n" NORMAL ,i , objectType_WhichModelToDraw ); } } scene->object[i].bbox2D[0] = mod->bbox2D[0]; scene->object[i].bbox2D[1] = mod->bbox2D[1]; scene->object[i].bbox2D[2] = mod->bbox2D[2]; scene->object[i].bbox2D[3] = mod->bbox2D[3]; } else { fprintf(stderr,YELLOW "Could not determine position of object %s (%u) , so not drawing it\n" NORMAL,scene->object[i].name,i); } if (joints!=0) { free(joints); joints=0; } if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"OpenGL error after drawing object %u \n",i); } } else { fprintf(stderr,YELLOW "Scene object %u/%u ( %s ) points to unallocated model %u/%u , cannot draw it\n" NORMAL,i,scene->numberOfObjects,scene->object[i].name , objectType_WhichModelToDraw , modelStorage->currentNumberOfModels ); } } drawAllConnectors(scene , timestampToUse , scaleX, scaleY, scaleZ); return 1; }
//! Creates a shader program object void Shader::create() { if((id = glCreateProgram()) == 0) checkOpenGLError(); }
// // Install our shader programs and tell GL to use them. // We also initialize the uniform variables. // void installShaders(void) { // // (1) Create shader objects // vertexShader = glCreateShader(GL_VERTEX_SHADER); fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); // // (2) Load source code into shader objects. // glShaderSource(vertexShader, 1, &vertexShaderSource, NULL); glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL); // // (3) Compile shaders. // glCompileShader(vertexShader); GLint success; glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success); if (!success) { GLchar infoLog[200]; GLint charsWritten; glGetShaderInfoLog(vertexShader, sizeof(infoLog), &charsWritten, infoLog); fprintf(stderr, "vertex shader info log:\n%s\n\n", infoLog); } checkOpenGLError(__LINE__); glCompileShader(fragmentShader); glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success); if (!success) { GLchar infoLog[200]; GLint charsWritten; glGetShaderInfoLog(fragmentShader, sizeof(infoLog), &charsWritten, infoLog); fprintf(stderr, "fragment shader info log:\n%s\n\n", infoLog); } checkOpenGLError(__LINE__); // // (4) Create program object and attach vertex and fragment shader. // program = glCreateProgram(); glAttachShader(program, vertexShader); glAttachShader(program, fragmentShader); checkOpenGLError(__LINE__); // // (5) Link program. // glLinkProgram(program); glGetProgramiv(program, GL_LINK_STATUS, &success); if (!success) { GLchar infoLog[200]; GLint charsWritten; glGetProgramInfoLog(program, sizeof(infoLog), &charsWritten, infoLog); fprintf(stderr, "program info log:\n%s\n\n", infoLog); } checkOpenGLError(__LINE__); // // (7) // vertexPositionAttr = glGetAttribLocation(program, "vertexPosition"); if (vertexPositionAttr == -1) { fprintf(stderr, "Error fetching vertex position attribute!\n"); exit(-1); } // // (8) Fetch handles for uniform variables in program. // None, using built-ins. // ModelViewProjectionUniform = glGetUniformLocation(program, "ModelViewProjection"); ColorUniform = glGetUniformLocation(program,"Color"); // // (9) Tell GL to use our program // glUseProgram(program); }
// Create, compile and link program. void ShaderProgram::createCompileLink() { m_programName = glCreateProgram(); for (std::map<GLenum, Shader *>::iterator it = m_shaders.begin(); it != m_shaders.end(); ++it) { (it->second)->createShader(); glAttachShader(m_programName,(it->second)->shaderName()); } checkOpenGLError("Error attaching shaders."); bool shaderCompilationFailed = false; for (std::map<GLenum, Shader *>::iterator it = m_shaders.begin(); it != m_shaders.end(); ++it) { GLint compileStatus = (it->second)->compile(); if (compileStatus == GL_FALSE){ shaderCompilationFailed = true; displayShaderCompileLog("Shader compilation failed", *(it->second)); } } checkOpenGLError("Error compiling shaders."); // fail if some compilation failed if (shaderCompilationFailed) std::cout << "ERROR: Shader compilation failed" << std::endl; // "bind" vertex attribute channels for (auto& attrib : m_attribs){ glBindAttribLocation(m_programName, attrib.second.index, attrib.second.name.c_str()); } checkOpenGLError("Error binding attrib locations."); // link program and check for errors GLint linkResult = linkProgram(); if (linkResult == GL_FALSE) { displayProgramLinkingLog("Shader Program linking failed"); } // get uniform ids for (std::map<std::string, UniformData>::iterator it = m_uniforms.begin(); it != m_uniforms.end(); ++it) { const std::string &uniName = it->second.name; GLint loc = glGetUniformLocation(m_programName, uniName.c_str()); it->second.id = loc; if (loc == -1) { std::cerr << "[Warning] Uniform not found: '" << uniName << "'" << std::endl; } } checkOpenGLError("Error getting unfiorm locations."); // bind uniform blocks (the buffer still needs to be assigned to the same bind point) for (std::map<std::string, UniformBlockData>::iterator it = m_uniformBlocks.begin(); it != m_uniformBlocks.end(); ++it) { const std::string &blockName = it->second.name; GLuint blockIndex = glGetUniformBlockIndex(m_programName, blockName.c_str()); glUniformBlockBinding(m_programName, blockIndex, it->second.bindPoint); } checkOpenGLError("Error binding uniform blocks."); }