/** * Method for create a window */ void Visualizer::createWindow(const char * title) { xnew=0; ynew=0; znew=0; /* actual position */ xold=0; yold=0; zold=0; /* old position */ xx1=0; yy1=0; zz1=0; /* mouse position*/ mouseState=0; /* mouse button state */ xshift=0; yshift=0; /* shifting in space*/ xnew=0; ynew=0; znew=0; /* actual position */ xold=0; yold=0; zold=0; /* old position */ xx1=0; yy1=0; zz1=0; /* mouse position*/ mouseState=0; /* mouse button state */ xshift=0; yshift=0; /* shifting in space*/ fov=45.0; /* field of view */ near_plane=1; /* trim plain */ far_plane=1000.0; /* farther trim plain */ line_width=1.0; /* width of line */ WindowWidth=1024; /* width and height of window */ WindowHeight=768; ObjectType=0; /* type of paint object */ Solid=1; /* fill or wireframe model */ char * dummy_argv[1]; dummy_argv[0] = const_cast<char *>("run"); int dummy_argc = 1; glutInit(&dummy_argc, dummy_argv); glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH | GLUT_MULTISAMPLE ); /* graphic mod of window */ glutInitWindowSize(WindowWidth,WindowHeight); /* original window size */ glutInitWindowPosition(10,10); /* original window position */ glutCreateWindow(title); /* create window */ glutDisplayFunc(onDisplay); /* set function for redisplay */ glutReshapeFunc(onReshape); /* set function for change of size window */ glutKeyboardFunc(onKeyboard); /* set function for press key */ glutSpecialFunc(onSpecial); glutMouseFunc(onMouseClick); /* set function for press mouse button */ glutMotionFunc(onMouseMotion); /* set function for mouse move */ glClearColor(0.0, 0.0, 0.0, 0.0); /* color for clearing of color-buffer */ glClearDepth(1.0f); /* color for clearing of z-buffer */ glEnable(GL_DEPTH_TEST); /* configure function for testing value in z-buffer */ glDepthFunc(GL_LESS); /* select function */ glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); /* improvement display */ glEnable(GL_CULL_FACE); glPolygonMode(GL_FRONT, GL_FILL); /* configure draw of fill polygons */ //glCullFace(GL_FRONT); glLineWidth(line_width); /* line width */ glPointSize(line_width); //glEnable(GL_MULTISAMPLE); #ifdef FREEGLUT #ifdef GLUT_AUX int *sampleNumbers = NULL; int sampleNumbersSize = 0; sampleNumbers = glutGetModeValues(GLUT_MULTISAMPLE, &sampleNumbersSize); if(sampleNumbers != NULL) { glutSetOption(GLUT_MULTISAMPLE, sampleNumbers[sampleNumbersSize - 1]); printf("Multisampling with %i samples.\n", sampleNumbers[sampleNumbersSize - 1]); free(sampleNumbers); } else { printf("Multisampling is not available.\n"); } #endif #endif scene_ = glGenLists(1); /* get number of calllist */ createCallList(); /* initialization */ glutMainLoop(); }
void GraphicsWindow::Paint(void) { int i; havePainted = true; int w, h; GetGraphicsWindowSize(&w, &h); width = w; height = h; glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glScaled(scale*2.0/w, scale*2.0/h, scale*1.0/30000); double mat[16]; // Last thing before display is to apply the perspective double clp = SS.CameraTangent()*scale; MakeMatrix(mat, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, clp, 1); glMultMatrixd(mat); // Before that, we apply the rotation Vector n = projUp.Cross(projRight); MakeMatrix(mat, projRight.x, projRight.y, projRight.z, 0, projUp.x, projUp.y, projUp.z, 0, n.x, n.y, n.z, 0, 0, 0, 0, 1); glMultMatrixd(mat); // And before that, the translation MakeMatrix(mat, 1, 0, 0, offset.x, 0, 1, 0, offset.y, 0, 0, 1, offset.z, 0, 0, 0, 1); glMultMatrixd(mat); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glShadeModel(GL_SMOOTH); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); glEnable(GL_LINE_SMOOTH); // don't enable GL_POLYGON_SMOOTH; that looks ugly on some graphics cards, // drawn with leaks in the mesh glEnable(GL_POLYGON_OFFSET_LINE); glEnable(GL_POLYGON_OFFSET_FILL); glEnable(GL_DEPTH_TEST); glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); glEnable(GL_NORMALIZE); // At the same depth, we want later lines drawn over earlier. glDepthFunc(GL_LEQUAL); if(SS.AllGroupsOkay()) { glClearColor(REDf(SS.backgroundColor), GREENf(SS.backgroundColor), BLUEf(SS.backgroundColor), 1.0f); } else { // Draw a different background whenever we're having solve problems. DWORD rgb = Style::Color(Style::DRAW_ERROR); glClearColor(0.4f*REDf(rgb), 0.4f*GREENf(rgb), 0.4f*BLUEf(rgb), 1.0f); // And show the text window, which has info to debug it ForceTextWindowShown(); } glClear(GL_COLOR_BUFFER_BIT); glClearDepth(1.0); glClear(GL_DEPTH_BUFFER_BIT); if(SS.bgImage.fromFile) { // If a background image is loaded, then we draw it now as a texture. // This handles the resizing for us nicely. glBindTexture(GL_TEXTURE_2D, TEXTURE_BACKGROUND_IMG); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, SS.bgImage.rw, SS.bgImage.rh, 0, GL_RGB, GL_UNSIGNED_BYTE, SS.bgImage.fromFile); double tw = ((double)SS.bgImage.w) / SS.bgImage.rw, th = ((double)SS.bgImage.h) / SS.bgImage.rh; double mmw = SS.bgImage.w / SS.bgImage.scale, mmh = SS.bgImage.h / SS.bgImage.scale; Vector origin = SS.bgImage.origin; origin = origin.DotInToCsys(projRight, projUp, n); // Place the depth of our origin at the point that corresponds to // w = 1, so that it's unaffected by perspective. origin.z = (offset.ScaledBy(-1)).Dot(n); origin = origin.ScaleOutOfCsys(projRight, projUp, n); // Place the background at the very back of the Z order, though, by // mucking with the depth range. glDepthRange(1, 1); glEnable(GL_TEXTURE_2D); glBegin(GL_QUADS); glTexCoord2d(0, 0); glxVertex3v(origin); glTexCoord2d(0, th); glxVertex3v(origin.Plus(projUp.ScaledBy(mmh))); glTexCoord2d(tw, th); glxVertex3v(origin.Plus(projRight.ScaledBy(mmw).Plus( projUp. ScaledBy(mmh)))); glTexCoord2d(tw, 0); glxVertex3v(origin.Plus(projRight.ScaledBy(mmw))); glEnd(); glDisable(GL_TEXTURE_2D); } glxDepthRangeOffset(0); // Nasty case when we're reloading the imported files; could be that // we get an error, so a dialog pops up, and a message loop starts, and // we have to get called to paint ourselves. If the sketch is screwed // up, then we could trigger an oops trying to draw. if(!SS.allConsistent) return; // Let's use two lights, at the user-specified locations GLfloat f; glEnable(GL_LIGHT0); f = (GLfloat)SS.lightIntensity[0]; GLfloat li0[] = { f, f, f, 1.0f }; glLightfv(GL_LIGHT0, GL_DIFFUSE, li0); glLightfv(GL_LIGHT0, GL_SPECULAR, li0); glEnable(GL_LIGHT1); f = (GLfloat)SS.lightIntensity[1]; GLfloat li1[] = { f, f, f, 1.0f }; glLightfv(GL_LIGHT1, GL_DIFFUSE, li1); glLightfv(GL_LIGHT1, GL_SPECULAR, li1); Vector ld; ld = VectorFromProjs(SS.lightDir[0]); GLfloat ld0[4] = { (GLfloat)ld.x, (GLfloat)ld.y, (GLfloat)ld.z, 0 }; glLightfv(GL_LIGHT0, GL_POSITION, ld0); ld = VectorFromProjs(SS.lightDir[1]); GLfloat ld1[4] = { (GLfloat)ld.x, (GLfloat)ld.y, (GLfloat)ld.z, 0 }; glLightfv(GL_LIGHT1, GL_POSITION, ld1); if(SS.drawBackFaces) { // For debugging, draw the backs of the triangles in red, so that we // notice when a shell is open glLightModelf(GL_LIGHT_MODEL_TWO_SIDE, 1); } else { glLightModelf(GL_LIGHT_MODEL_TWO_SIDE, 0); } GLfloat ambient[4] = { (float)SS.ambientIntensity, (float)SS.ambientIntensity, (float)SS.ambientIntensity, 1 }; glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient); glxUnlockColor(); if(showSnapGrid && LockedInWorkplane()) { hEntity he = ActiveWorkplane(); EntityBase *wrkpl = SK.GetEntity(he), *norm = wrkpl->Normal(); Vector wu, wv, wn, wp; wp = SK.GetEntity(wrkpl->point[0])->PointGetNum(); wu = norm->NormalU(); wv = norm->NormalV(); wn = norm->NormalN(); double g = SS.gridSpacing; double umin = VERY_POSITIVE, umax = VERY_NEGATIVE, vmin = VERY_POSITIVE, vmax = VERY_NEGATIVE; int a; for(a = 0; a < 4; a++) { // Ideally, we would just do +/- half the width and height; but // allow some extra slop for rounding. Vector horiz = projRight.ScaledBy((0.6*width)/scale + 2*g), vert = projUp. ScaledBy((0.6*height)/scale + 2*g); if(a == 2 || a == 3) horiz = horiz.ScaledBy(-1); if(a == 1 || a == 3) vert = vert. ScaledBy(-1); Vector tp = horiz.Plus(vert).Minus(offset); // Project the point into our grid plane, normal to the screen // (not to the grid plane). If the plane is on edge then this is // impossible so don't try to draw the grid. bool parallel; Vector tpp = Vector::AtIntersectionOfPlaneAndLine( wn, wn.Dot(wp), tp, tp.Plus(n), ¶llel); if(parallel) goto nogrid; tpp = tpp.Minus(wp); double uu = tpp.Dot(wu), vv = tpp.Dot(wv); umin = min(uu, umin); umax = max(uu, umax); vmin = min(vv, vmin); vmax = max(vv, vmax); } int i, j, i0, i1, j0, j1; i0 = (int)(umin / g); i1 = (int)(umax / g); j0 = (int)(vmin / g); j1 = (int)(vmax / g); if(i0 > i1 || i1 - i0 > 400) goto nogrid; if(j0 > j1 || j1 - j0 > 400) goto nogrid; glLineWidth(1); glxColorRGBa(Style::Color(Style::DATUM), 0.3); glBegin(GL_LINES); for(i = i0 + 1; i < i1; i++) { glxVertex3v(wp.Plus(wu.ScaledBy(i*g)).Plus(wv.ScaledBy(j0*g))); glxVertex3v(wp.Plus(wu.ScaledBy(i*g)).Plus(wv.ScaledBy(j1*g))); } for(j = j0 + 1; j < j1; j++) { glxVertex3v(wp.Plus(wu.ScaledBy(i0*g)).Plus(wv.ScaledBy(j*g))); glxVertex3v(wp.Plus(wu.ScaledBy(i1*g)).Plus(wv.ScaledBy(j*g))); } glEnd(); // Clear the depth buffer, so that the grid is at the very back of // the Z order. glClear(GL_DEPTH_BUFFER_BIT); nogrid:; } // Draw the active group; this does stuff like the mesh and edges. (SK.GetGroup(activeGroup))->Draw(); // Now draw the entities if(showHdnLines) glDisable(GL_DEPTH_TEST); Entity::DrawAll(); // Draw filled paths in all groups, when those filled paths were requested // specially by assigning a style with a fill color, or when the filled // paths are just being filled by default. This should go last, to make // the transparency work. Group *g; for(g = SK.group.First(); g; g = SK.group.NextAfter(g)) { if(!(g->IsVisible())) continue; g->DrawFilledPaths(); } glDisable(GL_DEPTH_TEST); // Draw the constraints for(i = 0; i < SK.constraint.n; i++) { SK.constraint.elem[i].Draw(); } // Draw the traced path, if one exists glLineWidth(Style::Width(Style::ANALYZE)); glxColorRGB(Style::Color(Style::ANALYZE)); SContour *sc = &(SS.traced.path); glBegin(GL_LINE_STRIP); for(i = 0; i < sc->l.n; i++) { glxVertex3v(sc->l.elem[i].p); } glEnd(); // And the naked edges, if the user did Analyze -> Show Naked Edges. glLineWidth(Style::Width(Style::DRAW_ERROR)); glxColorRGB(Style::Color(Style::DRAW_ERROR)); glxDrawEdges(&(SS.nakedEdges), true); // Then redraw whatever the mouse is hovering over, highlighted. glDisable(GL_DEPTH_TEST); glxLockColorTo(Style::Color(Style::HOVERED)); hover.Draw(); // And finally draw the selection, same mechanism. glxLockColorTo(Style::Color(Style::SELECTED)); for(Selection *s = selection.First(); s; s = selection.NextAfter(s)) { s->Draw(); } glxUnlockColor(); // If a marquee selection is in progress, then draw the selection // rectangle, as an outline and a transparent fill. if(pending.operation == DRAGGING_MARQUEE) { Point2d begin = ProjectPoint(orig.marqueePoint); double xmin = min(orig.mouse.x, begin.x), xmax = max(orig.mouse.x, begin.x), ymin = min(orig.mouse.y, begin.y), ymax = max(orig.mouse.y, begin.y); Vector tl = UnProjectPoint(Point2d::From(xmin, ymin)), tr = UnProjectPoint(Point2d::From(xmax, ymin)), br = UnProjectPoint(Point2d::From(xmax, ymax)), bl = UnProjectPoint(Point2d::From(xmin, ymax)); glLineWidth((GLfloat)1.3); glxColorRGB(Style::Color(Style::HOVERED)); glBegin(GL_LINE_LOOP); glxVertex3v(tl); glxVertex3v(tr); glxVertex3v(br); glxVertex3v(bl); glEnd(); glxColorRGBa(Style::Color(Style::HOVERED), 0.10); glBegin(GL_QUADS); glxVertex3v(tl); glxVertex3v(tr); glxVertex3v(br); glxVertex3v(bl); glEnd(); } // An extra line, used to indicate the origin when rotating within the // plane of the monitor. if(SS.extraLine.draw) { glLineWidth(1); glxLockColorTo(Style::Color(Style::DATUM)); glBegin(GL_LINES); glxVertex3v(SS.extraLine.ptA); glxVertex3v(SS.extraLine.ptB); glEnd(); } // A note to indicate the origin in the just-exported file. if(SS.justExportedInfo.draw) { glxColorRGB(Style::Color(Style::DATUM)); Vector p = SS.justExportedInfo.pt, u = SS.justExportedInfo.u, v = SS.justExportedInfo.v; glLineWidth(1.5); glBegin(GL_LINES); glxVertex3v(p.Plus(u.WithMagnitude(-15/scale))); glxVertex3v(p.Plus(u.WithMagnitude(30/scale))); glxVertex3v(p.Plus(v.WithMagnitude(-15/scale))); glxVertex3v(p.Plus(v.WithMagnitude(30/scale))); glEnd(); glxWriteText("(x, y) = (0, 0) for file just exported", DEFAULT_TEXT_HEIGHT, p.Plus(u.ScaledBy(10/scale)).Plus(v.ScaledBy(10/scale)), u, v, NULL, NULL); glxWriteText("press Esc to clear this message", DEFAULT_TEXT_HEIGHT, p.Plus(u.ScaledBy(40/scale)).Plus( v.ScaledBy(-(DEFAULT_TEXT_HEIGHT)/scale)), u, v, NULL, NULL); } // And finally the toolbar. if(SS.showToolbar) { ToolbarDraw(); } }
/** * This function does any needed initialization on the rendering context. * This is the first opportunity to do any OpenGL related tasks. */ void SetupRC() { // Blue background glClearColor(0.0f, 0.0f, 1.0f, 1.0f ); shaderManager.init(); glEnable(GL_DEPTH_TEST); gltCreateCylinder(bckgrndCylBatch, 4.0f, 4.0f, 5.2f, 1024, 1); gltCreateDisk(diskBatch, 0.0f, 1.5f, 40, 10); glass1Batch.begin(GL_TRIANGLE_FAN, 4, 1); glass1Batch.Vertex3f(-1.0f, -1.0f, 0.0f); glass1Batch.Vertex3f(1.0f, -1.0f, 0.0f); glass1Batch.Vertex3f(1.0f, 1.0f, 0.0f); glass1Batch.Vertex3f(-1.0f, 1.0f, 0.0f); glass1Batch.end(); glass2Batch.begin(GL_TRIANGLE_FAN, 4, 1); glass2Batch.Vertex3f(0.0f, 1.0f, 0.0f); glass2Batch.Vertex3f(1.0f, 0.0f, 0.0f); glass2Batch.Vertex3f(0.0f, -1.0f, 0.0f); glass2Batch.Vertex3f(-1.0f, 0.0f, 0.0f); glass2Batch.end(); glass3Batch.begin(GL_TRIANGLE_FAN, 3, 1); glass3Batch.Vertex3f(0.0f, 1.0f, 0.0f); glass3Batch.Vertex3f(1.0f, -1.0f, 0.0f); glass3Batch.Vertex3f(-1.0f, -1.0f, 0.0f); glass3Batch.end(); glass4Batch.begin(GL_TRIANGLE_FAN, 4, 1); glass4Batch.Vertex3f(-1.0f, 1.0f, 0.0f); glass4Batch.Vertex3f(1.0f, 0.5f, 0.0f); glass4Batch.Vertex3f(1.0f, -1.0f, 0.0f); glass4Batch.Vertex3f(-1.0f, -0.5f, 0.0f); glass4Batch.end(); glGenTextures(2, textures); glBindTexture(GL_TEXTURE_2D, textures[0]); gltLoadTextureBMP("marble.bmp", GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR, GL_REPEAT); glBindTexture(GL_TEXTURE_2D, textures[1]); gltLoadTextureBMP("start_line.bmp", GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR, GL_REPEAT); // create and bind an FBO glGenFramebuffers(1, &msFBO); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, msFBO); // create depth texture glGenTextures(1, &depthTextureName); glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, depthTextureName); glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, 8, GL_DEPTH_COMPONENT24, screenWidth, screenHeight, GL_FALSE); // setup HDR render texture glGenTextures(1, msTexture); glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, msTexture[0]); glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, 8, GL_RGBA8, screenWidth, screenHeight, GL_FALSE); // create and bind FBO glGenFramebuffers(1, &msFBO); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, msFBO); // attach texture to first color attachment and depth RBO glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, msTexture[0], 0); glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D_MULTISAMPLE, depthTextureName, 0); // reset framebuffer binding glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); // Load oit resolve shader oitResolve = gltLoadShaderWithFileEx("basic.vs", "oitResolve.fs", 3, GLT_ATTRIBUTE_VERTEX, "vVertex", GLT_ATTRIBUTE_NORMAL, "vNormal", GLT_ATTRIBUTE_TEXTURE0, "vTexCoord0"); glBindFragDataLocation(oitResolve, 0, "oColor"); glLinkProgram(oitResolve); // Load multisample resolve shader msResolve = gltLoadShaderWithFileEx("basic.vs", "msResolve.fs", 3, GLT_ATTRIBUTE_VERTEX, "vVertex", GLT_ATTRIBUTE_NORMAL, "vNormal", GLT_ATTRIBUTE_TEXTURE0, "vTexCoord0"); glBindFragDataLocation(msResolve, 0, "oColor"); glLinkProgram(msResolve); // Make sure all went well gltCheckErrors(oitResolve); gltCheckErrors(msResolve); int numMasks = 0; glGetIntegerv(GL_MAX_SAMPLE_MASK_WORDS, &numMasks); log("GL_MAX_SAMPLE_MASK_WORDS: %d", numMasks); }
void Render::RenderScene(Camera* pCamera, Scene* pScene, Texture* pRenderColor, Texture* pRenderDepth) { if(m_multiPass && m_pSlicedQuaxol && m_pOverdrawQuaxol && pRenderDepth && pRenderColor) { // 1st pass of color, depth to ([eyefbo,colorfbo], [eyedepth,depthfbo]) glDisable(GL_BLEND); glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GEQUAL, 0.2f); glDepthFunc(GL_LESS); glEnable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); WasGLErrorPlusPrint(); m_pSlicedQuaxol->StartUsing(); // TODO: calc this from the block size and the w near and far // currently tuned for -40 near, 40 far, 10 blocksize static Vec4f sliceRange(0.456f, 0.556f, 0.0f, 0.0f); GLuint hSliceShaderRange = m_pSlicedQuaxol->getUniform("sliceRange"); if(hSliceShaderRange != -1) { glUniform4fv(hSliceShaderRange, 1, sliceRange.raw()); WasGLErrorPlusPrint(); } m_pSlicedQuaxol->StopUsing(); //float savedWnear = pCamera->_wNear; //float savedWfar = pCamera->_wFar; //float savedWratio = pCamera->_wScreenSizeRatio; //static float sliceAmount = 0.334f; //float wRange = pCamera->_wFar - pCamera->_wNear; //float wPreNear = (1.0f - sliceAmount) * 0.5f * wRange; //pCamera->SetWProjection(savedWnear + wPreNear, savedWfar - wPreNear, 1.0f /*ratio*/); pScene->RenderQuaxols(pCamera, m_pSlicedQuaxol); pScene->RenderGroundPlane(pCamera); //pCamera->SetWProjection(savedWnear, savedWfar, savedWratio); // 2nd pass of depth - offset <= color blend to (overdrawfbo) glBindFramebuffer(GL_FRAMEBUFFER, m_overdrawColor->m_framebuffer_id); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_overdrawColor->m_texture_id, 0); //glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, // GL_TEXTURE_2D, m_overdrawDepth->m_texture_id, 0); // waste? glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT); // good opportunity to do order independent alpha // but first the stupid way glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //glBlendFunc(GL_SRC_ALPHA, GL_ONE); glDisable(GL_ALPHA_TEST); glDisable(GL_DEPTH_TEST); glDepthFunc(GL_ALWAYS); glDepthMask(GL_FALSE); WasGLErrorPlusPrint(); m_pOverdrawQuaxol->StartUsing(); GLuint hOverdrawShaderRange = m_pOverdrawQuaxol->getUniform("sliceRange"); if(hOverdrawShaderRange != -1) { glUniform4fv(hOverdrawShaderRange, 1, sliceRange.raw()); } m_pOverdrawQuaxol->StopUsing(); GLint hDepthTex = m_pOverdrawQuaxol->getUniform("texDepth"); if(hDepthTex != -1) { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, pRenderDepth->GetTextureID()); WasGLErrorPlusPrint(); //glUniform1i(hDepthTex, 1); //WasGLErrorPlusPrint(); } pScene->RenderQuaxols(pCamera, m_pOverdrawQuaxol); //// 3rd additive fullscreen render overlay //// with capped blending to ([eyefbo,bb]) //RenderCompose(pCamera, pRenderColor, m_overdrawColor); // restore depth mask glDepthMask(GL_TRUE); } else { pScene->RenderEverything(pCamera); } }
void SetupRC(void) { glClearColor(1.0f,1.0f,1.0f,1.0f); }
void SetBackgroundColor(int r, int g, int b) /*****************************************************************************/ { glClearColor(r/255.0f, g/255.0f, b/255.0f, 0); }
void GLWidget3D::render() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); //////////////////////////////////////////////////////////////////////////////////////////////////////////////// // PASS 1: Render to texture glUseProgram(renderManager.programs["pass1"]); glBindFramebuffer(GL_FRAMEBUFFER, renderManager.fragDataFB); glClearColor(0.95, 0.95, 0.95, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, renderManager.fragDataTex[0], 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, renderManager.fragDataTex[1], 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, renderManager.fragDataTex[2], 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3, GL_TEXTURE_2D, renderManager.fragDataTex[3], 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, renderManager.fragDepthTex, 0); // Set the list of draw buffers. GLenum DrawBuffers[4] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 }; glDrawBuffers(4, DrawBuffers); // "3" is the size of DrawBuffers // Always check that our framebuffer is ok if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { printf("+ERROR: GL_FRAMEBUFFER_COMPLETE false\n"); exit(0); } glUniformMatrix4fv(glGetUniformLocation(renderManager.programs["pass1"], "mvpMatrix"), 1, false, &camera.mvpMatrix[0][0]); glUniform3f(glGetUniformLocation(renderManager.programs["pass1"], "lightDir"), light_dir.x, light_dir.y, light_dir.z); glUniformMatrix4fv(glGetUniformLocation(renderManager.programs["pass1"], "light_mvpMatrix"), 1, false, &light_mvpMatrix[0][0]); glUniform1i(glGetUniformLocation(renderManager.programs["pass1"], "shadowMap"), 6); glActiveTexture(GL_TEXTURE6); glBindTexture(GL_TEXTURE_2D, renderManager.shadow.textureDepth); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); drawScene(); //////////////////////////////////////////////////////////////////////////////////////////////////////////////// // PASS 2: Create AO if (renderManager.renderingMode == RenderManager::RENDERING_MODE_SSAO) { glUseProgram(renderManager.programs["ssao"]); glBindFramebuffer(GL_FRAMEBUFFER, renderManager.fragDataFB_AO); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, renderManager.fragAOTex, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, renderManager.fragDepthTex_AO, 0); GLenum DrawBuffers[1] = { GL_COLOR_ATTACHMENT0 }; glDrawBuffers(1, DrawBuffers); // "1" is the size of DrawBuffers glClearColor(1, 1, 1, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Always check that our framebuffer is ok if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { printf("++ERROR: GL_FRAMEBUFFER_COMPLETE false\n"); exit(0); } glDisable(GL_DEPTH_TEST); glDepthFunc(GL_ALWAYS); glUniform2f(glGetUniformLocation(renderManager.programs["ssao"], "pixelSize"), 2.0f / this->width(), 2.0f / this->height()); glUniform1i(glGetUniformLocation(renderManager.programs["ssao"], "tex0"), 1); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, renderManager.fragDataTex[0]); glUniform1i(glGetUniformLocation(renderManager.programs["ssao"], "tex1"), 2); glActiveTexture(GL_TEXTURE2); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, renderManager.fragDataTex[1]); glUniform1i(glGetUniformLocation(renderManager.programs["ssao"], "tex2"), 3); glActiveTexture(GL_TEXTURE3); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, renderManager.fragDataTex[2]); glUniform1i(glGetUniformLocation(renderManager.programs["ssao"], "depthTex"), 8); glActiveTexture(GL_TEXTURE8); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, renderManager.fragDepthTex); glUniform1i(glGetUniformLocation(renderManager.programs["ssao"], "noiseTex"), 7); glActiveTexture(GL_TEXTURE7); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, renderManager.fragNoiseTex); { glUniformMatrix4fv(glGetUniformLocation(renderManager.programs["ssao"], "mvpMatrix"), 1, false, &camera.mvpMatrix[0][0]); glUniformMatrix4fv(glGetUniformLocation(renderManager.programs["ssao"], "pMatrix"), 1, false, &camera.pMatrix[0][0]); } glUniform1i(glGetUniformLocation(renderManager.programs["ssao"], "uKernelSize"), renderManager.uKernelSize); glUniform3fv(glGetUniformLocation(renderManager.programs["ssao"], "uKernelOffsets"), renderManager.uKernelOffsets.size(), (const GLfloat*)renderManager.uKernelOffsets.data()); glUniform1f(glGetUniformLocation(renderManager.programs["ssao"], "uPower"), renderManager.uPower); glUniform1f(glGetUniformLocation(renderManager.programs["ssao"], "uRadius"), renderManager.uRadius); glBindVertexArray(renderManager.secondPassVAO); glDrawArrays(GL_QUADS, 0, 4); glBindVertexArray(0); glDepthFunc(GL_LEQUAL); } else if (renderManager.renderingMode == RenderManager::RENDERING_MODE_LINE || renderManager.renderingMode == RenderManager::RENDERING_MODE_HATCHING) { glUseProgram(renderManager.programs["line"]); glBindFramebuffer(GL_FRAMEBUFFER, 0); glClearColor(1, 1, 1, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDisable(GL_DEPTH_TEST); glDepthFunc(GL_ALWAYS); glUniform2f(glGetUniformLocation(renderManager.programs["line"], "pixelSize"), 1.0f / this->width(), 1.0f / this->height()); glUniformMatrix4fv(glGetUniformLocation(renderManager.programs["line"], "pMatrix"), 1, false, &camera.pMatrix[0][0]); if (renderManager.renderingMode == RenderManager::RENDERING_MODE_LINE) { glUniform1i(glGetUniformLocation(renderManager.programs["line"], "useHatching"), 0); } else { glUniform1i(glGetUniformLocation(renderManager.programs["line"], "useHatching"), 1); } glUniform1i(glGetUniformLocation(renderManager.programs["line"], "tex0"), 1); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, renderManager.fragDataTex[0]); glUniform1i(glGetUniformLocation(renderManager.programs["line"], "tex1"), 2); glActiveTexture(GL_TEXTURE2); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, renderManager.fragDataTex[1]); glUniform1i(glGetUniformLocation(renderManager.programs["line"], "tex2"), 3); glActiveTexture(GL_TEXTURE3); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, renderManager.fragDataTex[2]); glUniform1i(glGetUniformLocation(renderManager.programs["line"], "tex3"), 4); glActiveTexture(GL_TEXTURE4); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, renderManager.fragDataTex[3]); glUniform1i(glGetUniformLocation(renderManager.programs["line"], "depthTex"), 8); glActiveTexture(GL_TEXTURE8); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, renderManager.fragDepthTex); glUniform1i(glGetUniformLocation(renderManager.programs["line"], "hatchingTexture"), 5); glActiveTexture(GL_TEXTURE5); glBindTexture(GL_TEXTURE_3D, renderManager.hatchingTextures); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glBindVertexArray(renderManager.secondPassVAO); glDrawArrays(GL_QUADS, 0, 4); glBindVertexArray(0); glDepthFunc(GL_LEQUAL); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Blur if (renderManager.renderingMode != RenderManager::RENDERING_MODE_LINE && renderManager.renderingMode != RenderManager::RENDERING_MODE_HATCHING) { glBindFramebuffer(GL_FRAMEBUFFER, 0); qglClearColor(QColor(0xFF, 0xFF, 0xFF)); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDisable(GL_DEPTH_TEST); glDepthFunc(GL_ALWAYS); glUseProgram(renderManager.programs["blur"]); glUniform2f(glGetUniformLocation(renderManager.programs["blur"], "pixelSize"), 2.0f / this->width(), 2.0f / this->height()); //printf("pixelSize loc %d\n", glGetUniformLocation(vboRenderManager.programs["blur"], "pixelSize")); glUniform1i(glGetUniformLocation(renderManager.programs["blur"], "tex0"), 1);//COLOR glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, renderManager.fragDataTex[0]); glUniform1i(glGetUniformLocation(renderManager.programs["blur"], "tex1"), 2);//NORMAL glActiveTexture(GL_TEXTURE2); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, renderManager.fragDataTex[1]); /*glUniform1i(glGetUniformLocation(renderManager.programs["blur"], "tex2"), 3); glActiveTexture(GL_TEXTURE3); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, renderManager.fragDataTex[2]);*/ glUniform1i(glGetUniformLocation(renderManager.programs["blur"], "depthTex"), 8); glActiveTexture(GL_TEXTURE8); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, renderManager.fragDepthTex); glUniform1i(glGetUniformLocation(renderManager.programs["blur"], "tex3"), 4);//AO glActiveTexture(GL_TEXTURE4); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, renderManager.fragAOTex); if (renderManager.renderingMode == RenderManager::RENDERING_MODE_SSAO) { glUniform1i(glGetUniformLocation(renderManager.programs["blur"], "ssao_used"), 1); // ssao used } else { glUniform1i(glGetUniformLocation(renderManager.programs["blur"], "ssao_used"), 0); // no ssao } glBindVertexArray(renderManager.secondPassVAO); glDrawArrays(GL_QUADS, 0, 4); glBindVertexArray(0); glDepthFunc(GL_LEQUAL); } // REMOVE glActiveTexture(GL_TEXTURE0); }
int main () { /*--------------------------------START OPENGL---------------------------*/ assert (restart_gl_log ()); // start GL context and O/S window using the GLFW helper library assert (start_gl ()); glEnable (GL_DEPTH_TEST); // enable depth-testing // depth-testing interprets a smaller value as "closer" glDepthFunc (GL_LESS); glEnable (GL_CULL_FACE); // cull face glCullFace (GL_BACK); // cull back face // set counter-clock-wise vertex order to mean the front glFrontFace (GL_CCW); glClearColor (0.2, 0.2, 0.2, 1.0); // grey background to help spot mistakes glViewport (0, 0, g_gl_width, g_gl_height); /*------------------------------CREATE GEOMETRY------------------------------*/ GLfloat* vp = NULL; // array of vertex points GLfloat* vn = NULL; // array of vertex normals GLfloat* vt = NULL; // array of texture coordinates int g_point_count = 0; assert (load_obj_file (MESH_FILE, vp, vt, vn, g_point_count)); GLuint vao; glGenVertexArrays (1, &vao); glBindVertexArray (vao); GLuint points_vbo; if (NULL != vp) { glGenBuffers (1, &points_vbo); glBindBuffer (GL_ARRAY_BUFFER, points_vbo); glBufferData (GL_ARRAY_BUFFER, 3 * g_point_count * sizeof (GLfloat), vp, GL_STATIC_DRAW); glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, NULL); glEnableVertexAttribArray (0); } GLuint normals_vbo; if (NULL != vn) { glGenBuffers (1, &normals_vbo); glBindBuffer (GL_ARRAY_BUFFER, normals_vbo); glBufferData (GL_ARRAY_BUFFER, 3 * g_point_count * sizeof (GLfloat), vn, GL_STATIC_DRAW); glVertexAttribPointer (1, 3, GL_FLOAT, GL_FALSE, 0, NULL); glEnableVertexAttribArray (1); } GLuint texcoords_vbo; if (NULL != vp) { glGenBuffers (1, &texcoords_vbo); glBindBuffer (GL_ARRAY_BUFFER, texcoords_vbo); glBufferData (GL_ARRAY_BUFFER, 2 * g_point_count * sizeof (GLfloat), vp, GL_STATIC_DRAW); glVertexAttribPointer (2, 2, GL_FLOAT, GL_FALSE, 0, NULL); glEnableVertexAttribArray (2); } /*-------------------------------CREATE SHADERS------------------------------*/ GLuint shader_programme = create_programme_from_files (VERTEX_SHADER_FILE, FRAGMENT_SHADER_FILE); int view_mat_location = glGetUniformLocation (shader_programme, "view"); int proj_mat_location = glGetUniformLocation (shader_programme, "proj"); /* if converting to GLSL 410 do this to replace GLSL texture bindings: GLint diffuse_map_loc, specular_map_loc, ambient_map_loc, emission_map_loc; diffuse_map_loc = glGetUniformLocation (shader_programme, "diffuse_map"); specular_map_loc = glGetUniformLocation (shader_programme, "specular_map"); ambient_map_loc = glGetUniformLocation (shader_programme, "ambient_map"); emission_map_loc = glGetUniformLocation (shader_programme, "emission_map"); assert (diffuse_map_loc > -1); assert (specular_map_loc > -1); assert (ambient_map_loc > -1); assert (emission_map_loc > -1); glUseProgram (shader_programme); glUniform1i (diffuse_map_loc, 0); glUniform1i (specular_map_loc, 1); glUniform1i (ambient_map_loc, 2); glUniform1i (emission_map_loc, 3); */ // load texture GLuint tex_diff, tex_spec, tex_amb, tex_emiss; glActiveTexture (GL_TEXTURE0); assert (load_texture ("boulder_diff.png", &tex_diff)); glActiveTexture (GL_TEXTURE1); assert (load_texture ("boulder_spec.png", &tex_spec)); glActiveTexture (GL_TEXTURE2); assert (load_texture ("ao.png", &tex_amb)); glActiveTexture (GL_TEXTURE3); assert (load_texture ("tileable9b_emiss.png", &tex_emiss)); #define ONE_DEG_IN_RAD (2.0 * M_PI) / 360.0 // 0.017444444 // input variables float near = 0.1f; // clipping plane float far = 100.0f; // clipping plane float fov = 67.0f * ONE_DEG_IN_RAD; // convert 67 degrees to radians float aspect = (float)g_gl_width / (float)g_gl_height; // aspect ratio // matrix components float range = tan (fov * 0.5f) * near; float Sx = (2.0f * near) / (range * aspect + range * aspect); float Sy = near / range; float Sz = -(far + near) / (far - near); float Pz = -(2.0f * far * near) / (far - near); GLfloat proj_mat[] = { Sx, 0.0f, 0.0f, 0.0f, 0.0f, Sy, 0.0f, 0.0f, 0.0f, 0.0f, Sz, -1.0f, 0.0f, 0.0f, Pz, 0.0f }; float cam_speed = 1.0f; // 1 unit per second float cam_yaw_speed = 10.0f; // 10 degrees per second // don't start at zero, or we will be too close float cam_pos[] = {0.0f, 0.0f, 5.0f}; float cam_yaw = 0.0f; // y-rotation in degrees mat4 T = translate (identity_mat4 (), vec3 (-cam_pos[0], -cam_pos[1], -cam_pos[2])); mat4 R = rotate_y_deg (identity_mat4 (), -cam_yaw); mat4 view_mat = R * T; glUseProgram (shader_programme); glUniformMatrix4fv (view_mat_location, 1, GL_FALSE, view_mat.m); glUniformMatrix4fv (proj_mat_location, 1, GL_FALSE, proj_mat); while (!glfwWindowShouldClose (g_window)) { static double previous_seconds = glfwGetTime (); double current_seconds = glfwGetTime (); double elapsed_seconds = current_seconds - previous_seconds; previous_seconds = current_seconds; _update_fps_counter (g_window); // wipe the drawing surface clear glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glViewport (0, 0, g_gl_width, g_gl_height); glUseProgram (shader_programme); glBindVertexArray (vao); // draw points 0-3 from the currently bound VAO with current shader glDrawArrays (GL_TRIANGLES, 0, g_point_count); // update other events like input handling glfwPollEvents (); // control keys bool cam_moved = false; if (glfwGetKey (g_window, GLFW_KEY_A)) { cam_pos[0] -= cam_speed * elapsed_seconds; cam_moved = true; } if (glfwGetKey (g_window, GLFW_KEY_D)) { cam_pos[0] += cam_speed * elapsed_seconds; cam_moved = true; } if (glfwGetKey (g_window, GLFW_KEY_PAGE_UP)) { cam_pos[1] += cam_speed * elapsed_seconds; cam_moved = true; } if (glfwGetKey (g_window, GLFW_KEY_PAGE_DOWN)) { cam_pos[1] -= cam_speed * elapsed_seconds; cam_moved = true; } if (glfwGetKey (g_window, GLFW_KEY_W)) { cam_pos[2] -= cam_speed * elapsed_seconds; cam_moved = true; } if (glfwGetKey (g_window, GLFW_KEY_S)) { cam_pos[2] += cam_speed * elapsed_seconds; cam_moved = true; } if (glfwGetKey (g_window, GLFW_KEY_LEFT)) { cam_yaw += cam_yaw_speed * elapsed_seconds; cam_moved = true; } if (glfwGetKey (g_window, GLFW_KEY_RIGHT)) { cam_yaw -= cam_yaw_speed * elapsed_seconds; cam_moved = true; } // update view matrix if (cam_moved) { mat4 T = translate (identity_mat4 (), vec3 (-cam_pos[0], -cam_pos[1], -cam_pos[2])); // cam translation mat4 R = rotate_y_deg (identity_mat4 (), -cam_yaw); // mat4 view_mat = R * T; glUniformMatrix4fv (view_mat_location, 1, GL_FALSE, view_mat.m); } if (GLFW_PRESS == glfwGetKey (g_window, GLFW_KEY_ESCAPE)) { glfwSetWindowShouldClose (g_window, 1); } // put the stuff we've been drawing onto the display glfwSwapBuffers (g_window); } // close GL context and any other GLFW resources glfwTerminate(); return 0; }
void DisplayDeviceOpenGL::setClearColor(float r, float g, float b, float a) const { glClearColor(r, g, b, a); }
void CARenderImage::draw() { if( m_bAutoDraw) { begin(); if (m_uClearFlags) { GLfloat oldClearColor[4] = {0.0f}; GLfloat oldDepthClearValue = 0.0f; GLint oldStencilClearValue = 0; // backup and set if (m_uClearFlags & GL_COLOR_BUFFER_BIT) { glGetFloatv(GL_COLOR_CLEAR_VALUE, oldClearColor); glClearColor(m_sClearColor.r, m_sClearColor.g, m_sClearColor.b, m_sClearColor.a); } if (m_uClearFlags & GL_DEPTH_BUFFER_BIT) { glGetFloatv(GL_DEPTH_CLEAR_VALUE, &oldDepthClearValue); glClearDepth(m_fClearDepth); } if (m_uClearFlags & GL_STENCIL_BUFFER_BIT) { glGetIntegerv(GL_STENCIL_CLEAR_VALUE, &oldStencilClearValue); glClearStencil(m_nClearStencil); } // clear glClear(m_uClearFlags); // restore if (m_uClearFlags & GL_COLOR_BUFFER_BIT) { glClearColor(oldClearColor[0], oldClearColor[1], oldClearColor[2], oldClearColor[3]); } if (m_uClearFlags & GL_DEPTH_BUFFER_BIT) { glClearDepth(oldDepthClearValue); } if (m_uClearFlags & GL_STENCIL_BUFFER_BIT) { glClearStencil(oldStencilClearValue); } } //! make sure all children are drawn sortAllSubviews(); CAVector<CAView*>::const_iterator itr; for (itr=m_obSubviews.begin(); itr!=m_obSubviews.end(); itr++) { (*itr)->visit(); } end(); } }
/*!**************************************************************************** @Function InitView @Return bool true if no error occured @Description Code in InitView() will be called by PVRShell upon initialization or after a change in the rendering context. Used to initialize variables that are dependant on the rendering context (e.g. textures, vertex buffers, etc.) ******************************************************************************/ bool OGLESIntroducingPFX::InitView() { /* Initialize Print3D */ bool bRotate = PVRShellGet(prefIsRotated) && PVRShellGet(prefFullScreen); if(m_Print3D.SetTextures(0,PVRShellGet(prefWidth),PVRShellGet(prefHeight), bRotate) != PVR_SUCCESS) { PVRShellSet(prefExitMessage, "ERROR: Cannot initialise Print3D\n"); return false; } // Sets the clear color glClearColor(0.6f, 0.8f, 1.0f, 1.0f); // Enables depth test using the z-buffer glEnable(GL_DEPTH_TEST); /* Loads the light direction from the scene. */ // We check the scene contains at least one if (m_Scene.nNumLight == 0) { PVRShellSet(prefExitMessage, "ERROR: The scene does not contain a light\n"); return false; } /* Load the effect file */ { unsigned int nUnknownUniformCount; CPVRTString error; // Parse the file m_pEffectParser = new CPVRTPFXParser; if(m_pEffectParser->ParseFromFile(c_szPfxFile, &error) != PVR_SUCCESS) { PVRShellSet(prefExitMessage, error.c_str()); return false; } // Load an effect from the file m_pEffect = new CPVRTPFXEffect(); if(m_pEffect->Load(*m_pEffectParser, "Effect", c_szPfxFile, &error) != PVR_SUCCESS) { PVRShellSet(prefExitMessage, error.c_str()); return false; } // Generate uniform array if(m_pEffect->BuildUniformTable( &m_psUniforms, &m_nUniformCnt, &nUnknownUniformCount, c_psUniformSemantics, sizeof(c_psUniformSemantics) / sizeof(*c_psUniformSemantics), &error) != PVR_SUCCESS) { PVRShellOutputDebug(error.c_str()); return false; } if(nUnknownUniformCount) { PVRShellOutputDebug(error.c_str()); PVRShellOutputDebug("Unknown uniform semantic count: %d\n", nUnknownUniformCount); } } /* Loads the textures. For a more detailed explanation, see Texturing and IntroducingPVRTools */ { const SPVRTPFXTexture *psTex; unsigned int nCnt, i; GLuint ui; psTex = m_pEffect->GetTextureArray(nCnt); for(i = 0; i < nCnt; ++i) { if(strcmp(psTex[i].p, "Reflection.pvr") == 0) { if(PVRTTextureLoadFromPVR(c_szReflectTexFile, &ui) != PVR_SUCCESS) { PVRShellSet(prefExitMessage, "ERROR: Cannot load the texture\n"); return false; } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); m_pEffect->SetTexture(i, ui); } else if (strcmp(psTex[i].p, "Basetex.pvr") == 0) { if(PVRTTextureLoadFromPVR(c_szBaseTexFile, &ui) != PVR_SUCCESS) { PVRShellSet(prefExitMessage, "ERROR: Cannot load the texture\n"); return false; } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); m_pEffect->SetTexture(i, ui); } else { PVRShellOutputDebug("Warning: effect file requested unrecognised texture: \"%s\"\n", psTex[i].p); m_pEffect->SetTexture(i, 0); } } } // Create buffer objects. m_aiVboID = new GLuint[m_Scene.nNumMeshNode]; glGenBuffers(m_Scene.nNumMeshNode, m_aiVboID); for(int i = 0; i < (int)m_Scene.nNumMeshNode ; i++) { SPODNode* pNode = &m_Scene.pNode[i]; // Gets pMesh referenced by the pNode SPODMesh* pMesh = &m_Scene.pMesh[pNode->nIdx]; // Generate a vertex buffer and set the interleaved vertex data. glBindBuffer(GL_ARRAY_BUFFER, m_aiVboID[i]); glBufferData(GL_ARRAY_BUFFER, pMesh->sVertex.nStride*pMesh->nNumVertex, pMesh->pInterleaved, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); } return true; }
void NBodyWorldApp::draw(){ long tstart = getCPUticks(); glClearColor( 0.9f, 0.9f, 0.9f, 0.0f ); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); long t1 = getCPUticks(); world.update(); long t2 = getCPUticks(); Vec2d pa,pb,fout; pa.set(0.0,0.0); pb.set(0.0,0.0); int nsamp = 100; double dx = 4.0/nsamp; double ox = 0; double oy = 0; glColor3f( 0.9f, 0.2f, 0.2f ); ox=0; oy=0; for( int i=0; i<nsamp; i++ ){ pb.x = i * dx; pairwiseForce( pa, pb, -1, fout ); double x=pb.x*5;double y=-0.2*fout.x; Draw2D::drawLine_d( {ox,oy},{x,y} ); ox=x; oy=y; } glColor3f( 0.2f, 0.2f, 0.2f ); ox=0; oy=0; for( int i=0; i<nsamp; i++ ){ pb.x = i * dx; pairwiseForce( pa, pb, 0, fout ); double x=pb.x*5;double y=-0.2*fout.x; Draw2D::drawLine_d( {ox,oy},{x,y} ); ox=x; oy=y; } glColor3f( 0.2f, 0.2f, 0.9f ); ox=0; oy=0; for( int i=0; i<nsamp; i++ ){ pb.x = i * dx; pairwiseForce( pa, pb, +1, fout ); double x=pb.x*5;double y=-0.2*fout.x; Draw2D::drawLine_d( {ox,oy},{x,y} ); ox=x; oy=y; } glColor3f( 0.2f, 0.2f, 0.2f ); Draw2D::drawLine_d( {0.0,-10.0},{0.0,+10.0} ); Draw2D::drawLine_d( {-10.0,0.0},{+10.0,0.0} ); Particle2D* screenObjects[65536]; /* glColor3f( 0.2f, 0.2f, 0.2f ); for( int i=0; i<world.nParticles; i++ ){ Particle2D* pi = &(world.particles[i]); ULONG icell = world.map.getBucket( pi->pos.x, pi->pos.y ); double x,y; world.map.unfoldBucket( icell, x, y ); Draw2D::drawRectangle( (float)x, (float)y, (float)(x+world.map.step), (float)(y+world.map.step), false ); } */ glColor3f( 0.2f, 0.2f, 0.2f ); for( ULONG icell : world.activeCells ){ double x,y; world.map.unfoldBucket( icell, x, y ); Draw2D::drawRectangle( (float)x, (float)y, (float)(x+world.map.step), (float)(y+world.map.step), false ); /* UINT nfound = world.map.HashMap<Particle2D>::getBucketObjects( icell, screenObjects ); if( nfound <= 0 ){ UHALF ix,iy; world.map.unfoldBucketInt( icell, ix, iy ); printf( "!!! activeCell %i=(%i,%i) is empty\n", icell, ix, iy ); int i= 97; printf( "!!! particle %i-th (%3.3f,%3.3f) \n", i, world.particles[i].pos.x, world.particles[i].pos.y ); exit(0); } */ } glColor3f( 0.7f, 0.7f, 0.7f ); for( ULONG icell : world.activeCellsNeighbors ){ double x,y; world.map.unfoldBucket( icell, x, y ); Draw2D::drawRectangle( (float)x, (float)y, (float)(x+world.map.step), (float)(y+world.map.step), false ); } /* glColor3f( 0.9f, 0.9f, 0.9f ); for( int i=0; i<world.nActiveParticles; i++ ){ Draw2D::drawPointCross_d( world.activeParticles[i]->pos, 0.5 ); } */ //float camXmin_ =-1; float camXmax_ =+1; //float camYmin_ =-1; float camYmax_ =+1; float camXmin_ =camXmin; float camXmax_ =camXmax; float camYmin_ =camYmin; float camYmax_ =camYmax; /* Draw2D::drawRectangle( camXmin_, camYmin_, camXmax_, camYmax_, false ); UINT nfound = world.map.getObjectsInRect( camXmin_, camYmin_, camXmax_, camYmax_, &(screenObjects[0]) ); //glBegin(GL_POINTS); for( int i=0; i<nfound; i++ ){ Particle2D* p = screenObjects[i]; //glVertex3f( (float) p->pos.x, (float)p->pos.y, 1.0f ); Draw2D::drawCircle_d( p->pos, 0.25, 8, true ); } //glEnd(); printf( "nfound %i filled %i \n", nfound, world.map.filled ); */ UHALF ix0 = world.map.getIx( camXmin_ ); UHALF iy0 = world.map.getIy( camYmin_ ); UHALF ix1 = world.map.getIx( camXmax_ ); UHALF iy1 = world.map.getIy( camYmax_ ); UINT nfound_tot = 0; int ncells = 0; for( UHALF iy = iy0; iy<=iy1; iy++ ){ for( UHALF ix = ix0; ix<=ix1; ix++ ){ UINT nfoundi = world.map.getBucketObjectsInt( ix, iy, screenObjects ); nfound_tot += nfoundi; for( int i=0; i<nfoundi; i++ ){ Particle2D* p = screenObjects[i]; if( p->charge > 0 ){ glColor3f( 0.0f, 0.5f, 1.0f ); }else{ glColor3f( 1.0f, 0.5f, 0.0f ); } Draw2D::drawCircle_d( p->pos, 0.5, 8, true ); //Vec2d pos_f; pos_f.set_mul( p->force, 1.0 ); pos_f.add( p->pos ); //Draw2D::drawLine_d( p->pos, pos_f ); } /* if( nfoundi > 0 ){ glColor3f( 0.3f, 0.3f, 0.3f ); double x = world.map.getX(ix); double y = world.map.getY(iy); Draw2D::drawRectangle( (float)x, (float)y, (float)(x+world.map.step), (float)(y+world.map.step), false ); } */ //printf( " ix %i iy %i \n", ix, iy, ni ); } } Draw2D::drawPointCross_d( world.anchor, 0.5 ); if( world.picked != NULL ) Draw2D::drawLine_d( world.anchor, world.picked->pos ); long tend = getCPUticks(); //printf( " ======== frame %i DONE ( map.filled %i nfound_tot %i )\n", frameCount, world.map.filled, nfound_tot ); printf( " ======== frame %i DONE T=%3.3f Mticks/frame( %3.3f Mticks simulation )\n", frameCount, (tend-tstart)*1.0e-6, (t2-t1)*1.0e-6 ); //STOP = true; };
void render(void) { Rect r; //Clear the screen glClearColor(1.0, 1.0, 1.0, 1.0); glClear(GL_COLOR_BUFFER_BIT); // // //draw a quad with texture float wid = 120.0f; glColor3f(1.0, 1.0, 1.0); if (forest) { glBindTexture(GL_TEXTURE_2D, forestTexture); glBegin(GL_QUADS); glTexCoord2f(0.0f, 1.0f); glVertex2i(0, 0); glTexCoord2f(0.0f, 0.0f); glVertex2i(0, yres); glTexCoord2f(1.0f, 0.0f); glVertex2i(xres, yres); glTexCoord2f(1.0f, 1.0f); glVertex2i(xres, 0); glEnd(); } if (show_bigfoot) { glPushMatrix(); glTranslatef(bigfoot.pos[0], bigfoot.pos[1], bigfoot.pos[2]); if (!silhouette) { glBindTexture(GL_TEXTURE_2D, bigfootTexture); } else { glBindTexture(GL_TEXTURE_2D, silhouetteTexture); glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GREATER, 0.0f); glColor4ub(255,255,255,255); } glBegin(GL_QUADS); if (bigfoot.vel[0] > 0.0) { glTexCoord2f(0.0f, 1.0f); glVertex2i(-wid,-wid); glTexCoord2f(0.0f, 0.0f); glVertex2i(-wid, wid); glTexCoord2f(1.0f, 0.0f); glVertex2i( wid, wid); glTexCoord2f(1.0f, 1.0f); glVertex2i( wid,-wid); } else { glTexCoord2f(1.0f, 1.0f); glVertex2i(-wid,-wid); glTexCoord2f(1.0f, 0.0f); glVertex2i(-wid, wid); glTexCoord2f(0.0f, 0.0f); glVertex2i( wid, wid); glTexCoord2f(0.0f, 1.0f); glVertex2i( wid,-wid); } glEnd(); glPopMatrix(); // if (trees && silhouette) { glBindTexture(GL_TEXTURE_2D, forestTransTexture); glBegin(GL_QUADS); glTexCoord2f(0.0f, 1.0f); glVertex2i(0, 0); glTexCoord2f(0.0f, 0.0f); glVertex2i(0, yres); glTexCoord2f(1.0f, 0.0f); glVertex2i(xres, yres); glTexCoord2f(1.0f, 1.0f); glVertex2i(xres, 0); glEnd(); } glDisable(GL_ALPHA_TEST); } glDisable(GL_TEXTURE_2D); //glColor3f(1.0f, 0.0f, 0.0f); //glBegin(GL_QUADS); // glVertex2i(10,10); // glVertex2i(10,60); // glVertex2i(60,60); // glVertex2i(60,10); //glEnd(); //return; glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); if (show_rain) draw_raindrops(); glDisable(GL_BLEND); glEnable(GL_TEXTURE_2D); // #ifdef USE_UMBRELLA if (show_umbrella) draw_umbrella(); #endif //USE_UMBRELLA glBindTexture(GL_TEXTURE_2D, 0); // // r.bot = yres - 20; r.left = 10; r.center = 0; unsigned int cref = 0x00ffffff; ggprint8b(&r, 16, cref, "B - Bigfoot"); ggprint8b(&r, 16, cref, "F - Forest"); ggprint8b(&r, 16, cref, "S - Silhouette"); ggprint8b(&r, 16, cref, "T - Trees"); ggprint8b(&r, 16, cref, "U - Umbrella"); ggprint8b(&r, 16, cref, "R - Rain"); ggprint8b(&r, 16, cref, "D - Deflection"); ggprint8b(&r, 16, cref, "N - Sounds"); }
void init_opengl(void) { //OpenGL initialization glViewport(0, 0, xres, yres); //Initialize matrices glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //This sets 2D mode (no perspective) glOrtho(0, xres, 0, yres, -1, 1); glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); glDisable(GL_FOG); glDisable(GL_CULL_FACE); //Clear the screen glClearColor(1.0, 1.0, 1.0, 1.0); //glClear(GL_COLOR_BUFFER_BIT); //Do this to allow fonts glEnable(GL_TEXTURE_2D); initialize_fonts(); // //load the images file into a ppm structure. // bigfootImage = ppm6GetImage("./images/bigfoot.ppm"); forestImage = ppm6GetImage("./images/forest.ppm"); forestTransImage = ppm6GetImage("./images/forestTrans.ppm"); umbrellaImage = ppm6GetImage("./images/umbrella.ppm"); // //create opengl texture elements glGenTextures(1, &bigfootTexture); glGenTextures(1, &silhouetteTexture); glGenTextures(1, &forestTexture); glGenTextures(1, &umbrellaTexture); //------------------------------------------------------------------------- //bigfoot // int w = bigfootImage->width; int h = bigfootImage->height; // glBindTexture(GL_TEXTURE_2D, bigfootTexture); // glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, 3, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, bigfootImage->data); //------------------------------------------------------------------------- // //silhouette //this is similar to a sprite graphic // glBindTexture(GL_TEXTURE_2D, silhouetteTexture); // glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); // //must build a new set of data... unsigned char *silhouetteData = buildAlphaData(bigfootImage); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, silhouetteData); delete [] silhouetteData; //------------------------------------------------------------------------- // //umbrella // glBindTexture(GL_TEXTURE_2D, umbrellaTexture); // glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); // //must build a new set of data... silhouetteData = buildAlphaData(umbrellaImage); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, silhouetteData); delete [] silhouetteData; //------------------------------------------------------------------------- // //forest glBindTexture(GL_TEXTURE_2D, forestTexture); // glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, 3, forestImage->width, forestImage->height, 0, GL_RGB, GL_UNSIGNED_BYTE, forestImage->data); //------------------------------------------------------------------------- // //forest transparent part // glBindTexture(GL_TEXTURE_2D, forestTransTexture); // glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); // //must build a new set of data... w = forestTransImage->width; h = forestTransImage->height; unsigned char *ftData = buildAlphaData(forestTransImage); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, ftData); delete [] ftData; //------------------------------------------------------------------------- }
static void Init(ModeInfo *mi) { atlantisstruct *ap = &atlantis[MI_SCREEN(mi)]; static const float ambient[] = {0.1, 0.1, 0.1, 1.0}; static const float diffuse[] = {1.0, 1.0, 1.0, 1.0}; static const float position[] = {0.0, 1.0, 0.0, 0.0}; static const float mat_shininess[] = {90.0}; static const float mat_specular[] = {0.8, 0.8, 0.8, 1.0}; static const float mat_diffuse[] = {0.46, 0.66, 0.795, 1.0}; static const float mat_ambient[] = {0.0, 0.1, 0.2, 1.0}; static const float lmodel_ambient[] = {0.4, 0.4, 0.4, 1.0}; static const float lmodel_localviewer[] = {0.0}; float fblue = 0.0, fgreen; glFrontFace(GL_CCW); if (ap->wire) { glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glDisable(GL_LIGHTING); glDisable(GL_NORMALIZE); } else { glDepthFunc(GL_LEQUAL); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glEnable(GL_NORMALIZE); glShadeModel(GL_SMOOTH); glLightfv(GL_LIGHT0, GL_AMBIENT, ambient); glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse); glLightfv(GL_LIGHT0, GL_POSITION, position); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient); glLightModelfv(GL_LIGHT_MODEL_LOCAL_VIEWER, lmodel_localviewer); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shininess); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_diffuse); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, mat_ambient); } if (ap->wire || !do_texture) { glDisable(GL_TEXTURE_2D); } else { GLfloat scale = 0.0005; if (!ap->texture) parse_image_data (mi); clear_gl_error(); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ap->texture->width, ap->texture->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, ap->texture->data); check_gl_error("texture"); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); # ifndef HAVE_JWZGLES { GLfloat s_plane[] = { 1, 0, 0, 0 }; GLfloat t_plane[] = { 0, 0, 1, 0 }; glTexGeni (GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR); glTexGeni (GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR); glTexGenfv(GL_S, GL_EYE_PLANE, s_plane); glTexGenfv(GL_T, GL_EYE_PLANE, t_plane); glEnable(GL_TEXTURE_GEN_S); glEnable(GL_TEXTURE_GEN_T); } # endif glEnable(GL_TEXTURE_2D); glMatrixMode(GL_TEXTURE); glLoadIdentity(); glScalef(scale, scale, 1); glMatrixMode(GL_MODELVIEW); } InitFishs(ap); /* Add a little randomness */ fblue = ((float) (NRAND(30)) / 100.0) + 0.70; fgreen = fblue * 0.56; glClearColor(0.0, fgreen, fblue, 1.0); }
void DisplayDeviceOpenGL::setClearColor(const Color& color) const { glClearColor(float(color.r()), float(color.g()), float(color.b()), float(color.a())); }
int main(int argc, char *argv[]) { EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); assert(display != EGL_NO_DISPLAY); assert(eglGetError() == EGL_SUCCESS); EGLint major = 0, minor = 0; EGLBoolean ret = eglInitialize(display, &major, &minor); assert(eglGetError() == EGL_SUCCESS); assert(ret == EGL_TRUE); assert(major * 10000 + minor >= 10004); EGLint numConfigs; ret = eglGetConfigs(display, NULL, 0, &numConfigs); assert(eglGetError() == EGL_SUCCESS); assert(ret == EGL_TRUE); EGLint attribs[] = { EGL_RED_SIZE, 5, EGL_GREEN_SIZE, 6, EGL_BLUE_SIZE, 5, EGL_NONE }; EGLConfig config; ret = eglChooseConfig(display, attribs, &config, 1, &numConfigs); assert(eglGetError() == EGL_SUCCESS); assert(ret == EGL_TRUE); EGLNativeWindowType dummyWindow; EGLSurface surface = eglCreateWindowSurface(display, config, dummyWindow, NULL); assert(eglGetError() == EGL_SUCCESS); assert(surface != 0); // WebGL maps to GLES2. GLES1 is not supported. EGLint contextAttribsOld[] = { EGL_CONTEXT_CLIENT_VERSION, 1, EGL_NONE }; EGLContext context = eglCreateContext(display, config, NULL, contextAttribsOld); assert(eglGetError() != EGL_SUCCESS); //Test for invalid attribs EGLint contextInvalidAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, 0xFFFF, -1, EGL_NONE }; context = eglCreateContext(display, config, NULL, contextInvalidAttribs); assert(eglGetError() != EGL_SUCCESS); assert(context == 0); //Test for missing terminator EGLint contextAttribsMissingTerm[] = { EGL_CONTEXT_CLIENT_VERSION, 2, }; context = eglCreateContext(display, config, NULL, contextAttribsMissingTerm); assert(eglGetError() != EGL_SUCCESS); assert(context == 0); //Test for null terminator EGLint contextAttribsNullTerm[] = { EGL_CONTEXT_CLIENT_VERSION, 2, 0 }; context = eglCreateContext(display, config, NULL, contextAttribsNullTerm); assert(eglGetError() != EGL_SUCCESS); assert(context == 0); //Test for invalid and null terminator EGLint contextAttribsNullTermInvalid[] = { 0, }; context = eglCreateContext(display, config, NULL, contextAttribsNullTermInvalid); assert(eglGetError() != EGL_SUCCESS); assert(context == 0); // The correct attributes, should create a good EGL context EGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; context = eglCreateContext(display, config, NULL, contextAttribs); assert(eglGetError() == EGL_SUCCESS); assert(context != 0); assert(eglGetCurrentContext() == 0); // Creating a context does not yet activate it. assert(eglGetError() == EGL_SUCCESS); ret = eglMakeCurrent(display, surface, surface, context); assert(eglGetError() == EGL_SUCCESS); assert(ret == EGL_TRUE); assert(eglGetCurrentContext() == context); assert(eglGetCurrentSurface(EGL_READ) == surface); assert(eglGetCurrentSurface(EGL_DRAW) == surface); glClearColor(1.0,0.0,0.0,0.5); glClear(GL_COLOR_BUFFER_BIT); ret = eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); assert(eglGetError() == EGL_SUCCESS); assert(ret == EGL_TRUE); assert(eglGetCurrentContext() == EGL_NO_CONTEXT); assert(eglGetCurrentSurface(EGL_READ) == EGL_NO_SURFACE); assert(eglGetCurrentSurface(EGL_DRAW) == EGL_NO_SURFACE); assert(eglSwapInterval(display, 0) == EGL_TRUE); assert(eglGetError() == EGL_SUCCESS); assert(eglSwapInterval(display, 1) == EGL_TRUE); assert(eglGetError() == EGL_SUCCESS); assert(eglSwapInterval(display, 2) == EGL_TRUE); assert(eglGetError() == EGL_SUCCESS); ret = eglTerminate(display); assert(eglGetError() == EGL_SUCCESS); assert(ret == EGL_TRUE); // eglGetProcAddress() without active GL context and/or connected EGL display (after eglTerminate) is required to work, even though the returned function // pointers cannot be called unless an active context is available: // "return value of NULL indicates that the specified function does not exist for the implementation." // "Client API function pointers returned by eglGetProcAddress are independent of the display and the currently bound client API context, and may be used by any client API context which supports the function." // At https://www.khronos.org/registry/EGL/specs/eglspec.1.5.pdf, pages 82-32. assert(eglGetProcAddress("glClear") != 0); assert(eglGetProcAddress("glWakaWaka") == 0); #ifdef REPORT_RESULT REPORT_RESULT(result); #endif }
void RadarCanvas::Render(wxPaintEvent &evt) { int w, h; if (!IsShown() || !m_pi->m_initialized) { return; } GetClientSize(&w, &h); wxPaintDC(this); // only to be used in paint events. use wxClientDC to paint // outside the paint event if (!m_pi->m_opengl_mode) { LOG_DIALOG(wxT("BR24radar_pi: %s cannot render non-OpenGL mode"), m_ri->m_name.c_str()); return; } if (!m_pi->m_opencpn_gl_context && !m_pi->m_opencpn_gl_context_broken) { LOG_DIALOG(wxT("BR24radar_pi: %s skip render as no context known yet"), m_ri->m_name.c_str()); return; } LOG_DIALOG(wxT("BR24radar_pi: %s render OpenGL canvas %d by %d "), m_ri->m_name.c_str(), w, h); SetCurrent(*m_context); glPushMatrix(); glPushAttrib(GL_ALL_ATTRIB_BITS); wxFont font = GetOCPNGUIScaledFont_PlugIn(_T("StatusBar")); m_FontNormal.Build(font); wxFont bigFont = GetOCPNGUIScaledFont_PlugIn(_T("Dialog")); bigFont.SetPointSize(bigFont.GetPointSize() + 2); bigFont.SetWeight(wxFONTWEIGHT_BOLD); m_FontBig.Build(bigFont); bigFont.SetPointSize(bigFont.GetPointSize() + 2); bigFont.SetWeight(wxFONTWEIGHT_NORMAL); m_FontMenu.Build(bigFont); bigFont.SetPointSize(bigFont.GetPointSize() + 10); bigFont.SetWeight(wxFONTWEIGHT_BOLD); m_FontMenuBold.Build(bigFont); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Black Background glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear the canvas glEnable(GL_TEXTURE_2D); // Enable textures glEnable(GL_COLOR_MATERIAL); glEnable(GL_BLEND); // glDisable(GL_DEPTH_TEST); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); // Next two operations on the project matrix stack glLoadIdentity(); // Reset projection matrix stack glOrtho(0, w, h, 0, -1, 1); glMatrixMode(GL_MODELVIEW); // Reset matrick stack target back to GL_MODELVIEW RenderRangeRingsAndHeading(w, h); Render_EBL_VRM(w, h); glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); // Next two operations on the project matrix stack glLoadIdentity(); // Reset projection matrix stack if (w >= h) { glScaled(1.0, (float)-w / h, 1.0); } else { glScaled((float)h / w, -1.0, 1.0); } glMatrixMode(GL_MODELVIEW); // Reset matrick stack target back to GL_MODELVIEW m_ri->RenderRadarImage(wxPoint(0, 0), 1.0, 0.0, false); glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); // Next two operations on the project matrix stack glLoadIdentity(); // Reset projection matrix stack glOrtho(0, w, h, 0, -1, 1); glMatrixMode(GL_MODELVIEW); // Reset matrick stack target back to GL_MODELVIEW glEnable(GL_TEXTURE_2D); RenderTexts(w, h); RenderCursor(w, h); #ifdef NEVER glDisable(GL_TEXTURE_2D); glMatrixMode(GL_PROJECTION); // Next two operations on the project matrix stack glLoadIdentity(); // Reset projection matrix stack glMatrixMode(GL_MODELVIEW); // Reset matrick stack target back to GL_MODELVIEW #endif glPopAttrib(); glPopMatrix(); glFlush(); glFinish(); SwapBuffers(); if (m_pi->m_opencpn_gl_context) { SetCurrent(*m_pi->m_opencpn_gl_context); } else { SetCurrent(*m_zero_context); // Make sure OpenCPN -at least- doesn't overwrite our context info } }
void init(char *filename) { GLfloat cloud_color[4] = { 1., 1., 1., 0., }; GLfloat fog_color[4], fog_density = 0.05, density, far_cull; unsigned *image; int width, height, components; if (filename) { image = read_texture(filename, &width, &height, &components); if (image == NULL) { fprintf(stderr, "Error: Can't load image file \"%s\".\n", filename); exit(EXIT_FAILURE); } else { printf("%d x %d image loaded\n", width, height); } if (components != 1) { printf("must be a bw image\n"); exit(EXIT_FAILURE); } } else { int i, j; unsigned char *img; components = 4; width = height = 512; image = (unsigned *) malloc(width*height*sizeof(unsigned)); img = (unsigned char *)image; for (j = 0; j < height; j++) for (i = 0; i < width; i++) { int w2 = width/2, h2 = height/2; if (i & 32) img[4*(i+j*width)+0] = 0xff; else img[4*(i+j*width)+1] = 0xff; if (j&32) img[4*(i+j*width)+2] = 0xff; if ((i-w2)*(i-w2) + (j-h2)*(j-h2) > 64*64 && (i-w2)*(i-w2) + (j-h2)*(j-h2) < 300*300) img[4*(i+j*width)+3] = 0xff; } } glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_BLEND); glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, cloud_color); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexImage2D(GL_TEXTURE_2D, 0, components, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image); glEnable(GL_TEXTURE_2D); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(50.,1.,.1,far_cull = 10.); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0.,0.,-5.5); density = 1.- expf(-5.5 * fog_density * fog_density * far_cull * far_cull); #define MAX(a,b) ((a) > (b) ? (a) : (b)) #define MIN(a,b) ((a) < (b) ? (a) : (b)) density = MAX(MIN(density, 1.), 0.); fog_color[0] = .23 + density *.57; fog_color[1] = .35 + density *.45; fog_color[2] = .78 + density *.22; glClearColor(fog_color[0], fog_color[1], fog_color[2], 1.f); glFogi(GL_FOG_MODE, GL_EXP2); glFogf(GL_FOG_DENSITY, fog_density); glFogfv(GL_FOG_COLOR, fog_color); if (fog_density > 0) glEnable(GL_FOG); }
static void screen_opengl_render_apply(OGLRender *oglrender) { Scene *scene = oglrender->scene; ARegion *ar = oglrender->ar; View3D *v3d = oglrender->v3d; RegionView3D *rv3d = oglrender->rv3d; RenderResult *rr; Object *camera = NULL; ImBuf *ibuf; void *lock; float winmat[4][4]; int sizex = oglrender->sizex; int sizey = oglrender->sizey; const short view_context = (v3d != NULL); bool draw_bgpic = true; bool draw_sky = (scene->r.alphamode == R_ADDSKY); unsigned char *rect = NULL; rr = RE_AcquireResultRead(oglrender->re); if (oglrender->is_sequencer) { SeqRenderData context; SpaceSeq *sseq = oglrender->sseq; int chanshown = sseq ? sseq->chanshown : 0; struct bGPdata *gpd = (sseq && (sseq->flag & SEQ_SHOW_GPENCIL)) ? sseq->gpd : NULL; context = BKE_sequencer_new_render_data(oglrender->bmain->eval_ctx, oglrender->bmain, scene, oglrender->sizex, oglrender->sizey, 100.0f); ibuf = BKE_sequencer_give_ibuf(&context, CFRA, chanshown); if (ibuf) { ImBuf *linear_ibuf; BLI_assert((oglrender->sizex == ibuf->x) && (oglrender->sizey == ibuf->y)); linear_ibuf = IMB_dupImBuf(ibuf); IMB_freeImBuf(ibuf); if (linear_ibuf->rect_float == NULL) { /* internally sequencer working in display space and stores both bytes and float buffers in that space. * It is possible that byte->float onversion didn't happen in sequencer (e.g. when adding image sequence/movie * into sequencer) there'll be only byte buffer. Create float buffer from existing byte buffer, making it linear */ IMB_float_from_rect(linear_ibuf); } else { /* ensure float buffer is in linear space, not in display space */ BKE_sequencer_imbuf_from_sequencer_space(scene, linear_ibuf); } memcpy(rr->rectf, linear_ibuf->rect_float, sizeof(float) * 4 * oglrender->sizex * oglrender->sizey); IMB_freeImBuf(linear_ibuf); } if (gpd) { int i; unsigned char *gp_rect; GPU_offscreen_bind(oglrender->ofs); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); wmOrtho2(0, sizex, 0, sizey); glTranslatef(sizex / 2, sizey / 2, 0.0f); ED_gpencil_draw_ex(gpd, sizex, sizey, scene->r.cfra); gp_rect = MEM_mallocN(sizex * sizey * sizeof(unsigned char) * 4, "offscreen rect"); GPU_offscreen_read_pixels(oglrender->ofs, GL_UNSIGNED_BYTE, gp_rect); for (i = 0; i < sizex * sizey * 4; i += 4) { float col_src[4]; rgba_uchar_to_float(col_src, &gp_rect[i]); blend_color_mix_float(&rr->rectf[i], &rr->rectf[i], col_src); } GPU_offscreen_unbind(oglrender->ofs); MEM_freeN(gp_rect); } } else if (view_context) { ED_view3d_draw_offscreen_init(scene, v3d); GPU_offscreen_bind(oglrender->ofs); /* bind */ /* render 3d view */ if (rv3d->persp == RV3D_CAMOB && v3d->camera) { /*int is_ortho = scene->r.mode & R_ORTHO;*/ camera = v3d->camera; RE_GetCameraWindow(oglrender->re, camera, scene->r.cfra, winmat); } else { rctf viewplane; float clipsta, clipend; bool is_ortho = ED_view3d_viewplane_get(v3d, rv3d, sizex, sizey, &viewplane, &clipsta, &clipend, NULL); if (is_ortho) orthographic_m4(winmat, viewplane.xmin, viewplane.xmax, viewplane.ymin, viewplane.ymax, -clipend, clipend); else perspective_m4(winmat, viewplane.xmin, viewplane.xmax, viewplane.ymin, viewplane.ymax, clipsta, clipend); } rect = MEM_mallocN(sizex * sizey * sizeof(unsigned char) * 4, "offscreen rect"); if ((scene->r.mode & R_OSA) == 0) { ED_view3d_draw_offscreen(scene, v3d, ar, sizex, sizey, NULL, winmat, draw_bgpic, draw_sky); GPU_offscreen_read_pixels(oglrender->ofs, GL_UNSIGNED_BYTE, rect); } else { /* simple accumulation, less hassle then FSAA FBO's */ static float jit_ofs[32][2]; float winmat_jitter[4][4]; int *accum_buffer = MEM_mallocN(sizex * sizey * sizeof(int) * 4, "accum1"); int i, j; BLI_jitter_init(jit_ofs, scene->r.osa); /* first sample buffer, also initializes 'rv3d->persmat' */ ED_view3d_draw_offscreen(scene, v3d, ar, sizex, sizey, NULL, winmat, draw_bgpic, draw_sky); GPU_offscreen_read_pixels(oglrender->ofs, GL_UNSIGNED_BYTE, rect); for (i = 0; i < sizex * sizey * 4; i++) accum_buffer[i] = rect[i]; /* skip the first sample */ for (j = 1; j < scene->r.osa; j++) { copy_m4_m4(winmat_jitter, winmat); window_translate_m4(winmat_jitter, rv3d->persmat, (jit_ofs[j][0] * 2.0f) / sizex, (jit_ofs[j][1] * 2.0f) / sizey); ED_view3d_draw_offscreen(scene, v3d, ar, sizex, sizey, NULL, winmat_jitter, draw_bgpic, draw_sky); GPU_offscreen_read_pixels(oglrender->ofs, GL_UNSIGNED_BYTE, rect); for (i = 0; i < sizex * sizey * 4; i++) accum_buffer[i] += rect[i]; } for (i = 0; i < sizex * sizey * 4; i++) rect[i] = accum_buffer[i] / scene->r.osa; MEM_freeN(accum_buffer); } GPU_offscreen_unbind(oglrender->ofs); /* unbind */ } else { /* shouldnt suddenly give errors mid-render but possible */ char err_out[256] = "unknown"; ImBuf *ibuf_view = ED_view3d_draw_offscreen_imbuf_simple(scene, scene->camera, oglrender->sizex, oglrender->sizey, IB_rect, OB_SOLID, false, true, (draw_sky) ? R_ADDSKY : R_ALPHAPREMUL, err_out); camera = scene->camera; if (ibuf_view) { /* steal rect reference from ibuf */ rect = (unsigned char *)ibuf_view->rect; ibuf_view->mall &= ~IB_rect; IMB_freeImBuf(ibuf_view); } else { fprintf(stderr, "%s: failed to get buffer, %s\n", __func__, err_out); } } /* note on color management: * * OpenGL renders into sRGB colors, but render buffers are expected to be * linear So we convert to linear here, so the conversion back to bytes can make it * sRGB (or other display space) again, and so that e.g. openexr saving also saves the * correct linear float buffer. */ if (rect) { int profile_to; if (BKE_scene_check_color_management_enabled(scene)) profile_to = IB_PROFILE_LINEAR_RGB; else profile_to = IB_PROFILE_SRGB; /* sequencer has got trickier conversion happened above * also assume opengl's space matches byte buffer color space */ IMB_buffer_float_from_byte(rr->rectf, rect, profile_to, IB_PROFILE_SRGB, true, oglrender->sizex, oglrender->sizey, oglrender->sizex, oglrender->sizex); } /* rr->rectf is now filled with image data */ if ((scene->r.stamp & R_STAMP_ALL) && (scene->r.stamp & R_STAMP_DRAW)) BKE_stamp_buf(scene, camera, rect, rr->rectf, rr->rectx, rr->recty, 4); RE_ReleaseResult(oglrender->re); /* update byte from float buffer */ ibuf = BKE_image_acquire_ibuf(oglrender->ima, &oglrender->iuser, &lock); if (ibuf) { ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID; /* write file for animation */ if (oglrender->write_still) { char name[FILE_MAX]; int ok; if (scene->r.im_format.planes == R_IMF_CHAN_DEPTH_8) { IMB_color_to_bw(ibuf); } BKE_makepicstring(name, scene->r.pic, oglrender->bmain->name, scene->r.cfra, &scene->r.im_format, (scene->r.scemode & R_EXTENSION) != 0, false); ok = BKE_imbuf_write_as(ibuf, name, &scene->r.im_format, true); /* no need to stamp here */ if (ok) printf("OpenGL Render written to '%s'\n", name); else printf("OpenGL Render failed to write '%s'\n", name); } } BKE_image_release_ibuf(oglrender->ima, ibuf, lock); if (rect) MEM_freeN(rect); }
void init() { gProgram = glCreateProgram(); { GLuint shader = glCreateShader(GL_VERTEX_SHADER); const GLchar* source = ReadShader("vertex-shader.txt"); if (source == NULL) { return; } glShaderSource(shader, 1, &source, NULL); delete[] source; glCompileShader(shader); GLint status; glGetShaderiv(shader, GL_COMPILE_STATUS, &status); if (status == GL_FALSE) { std::string msg("Compile failure in shader:\n"); GLint infoLogLength; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength); char* strInfoLog = new char[infoLogLength + 1]; glGetShaderInfoLog(shader, infoLogLength, NULL, strInfoLog); msg += strInfoLog; delete[] strInfoLog; glDeleteShader(shader); shader = 0; throw std::runtime_error(msg); } glAttachShader(gProgram, shader); } { GLuint shader = glCreateShader(GL_FRAGMENT_SHADER); const GLchar* source = ReadShader("fragment-shader.txt"); if (source == NULL) { return; } glShaderSource(shader, 1, &source, NULL); delete[] source; glCompileShader(shader); GLint status; glGetShaderiv(shader, GL_COMPILE_STATUS, &status); if (status == GL_FALSE) { std::string msg("Compile failure in shader:\n"); GLint infoLogLength; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength); char* strInfoLog = new char[infoLogLength + 1]; glGetShaderInfoLog(shader, infoLogLength, NULL, strInfoLog); msg += strInfoLog; delete[] strInfoLog; glDeleteShader(shader); shader = 0; throw std::runtime_error(msg); } glAttachShader(gProgram, shader); } glLinkProgram(gProgram); //glDetachShader(program, shader); GLint linkStatus; glGetProgramiv(gProgram, GL_LINK_STATUS, &linkStatus); if (linkStatus == GL_FALSE) { std::string msg("Program linking failure: "); GLint infoLogLength; glGetProgramiv(gProgram, GL_INFO_LOG_LENGTH, &infoLogLength); char* strInfoLog = new char[infoLogLength + 1]; glGetProgramInfoLog(gProgram, infoLogLength, NULL, strInfoLog); msg += strInfoLog; delete[] strInfoLog; glDeleteProgram(gProgram); gProgram = 0; throw std::runtime_error(msg); } glUseProgram(gProgram); /* glm::mat4 projection = glm::perspective(glm::radians(50.0f), 800.0f / 600.0f, 0.1f, 10.0f); GLint uniformProjection = glGetUniformLocation(gProgram, "projection"); if (uniformProjection == -1) throw std::runtime_error(std::string("Program uniform not found: ") + "projection"); glUniformMatrix4fv(uniformProjection, 1, GL_FALSE, glm::value_ptr(projection)); glm::mat4 camera = glm::lookAt(glm::vec3(3, 3, 3), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0)); //glm::mat4 camera = glm::lookAt(glm::vec3(0.5, 0.5, 0.5), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0)); GLint uniformCamera = glGetUniformLocation(gProgram, "camera"); if (uniformCamera == -1) throw std::runtime_error(std::string("Program uniform not found: ") + "camera"); glUniformMatrix4fv(uniformCamera, 1, GL_FALSE, glm::value_ptr(camera)); */ int width, height, channels; unsigned char* pixels = stbi_load("wooden-crate.jpg", &width, &height, &channels, 0); if (!pixels) { throw std::runtime_error(stbi_failure_reason()); } unsigned long rowSize = channels *width; unsigned char* rowBuffer = new unsigned char[rowSize]; unsigned halfRows = height / 2; for (unsigned rowIdx = 0; rowIdx < halfRows; ++rowIdx) { unsigned char* row = pixels + (rowIdx * width + 0) * channels;//GetPixelOffset(0, rowIdx, _width, _height, _format); unsigned char* oppositeRow = pixels + ((height - rowIdx - 1) * width + 0) * channels;//GetPixelOffset(0, _height - rowIdx - 1, _width, _height, _format); memcpy(rowBuffer, row, rowSize); memcpy(row, oppositeRow, rowSize); memcpy(oppositeRow, rowBuffer, rowSize); } delete rowBuffer; glGenTextures(1, &gTex); glBindTexture(GL_TEXTURE_2D, gTex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); GLint internalformat; switch (channels) { case 1: internalformat = GL_LUMINANCE; break; case 2: internalformat = GL_LUMINANCE_ALPHA; break; case 3: internalformat = GL_RGB; break; case 4: internalformat = GL_RGBA; break; default: throw std::runtime_error("Unrecognised Bitmap::Format"); } glTexImage2D(GL_TEXTURE_2D, 0, internalformat, (GLsizei)width, (GLsizei)height, 0, internalformat, GL_UNSIGNED_BYTE, pixels); glBindTexture(GL_TEXTURE_2D, 0); stbi_image_free(pixels); // make and bind the VAO glGenVertexArrays(1, &gVAO); glBindVertexArray(gVAO); // make and bind the VBO glGenBuffers(1, &gVBO); glBindBuffer(GL_ARRAY_BUFFER, gVBO); GLfloat vertexData[] = { // X Y Z U V // bottom -1.0f,-1.0f,-1.0f, 0.0f, 0.0f, 1.0f,-1.0f,-1.0f, 1.0f, 0.0f, -1.0f,-1.0f, 1.0f, 0.0f, 1.0f, 1.0f,-1.0f,-1.0f, 1.0f, 0.0f, 1.0f,-1.0f, 1.0f, 1.0f, 1.0f, -1.0f,-1.0f, 1.0f, 0.0f, 1.0f, // top -1.0f, 1.0f,-1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f,-1.0f, 1.0f, 0.0f, 1.0f, 1.0f,-1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, // front -1.0f,-1.0f, 1.0f, 1.0f, 0.0f, 1.0f,-1.0f, 1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,-1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, // back -1.0f,-1.0f,-1.0f, 0.0f, 0.0f, -1.0f, 1.0f,-1.0f, 0.0f, 1.0f, 1.0f,-1.0f,-1.0f, 1.0f, 0.0f, 1.0f,-1.0f,-1.0f, 1.0f, 0.0f, -1.0f, 1.0f,-1.0f, 0.0f, 1.0f, 1.0f, 1.0f,-1.0f, 1.0f, 1.0f, // left -1.0f,-1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f,-1.0f, 1.0f, 0.0f, -1.0f,-1.0f,-1.0f, 0.0f, 0.0f, -1.0f,-1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f,-1.0f, 1.0f, 0.0f, // right 1.0f,-1.0f, 1.0f, 1.0f, 1.0f, 1.0f,-1.0f,-1.0f, 1.0f, 0.0f, 1.0f, 1.0f,-1.0f, 0.0f, 0.0f, 1.0f,-1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,-1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f }; glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW); GLint attrib = glGetAttribLocation(gProgram, "vert"); if (attrib == -1) throw std::runtime_error(std::string("Program attribute not found: ") + "vert"); glEnableVertexAttribArray(attrib); glVertexAttribPointer(attrib, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), NULL); GLint vertTexCoord = glGetAttribLocation(gProgram, "vertTexCoord"); if (vertTexCoord == -1) throw std::runtime_error(std::string("Program attribute not found: ") + "vertTexCoord"); glEnableVertexAttribArray(vertTexCoord); glVertexAttribPointer(vertTexCoord, 2, GL_FLOAT, GL_TRUE, 5 * sizeof(GLfloat), (const GLvoid*)(3 * sizeof(GLfloat))); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glClearColor(0.196078431372549f, 0.3137254901960784f, 0.5882352941176471f, 1); }
void test_triangle_smoothed(GLenum mode) { GLint width, height; GLfloat vVertices[] = { 0.0f, 0.5f, 0.0f, -0.5f, -0.5f, 0.0f, 0.5f, -0.5f, 0.0f }; GLfloat vColors[] = { 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f}; EGLSurface surface; RD_START("triangle-smoothed", ""); display = get_display(); /* get an appropriate EGL frame buffer configuration */ ECHK(eglChooseConfig(display, config_attribute_list, &config, 1, &num_config)); DEBUG_MSG("num_config: %d", num_config); /* create an EGL rendering context */ ECHK(context = eglCreateContext(display, config, EGL_NO_CONTEXT, context_attribute_list)); surface = make_window(display, config, 400, 240); ECHK(eglQuerySurface(display, surface, EGL_WIDTH, &width)); ECHK(eglQuerySurface(display, surface, EGL_HEIGHT, &height)); DEBUG_MSG("Buffer: %dx%d", width, height); /* connect the context to the surface */ ECHK(eglMakeCurrent(display, surface, surface, context)); program = get_program(vertex_shader_source, fragment_shader_source); GCHK(glBindAttribLocation(program, 0, "aPosition")); GCHK(glBindAttribLocation(program, 1, "aColor")); link_program(program); GCHK(glViewport(0, 0, width, height)); GCHK(glFrontFace(mode)); /* clear the color buffer */ GCHK(glClearColor(0.0, 0.0, 0.0, 1.0)); GCHK(glClear(GL_COLOR_BUFFER_BIT)); GCHK(glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, vVertices)); GCHK(glEnableVertexAttribArray(0)); GCHK(glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, vColors)); GCHK(glEnableVertexAttribArray(1)); GCHK(glDrawArrays(GL_TRIANGLES, 0, 3)); ECHK(eglSwapBuffers(display, surface)); GCHK(glFlush()); ECHK(eglDestroySurface(display, surface)); ECHK(eglTerminate(display)); RD_END(); }
void Render::RenderAllScenesPerCamera( Texture* pRenderColor, Texture* pRenderDepth) { WasGLErrorPlusPrint(); Texture* pColorDestination = pRenderColor; if(m_multiPass) { GLuint clearFlags = 0; if(pRenderColor) { // this happens when we switch to vr, as the vr rendertarget is different ResizeRenderTargets(pRenderColor->m_width, pRenderColor->m_height); WasGLErrorPlusPrint(); } else { pRenderColor = m_renderColor; if(!pRenderColor) return; glBindFramebuffer(GL_FRAMEBUFFER, pRenderColor->m_framebuffer_id); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, pRenderColor->m_texture_id, 0); clearFlags |= GL_COLOR_BUFFER_BIT; WasGLErrorPlusPrint(); } // setup render depth if it wasn't passed in if(pRenderDepth == NULL) { pRenderDepth = m_renderDepth; glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, pRenderDepth->m_texture_id, 0); clearFlags |= GL_DEPTH_BUFFER_BIT; WasGLErrorPlusPrint(); } if(clearFlags != 0) { glViewport(0, 0, pRenderDepth->m_width, pRenderDepth->m_height); //glClearColor(1.0f, 0.5f, 0.0f, 1.0f); glClearColor(m_clearColor.x, m_clearColor.y, m_clearColor.z, m_clearColor.w); glClear(clearFlags); WasGLErrorPlusPrint(); } } for(const auto pCamera : m_cameras) { for(auto pScene : m_scenes) { RenderScene(pCamera, pScene, pRenderColor, pRenderDepth); } } if(m_multiPass) { RenderCompose(pColorDestination, pRenderColor, m_overdrawColor); // restore previous settings ToggleAlphaDepthModes(m_alphaDepthMode); for(const auto pCamera : m_cameras) { for(auto pScene : m_scenes) { pScene->RenderDynamicEntities(pCamera); } } } }
void init() { glClearColor(0,0,0,0); //glEnable(GL_DEPTH_TEST); }
FramebufferManager::FramebufferManager(int targetWidth, int targetHeight, int msaaSamples) { m_xfbFramebuffer = 0; m_efbColor = 0; m_efbDepth = 0; m_efbColorSwap = 0; m_resolvedColorTexture = 0; m_resolvedDepthTexture = 0; m_targetWidth = targetWidth; m_targetHeight = targetHeight; m_msaaSamples = msaaSamples; // The EFB can be set to different pixel formats by the game through the // BPMEM_ZCOMPARE register (which should probably have a different name). // They are: // - 24-bit RGB (8-bit components) with 24-bit Z // - 24-bit RGBA (6-bit components) with 24-bit Z // - Multisampled 16-bit RGB (5-6-5 format) with 16-bit Z // We only use one EFB format here: 32-bit ARGB with 24-bit Z. // Multisampling depends on user settings. // The distinction becomes important for certain operations, i.e. the // alpha channel should be ignored if the EFB does not have one. glActiveTexture(GL_TEXTURE9); GLuint glObj[3]; glGenTextures(3, glObj); m_efbColor = glObj[0]; m_efbDepth = glObj[1]; m_efbColorSwap = glObj[2]; m_EFBLayers = (g_ActiveConfig.iStereoMode > 0) ? 2 : 1; m_efbFramebuffer.resize(m_EFBLayers); m_resolvedFramebuffer.resize(m_EFBLayers); // OpenGL MSAA textures are a different kind of texture type and must be allocated // with a different function, so we create them separately. if (m_msaaSamples <= 1) { m_textureType = GL_TEXTURE_2D_ARRAY; glBindTexture(m_textureType, m_efbColor); glTexParameteri(m_textureType, GL_TEXTURE_MAX_LEVEL, 0); glTexImage3D(m_textureType, 0, GL_RGBA, m_targetWidth, m_targetHeight, m_EFBLayers, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); glBindTexture(m_textureType, m_efbDepth); glTexParameteri(m_textureType, GL_TEXTURE_MAX_LEVEL, 0); glTexImage3D(m_textureType, 0, GL_DEPTH_COMPONENT32F, m_targetWidth, m_targetHeight, m_EFBLayers, 0, GL_DEPTH_COMPONENT, GL_FLOAT, nullptr); glBindTexture(m_textureType, m_efbColorSwap); glTexParameteri(m_textureType, GL_TEXTURE_MAX_LEVEL, 0); glTexImage3D(m_textureType, 0, GL_RGBA, m_targetWidth, m_targetHeight, m_EFBLayers, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); } else { GLenum resolvedType = GL_TEXTURE_2D_ARRAY; // Only use a layered multisample texture if needed. Some drivers // slow down significantly with single-layered multisample textures. if (m_EFBLayers > 1) { m_textureType = GL_TEXTURE_2D_MULTISAMPLE_ARRAY; if (g_ogl_config.bSupports3DTextureStorage) { glBindTexture(m_textureType, m_efbColor); glTexStorage3DMultisample(m_textureType, m_msaaSamples, GL_RGBA8, m_targetWidth, m_targetHeight, m_EFBLayers, false); glBindTexture(m_textureType, m_efbDepth); glTexStorage3DMultisample(m_textureType, m_msaaSamples, GL_DEPTH_COMPONENT32F, m_targetWidth, m_targetHeight, m_EFBLayers, false); glBindTexture(m_textureType, m_efbColorSwap); glTexStorage3DMultisample(m_textureType, m_msaaSamples, GL_RGBA8, m_targetWidth, m_targetHeight, m_EFBLayers, false); glBindTexture(m_textureType, 0); } else { glBindTexture(m_textureType, m_efbColor); glTexImage3DMultisample(m_textureType, m_msaaSamples, GL_RGBA, m_targetWidth, m_targetHeight, m_EFBLayers, false); glBindTexture(m_textureType, m_efbDepth); glTexImage3DMultisample(m_textureType, m_msaaSamples, GL_DEPTH_COMPONENT32F, m_targetWidth, m_targetHeight, m_EFBLayers, false); glBindTexture(m_textureType, m_efbColorSwap); glTexImage3DMultisample(m_textureType, m_msaaSamples, GL_RGBA, m_targetWidth, m_targetHeight, m_EFBLayers, false); glBindTexture(m_textureType, 0); } } else { m_textureType = GL_TEXTURE_2D_MULTISAMPLE; if (g_ogl_config.bSupports2DTextureStorage) { glBindTexture(m_textureType, m_efbColor); glTexStorage2DMultisample(m_textureType, m_msaaSamples, GL_RGBA8, m_targetWidth, m_targetHeight, false); glBindTexture(m_textureType, m_efbDepth); glTexStorage2DMultisample(m_textureType, m_msaaSamples, GL_DEPTH_COMPONENT32F, m_targetWidth, m_targetHeight, false); glBindTexture(m_textureType, m_efbColorSwap); glTexStorage2DMultisample(m_textureType, m_msaaSamples, GL_RGBA8, m_targetWidth, m_targetHeight, false); glBindTexture(m_textureType, 0); } else { glBindTexture(m_textureType, m_efbColor); glTexImage2DMultisample(m_textureType, m_msaaSamples, GL_RGBA, m_targetWidth, m_targetHeight, false); glBindTexture(m_textureType, m_efbDepth); glTexImage2DMultisample(m_textureType, m_msaaSamples, GL_DEPTH_COMPONENT32F, m_targetWidth, m_targetHeight, false); glBindTexture(m_textureType, m_efbColorSwap); glTexImage2DMultisample(m_textureType, m_msaaSamples, GL_RGBA, m_targetWidth, m_targetHeight, false); glBindTexture(m_textureType, 0); } } // Although we are able to access the multisampled texture directly, we don't do it everywhere. // The old way is to "resolve" this multisampled texture by copying it into a non-sampled texture. // This would lead to an unneeded copy of the EFB, so we are going to avoid it. // But as this job isn't done right now, we do need that texture for resolving: glGenTextures(2, glObj); m_resolvedColorTexture = glObj[0]; m_resolvedDepthTexture = glObj[1]; glBindTexture(resolvedType, m_resolvedColorTexture); glTexParameteri(resolvedType, GL_TEXTURE_MAX_LEVEL, 0); glTexImage3D(resolvedType, 0, GL_RGBA, m_targetWidth, m_targetHeight, m_EFBLayers, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); glBindTexture(resolvedType, m_resolvedDepthTexture); glTexParameteri(resolvedType, GL_TEXTURE_MAX_LEVEL, 0); glTexImage3D(resolvedType, 0, GL_DEPTH_COMPONENT32F, m_targetWidth, m_targetHeight, m_EFBLayers, 0, GL_DEPTH_COMPONENT, GL_FLOAT, nullptr); // Bind resolved textures to resolved framebuffer. glGenFramebuffers(m_EFBLayers, m_resolvedFramebuffer.data()); glBindFramebuffer(GL_FRAMEBUFFER, m_resolvedFramebuffer[0]); FramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, resolvedType, m_resolvedColorTexture, 0); FramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, resolvedType, m_resolvedDepthTexture, 0); // Bind all the other layers as separate FBOs for blitting. for (unsigned int i = 1; i < m_EFBLayers; i++) { glBindFramebuffer(GL_FRAMEBUFFER, m_resolvedFramebuffer[i]); glFramebufferTextureLayer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, m_resolvedColorTexture, 0, i); glFramebufferTextureLayer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, m_resolvedDepthTexture, 0, i); } } // Create XFB framebuffer; targets will be created elsewhere. glGenFramebuffers(1, &m_xfbFramebuffer); // Bind target textures to EFB framebuffer. glGenFramebuffers(m_EFBLayers, m_efbFramebuffer.data()); glBindFramebuffer(GL_FRAMEBUFFER, m_efbFramebuffer[0]); FramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, m_textureType, m_efbColor, 0); FramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, m_textureType, m_efbDepth, 0); // Bind all the other layers as separate FBOs for blitting. for (unsigned int i = 1; i < m_EFBLayers; i++) { glBindFramebuffer(GL_FRAMEBUFFER, m_efbFramebuffer[i]); glFramebufferTextureLayer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, m_efbColor, 0, i); glFramebufferTextureLayer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, m_efbDepth, 0, i); } // EFB framebuffer is currently bound, make sure to clear its alpha value to 1.f glViewport(0, 0, m_targetWidth, m_targetHeight); glScissor(0, 0, m_targetWidth, m_targetHeight); glClearColor(0.f, 0.f, 0.f, 1.f); glClearDepthf(1.0f); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); // reinterpret pixel format const char* vs = m_EFBLayers > 1 ? "void main(void) {\n" " vec2 rawpos = vec2(gl_VertexID&1, gl_VertexID&2);\n" " gl_Position = vec4(rawpos*2.0-1.0, 0.0, 1.0);\n" "}\n" : "flat out int layer;\n" "void main(void) {\n" " layer = 0;\n" " vec2 rawpos = vec2(gl_VertexID&1, gl_VertexID&2);\n" " gl_Position = vec4(rawpos*2.0-1.0, 0.0, 1.0);\n" "}\n"; // The way to sample the EFB is based on the on the current configuration. // As we use the same sampling way for both interpreting shaders, the sampling // shader are generated first: std::string sampler; if (m_msaaSamples <= 1) { // non-msaa, so just fetch the pixel sampler = "SAMPLER_BINDING(9) uniform sampler2DArray samp9;\n" "vec4 sampleEFB(ivec3 pos) {\n" " return texelFetch(samp9, pos, 0);\n" "}\n"; } else if (g_ActiveConfig.backend_info.bSupportsSSAA) { // msaa + sample shading available, so just fetch the sample // This will lead to sample shading, but it's the only way to not loose // the values of each sample. if (m_EFBLayers > 1) { sampler = "SAMPLER_BINDING(9) uniform sampler2DMSArray samp9;\n" "vec4 sampleEFB(ivec3 pos) {\n" " return texelFetch(samp9, pos, gl_SampleID);\n" "}\n"; } else { sampler = "SAMPLER_BINDING(9) uniform sampler2DMS samp9;\n" "vec4 sampleEFB(ivec3 pos) {\n" " return texelFetch(samp9, pos.xy, gl_SampleID);\n" "}\n"; } } else { // msaa without sample shading: calculate the mean value of the pixel std::stringstream samples; samples << m_msaaSamples; if (m_EFBLayers > 1) { sampler = "SAMPLER_BINDING(9) uniform sampler2DMSArray samp9;\n" "vec4 sampleEFB(ivec3 pos) {\n" " vec4 color = vec4(0.0, 0.0, 0.0, 0.0);\n" " for(int i=0; i<" + samples.str() + "; i++)\n" " color += texelFetch(samp9, pos, 0), i);\n" " return color / " + samples.str() + ";\n" "}\n"; } else { sampler = "SAMPLER_BINDING(9) uniform sampler2DMS samp9;\n" "vec4 sampleEFB(ivec3 pos) {\n" " vec4 color = vec4(0.0, 0.0, 0.0, 0.0);\n" " for(int i=0; i<" + samples.str() + "; i++)\n" " color += texelFetch(samp9, pos.xy, i);\n" " return color / " + samples.str() + ";\n" "}\n"; } } std::string ps_rgba6_to_rgb8 = sampler + "flat in int layer;\n" "out vec4 ocol0;\n" "void main()\n" "{\n" " ivec4 src6 = ivec4(round(sampleEFB(ivec3(gl_FragCoord.xy, layer)) * 63.f));\n" " ivec4 dst8;\n" " dst8.r = (src6.r << 2) | (src6.g >> 4);\n" " dst8.g = ((src6.g & 0xF) << 4) | (src6.b >> 2);\n" " dst8.b = ((src6.b & 0x3) << 6) | src6.a;\n" " dst8.a = 255;\n" " ocol0 = float4(dst8) / 255.f;\n" "}"; std::string ps_rgb8_to_rgba6 = sampler + "flat in int layer;\n" "out vec4 ocol0;\n" "void main()\n" "{\n" " ivec4 src8 = ivec4(round(sampleEFB(ivec3(gl_FragCoord.xy, layer)) * 255.f));\n" " ivec4 dst6;\n" " dst6.r = src8.r >> 2;\n" " dst6.g = ((src8.r & 0x3) << 4) | (src8.g >> 4);\n" " dst6.b = ((src8.g & 0xF) << 2) | (src8.b >> 6);\n" " dst6.a = src8.b & 0x3F;\n" " ocol0 = float4(dst6) / 63.f;\n" "}"; std::stringstream vertices, layers; vertices << m_EFBLayers * 3; layers << m_EFBLayers; std::string gs = "layout(triangles) in;\n" "layout(triangle_strip, max_vertices = " + vertices.str() + ") out;\n" "flat out int layer;\n" "void main()\n" "{\n" " for (int j = 0; j < " + layers.str() + "; ++j) {\n" " for (int i = 0; i < 3; ++i) {\n" " layer = j;\n" " gl_Layer = j;\n" " gl_Position = gl_in[i].gl_Position;\n" " EmitVertex();\n" " }\n" " EndPrimitive();\n" " }\n" "}\n"; ProgramShaderCache::CompileShader(m_pixel_format_shaders[0], vs, ps_rgb8_to_rgba6.c_str(), (m_EFBLayers > 1) ? gs : ""); ProgramShaderCache::CompileShader(m_pixel_format_shaders[1], vs, ps_rgba6_to_rgb8.c_str(), (m_EFBLayers > 1) ? gs : ""); ProgramShaderCache::CompileShader(m_EfbPokes, StringFromFormat( "in vec2 rawpos;\n" "in vec4 color0;\n" // color "in int color1;\n" // depth "out vec4 v_c;\n" "out float v_z;\n" "void main(void) {\n" " gl_Position = vec4(((rawpos + 0.5) / vec2(640.0, 528.0) * 2.0 - 1.0) * vec2(1.0, -1.0), 0.0, 1.0);\n" " gl_PointSize = %d.0 / 640.0;\n" " v_c = color0.bgra;\n" " v_z = float(color1 & 0xFFFFFF) / 16777216.0;\n" "}\n", m_targetWidth), StringFromFormat( "in vec4 %s_c;\n" "in float %s_z;\n" "out vec4 ocol0;\n" "void main(void) {\n" " ocol0 = %s_c;\n" " gl_FragDepth = %s_z;\n" "}\n", m_EFBLayers > 1 ? "g" : "v", m_EFBLayers > 1 ? "g" : "v", m_EFBLayers > 1 ? "g" : "v", m_EFBLayers > 1 ? "g" : "v"), m_EFBLayers > 1 ? StringFromFormat( "layout(points) in;\n" "layout(points, max_vertices = %d) out;\n" "in vec4 v_c[1];\n" "in float v_z[1];\n" "out vec4 g_c;\n" "out float g_z;\n" "void main()\n" "{\n" " for (int j = 0; j < %d; ++j) {\n" " gl_Layer = j;\n" " gl_Position = gl_in[0].gl_Position;\n" " gl_PointSize = %d.0 / 640.0;\n" " g_c = v_c[0];\n" " g_z = v_z[0];\n" " EmitVertex();\n" " EndPrimitive();\n" " }\n" "}\n", m_EFBLayers, m_EFBLayers, m_targetWidth) : ""); glGenBuffers(1, &m_EfbPokes_VBO); glGenVertexArrays(1, &m_EfbPokes_VAO); glBindBuffer(GL_ARRAY_BUFFER, m_EfbPokes_VBO); glBindVertexArray(m_EfbPokes_VAO ); glEnableVertexAttribArray(SHADER_POSITION_ATTRIB); glVertexAttribPointer(SHADER_POSITION_ATTRIB, 2, GL_UNSIGNED_SHORT, 0, sizeof(EfbPokeData), (void*)offsetof(EfbPokeData, x)); glEnableVertexAttribArray(SHADER_COLOR0_ATTRIB); glVertexAttribPointer(SHADER_COLOR0_ATTRIB, 4, GL_UNSIGNED_BYTE, 1, sizeof(EfbPokeData), (void*)offsetof(EfbPokeData, data)); glEnableVertexAttribArray(SHADER_COLOR1_ATTRIB); glVertexAttribIPointer(SHADER_COLOR1_ATTRIB, 1, GL_INT, sizeof(EfbPokeData), (void*)offsetof(EfbPokeData, data)); if (GLInterface->GetMode() == GLInterfaceMode::MODE_OPENGL) glEnable(GL_PROGRAM_POINT_SIZE); }
void ViewportArrayApplication::Display(bool auto_redraw) { float t = float(GetTickCount() & 0x3FFF) / float(0x3FFF); static const vmath::vec3 X(1.0f, 0.0f, 0.0f); static const vmath::vec3 Y(0.0f, 1.0f, 0.0f); static const vmath::vec3 Z(0.0f, 0.0f, 1.0f); glDisable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClearDepth(1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(sort_prog); vmath::mat4 p(vmath::frustum(-1.0f, 1.0f, aspect, -aspect, 1.0f, 5000.0f)); vmath::mat4 m; m = vmath::mat4(vmath::translate(0.0f, 0.0f, 100.0f * sinf(6.28318531f * t) - 230.0f) * vmath::rotate(360.0f * t, X) * vmath::rotate(360.0f * t * 2.0f, Y) * vmath::rotate(360.0f * t * 5.0f, Z) * vmath::translate(0.0f, -80.0f, 0.0f)); glUniformMatrix4fv(model_matrix_pos, 1, GL_FALSE, m[0]); glUniformMatrix4fv(projection_matrix_pos, 1, GL_FALSE, p); glEnable(GL_RASTERIZER_DISCARD); glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, xfb); glBeginTransformFeedback(GL_POINTS); object.Render(); glEndTransformFeedback(); glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, 0); glDisable(GL_RASTERIZER_DISCARD); static const vmath::vec4 colors[2] = { vmath::vec4(0.8f, 0.8f, 0.9f, 0.5f), vmath::vec4(0.3f, 1.0f, 0.3f, 0.8f) }; glUseProgram(render_prog); glUniform4fv(0, 1, colors[0]); glBindVertexArray(vao[0]); glDrawTransformFeedbackStream(GL_TRIANGLES, xfb, 0); glUniform4fv(0, 1, colors[1]); glBindVertexArray(vao[1]); glDrawTransformFeedbackStream(GL_TRIANGLES, xfb, 1); base::Display(); }
/*!**************************************************************************** @Function InitView @Return bool true if no error occured @Description Code in InitView() will be called by PVRShell upon initialization or after a change in the rendering context. Used to initialize variables that are dependant on the rendering context (e.g. textures, vertex buffers, etc.) ******************************************************************************/ bool OGLES3BinaryShader::InitView() { // Initialise a colour to draw our triangle // (For this training course, binary loaded shaders use a different colour // To show which is being used. Red means it had to compile the shaders, // green shows that it retrieved the binary from memory. float afColour[]={0.0,0.0,0.0}; // Filename and path strings. char* pWritePath = (char*)PVRShellGet(prefWritePath); char* shaderPath = new char[strlen(pWritePath) + 13]; sprintf(shaderPath, "%sShaderBinary", pWritePath); // If binary shaders are not supported or there isn't a valid binary shader stored, recompile the shaders. if(!loadBinaryProgram(shaderPath,m_uiProgramObject)) { { // Fragment shader code const char* pszFragShader = "\ #version 300 es\n\ uniform lowp vec3 myColour;\ layout (location = 0) out lowp vec4 oColour;\ void main (void)\ {\ oColour = vec4(myColour, 1.0);\ }"; // Create the fragment shader object m_uiFragShader = glCreateShader(GL_FRAGMENT_SHADER); // Load the source code into it glShaderSource(m_uiFragShader, 1, (const char**)&pszFragShader, NULL); // Compile the source code glCompileShader(m_uiFragShader); // Check if compilation succeeded GLint bShaderCompiled; glGetShaderiv(m_uiFragShader, GL_COMPILE_STATUS, &bShaderCompiled); if (!bShaderCompiled) { // An error happened, first retrieve the length of the log message int i32InfoLogLength, i32CharsWritten; glGetShaderiv(m_uiFragShader, GL_INFO_LOG_LENGTH, &i32InfoLogLength); // Allocate enough space for the message and retrieve it char* pszInfoLog = new char[i32InfoLogLength]; glGetShaderInfoLog(m_uiFragShader, i32InfoLogLength, &i32CharsWritten, pszInfoLog); /* Displays the message in a dialog box when the application quits using the shell PVRShellSet function with first parameter prefExitMessage. */ char* pszMsg = new char[i32InfoLogLength+256]; strcpy(pszMsg, "Failed to compile fragment shader: "); strcat(pszMsg, pszInfoLog); PVRShellSet(prefExitMessage, pszMsg); delete [] pszMsg; delete [] pszInfoLog; delete [] shaderPath; return false; } } { // Vertex shader code. const char* pszVertShader = "\ #version 300 es\n\ layout (location = 0) in highp vec4 myVertex;\ uniform mediump mat4 myPMVMatrix;\ void main(void)\ {\ gl_Position = myPMVMatrix * myVertex;\ }"; // Loads the vertex shader in the same way m_uiVertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(m_uiVertexShader, 1, (const char**)&pszVertShader, NULL); glCompileShader(m_uiVertexShader); // Checks if the shader has compiled. GLint bShaderCompiled; glGetShaderiv(m_uiVertexShader, GL_COMPILE_STATUS, &bShaderCompiled); if (!bShaderCompiled) { int i32InfoLogLength, i32CharsWritten; glGetShaderiv(m_uiVertexShader, GL_INFO_LOG_LENGTH, &i32InfoLogLength); char* pszInfoLog = new char[i32InfoLogLength]; glGetShaderInfoLog(m_uiVertexShader, i32InfoLogLength, &i32CharsWritten, pszInfoLog); char* pszMsg = new char[i32InfoLogLength+256]; strcpy(pszMsg, "Failed to compile vertex shader: "); strcat(pszMsg, pszInfoLog); PVRShellSet(prefExitMessage, pszMsg); delete [] pszMsg; delete [] pszInfoLog; delete [] shaderPath; return false; } } // Create the shader program m_uiProgramObject = glCreateProgram(); // Attach the fragment and vertex shaders to the shader program. glAttachShader(m_uiProgramObject, m_uiFragShader); glAttachShader(m_uiProgramObject, m_uiVertexShader); // Bind the custom vertex attribute "myVertex" to location VERTEX_ARRAY glBindAttribLocation(m_uiProgramObject, VERTEX_ARRAY, "myVertex"); // Link the program glLinkProgram(m_uiProgramObject); // Check if linking succeeded in the same way we checked for compilation success GLint bLinked; glGetProgramiv(m_uiProgramObject, GL_LINK_STATUS, &bLinked); if (!bLinked) { int i32InfoLogLength, i32CharsWritten; glGetProgramiv(m_uiProgramObject, GL_INFO_LOG_LENGTH, &i32InfoLogLength); char* pszInfoLog = new char[i32InfoLogLength]; glGetProgramInfoLog(m_uiProgramObject, i32InfoLogLength, &i32CharsWritten, pszInfoLog); char* pszMsg = new char[i32InfoLogLength+256]; strcpy(pszMsg, "Failed to link program: "); strcat(pszMsg, pszInfoLog); PVRShellSet(prefExitMessage, pszMsg); delete [] pszMsg; delete [] pszInfoLog; delete [] shaderPath; return false; } // As there is no stored binary, save the current binary out for use later. // Note that this is done after both binding attributes and linking - // none of these can be performed after saveBinaryProgram(shaderPath,m_uiProgramObject); //Set red channel of the colour to maximum - red shows that the shaders had to be compiled. afColour[0]=1.0f; } else { //Set green channel of the colour to maximum - green shows that the shaders were loaded from binary files. afColour[1]=1.0f; } delete[] shaderPath; // Uses the program. glUseProgram(m_uiProgramObject); // Bind the colour to the fragment shader. GLint i32ColourLocation = glGetUniformLocation(m_uiProgramObject, "myColour"); // Then passes the colour to that variable glUniform3fv(i32ColourLocation, 1, afColour); // Sets the clear color glClearColor(0.6f, 0.8f, 1.0f, 1.0f); // Create VBO for the triangle from our data // Vertex data GLfloat afVertices[] = {-0.4f,-0.4f,0.0f, 0.4f,-0.4f,0.0f, 0.0f,0.4f,0.0f}; // Gen VBO glGenBuffers(1, &m_ui32Vbo); // Bind the VBO glBindBuffer(GL_ARRAY_BUFFER, m_ui32Vbo); // Set the buffer's data glBufferData(GL_ARRAY_BUFFER, 3 * (3 * sizeof(GLfloat)) /* 3 Vertices of 3 floats in size */, afVertices, GL_STATIC_DRAW); // Unbind the VBO glBindBuffer(GL_ARRAY_BUFFER, 0); return true; }
// ������Ⱦ״̬ void SetupRec() { glClearColor(0.6f, 0.4f, 0.7f, 1.0f); }
/** * Called to draw scene */ void RenderScene(void) { // Bind the FBO with multisample buffers glBindFramebuffer(GL_DRAW_FRAMEBUFFER, msFBO); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // User selected order independant transparency if (mode == USER_OIT) { // Use OIT, setup sample masks glSampleMaski(0, 0x01); glEnable(GL_SAMPLE_MASK); // Prevent depth test from culling covered surfaces glDepthFunc(GL_ALWAYS); } modelViewMatrix.push(); M3DMatrix44f mCamera; cameraFrame.GetCameraMatrix(mCamera); modelViewMatrix.MultMatrix(mCamera); modelViewMatrix.push(); modelViewMatrix.moveTo(0.0f, -0.4f, -4.0f); modelViewMatrix.rotateTo(worldAngle, 0.0, 1.0, 0.0); // Draw the background and disk to the first sample modelViewMatrix.push(); modelViewMatrix.moveTo(0.0f, 3.0f, 0.0f); modelViewMatrix.rotateTo(90.0, 1.0, 0.0, 0.0); modelViewMatrix.rotateTo(90.0, 0.0, 0.0, 1.0); glBindTexture(GL_TEXTURE_2D, textures[1]); shaderManager.useStockShader(GLT_SHADER_TEXTURE_REPLACE, transformPipeline.GetMVPMatrix(), 0); bckgrndCylBatch.draw(); modelViewMatrix.pop(); modelViewMatrix.moveTo(0.0f, -0.3f, 0.0f); modelViewMatrix.push(); modelViewMatrix.rotateTo(90.0, 1.0, 0.0, 0.0); shaderManager.useStockShader(GLT_SHADER_FLAT, transformPipeline.GetMVPMatrix(), vGrey); diskBatch.draw(); modelViewMatrix.pop(); modelViewMatrix.moveTo(0.0f, 0.1f, 0.0f); // User selected blending if (mode == USER_BLEND) { // Setup blend state glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); switch (blendMode) { case 1: glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); break; case 2: glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_DST_ALPHA); break; case 3: glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); break; case 4: glBlendFunc(GL_SRC_ALPHA, GL_ONE); break; case 5: glBlendFunc(GL_SRC_ALPHA, GL_DST_COLOR); break; case 6: glBlendFuncSeparate(GL_SRC_ALPHA, GL_DST_ALPHA, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); break; case 7: glBlendFuncSeparate(GL_SRC_COLOR, GL_DST_COLOR, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); break; default: glDisable(GL_BLEND); } } // Now draw the glass pieces DrawWorld(); modelViewMatrix.pop(); modelViewMatrix.pop(); // Clean up all state glDepthFunc(GL_LEQUAL); glDisable(GL_BLEND); glDisable(GL_SAMPLE_MASK); glSampleMaski(0, 0xffffffff); // Resolve multisample buffer projectionMatrix.push(); projectionMatrix.setMatrix(orthoMatrix); modelViewMatrix.push(); modelViewMatrix.identity(); // Setup and Clear the default framebuffer glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); glViewport(0, 0, screenWidth, screenHeight); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if (mode == USER_OIT) SetupOITResolveProg(); else if (mode == USER_BLEND) SetupResolveProg(); // Draw a full-size quad to resolve the multisample surfaces screenQuad.draw(); modelViewMatrix.pop(); projectionMatrix.pop(); // Reset texture state glEnable(GL_DEPTH_TEST); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0); // Perform the buffer swap to display back buffer glutSwapBuffers(); glutPostRedisplay(); }
window::window(int width, int height, bool fullScreen, std::wstring ptitle) : width (width), height(height), fullScreen(fullScreen), title(ptitle) { windowHandle = 0; deviceContext = 0; renderingContext = 0; WNDCLASSEX windowClass = {0}; windowClass.cbSize = sizeof(windowClass); windowClass.hInstance = GetModuleHandle(0); windowClass.style = CS_OWNDC; windowClass.hIcon = LoadIcon(windowClass.hInstance, MAKEINTRESOURCE(129)); windowClass.lpfnWndProc = wndproc; windowClass.lpszClassName = L"classy class"; ZeroMemory(keyDown, 256*sizeof(bool)); mouseLeft = mouseRight = false; RegisterClassEx(&windowClass); HWND temporaryWindow = CreateWindowEx(WS_EX_APPWINDOW, L"classy class", L"temporary", WS_SYSMENU|WS_BORDER|WS_MINIMIZEBOX, 0, 0, 0, 0, 0, 0, windowClass.hInstance, 0); HDC temporaryDeviceContext = GetDC(temporaryWindow); PIXELFORMATDESCRIPTOR pixelFormat = {0}; pixelFormat.nSize = sizeof(pixelFormat); pixelFormat.nVersion = 1; pixelFormat.dwFlags = PFD_DRAW_TO_WINDOW|PFD_SUPPORT_OPENGL|PFD_DOUBLEBUFFER; pixelFormat.cColorBits = 32; pixelFormat.cDepthBits = 24; SetPixelFormat(temporaryDeviceContext, ChoosePixelFormat(temporaryDeviceContext, &pixelFormat), &pixelFormat); HGLRC temporaryRenderingContext = wglCreateContext(temporaryDeviceContext); wglMakeCurrent(temporaryDeviceContext, temporaryRenderingContext); const int formatAttributes[] = { WGL_DRAW_TO_WINDOW_ARB, 1, WGL_SUPPORT_OPENGL_ARB, 1, WGL_ACCELERATION_ARB, 0x2027, WGL_DOUBLE_BUFFER_ARB, 1, WGL_PIXEL_TYPE_ARB, 0x202B, WGL_COLOR_BITS_ARB, 32, WGL_DEPTH_BITS_ARB, 24, 0 }; const int contextAttributes[] = { WGL_CONTEXT_PROFILE_MASK_ARB, 1, WGL_CONTEXT_MAJOR_VERSION_ARB, 3, WGL_CONTEXT_MINOR_VERSION_ARB, 3, 0 }; int format, formatcount; RECT windowArea = {0, 0, width, height}; DWORD displayFlags = WS_POPUP; if(fullScreen) { DEVMODE dev = {0}; dev.dmSize = sizeof(DEVMODE); dev.dmFields = DM_PELSWIDTH|DM_PELSHEIGHT|DM_BITSPERPEL; dev.dmPelsWidth = width; dev.dmPelsHeight = height; dev.dmBitsPerPel = 32; ChangeDisplaySettings(&dev, CDS_FULLSCREEN); } else { displayFlags = WS_SYSMENU|WS_CAPTION|WS_MINIMIZEBOX|WS_BORDER; AdjustWindowRect(&windowArea, displayFlags, 0); windowArea.right -= windowArea.left; windowArea.bottom -= windowArea.top; windowArea.left = (GetSystemMetrics(SM_CXSCREEN)-windowArea.right )/2; windowArea.top = (GetSystemMetrics(SM_CYSCREEN)-windowArea.bottom)/2; } windowHandle = CreateWindowEx(WS_EX_APPWINDOW, L"classy class", title.c_str(), displayFlags, windowArea.left, windowArea.top, windowArea.right, windowArea.bottom, 0, 0, windowClass.hInstance, 0); deviceContext = GetDC(windowHandle); ((PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB"))(deviceContext, formatAttributes, 0, 1, &format, (UINT*)&formatcount); SetPixelFormat(deviceContext, format, &pixelFormat); renderingContext = ((PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB"))(deviceContext, 0, contextAttributes); wglMakeCurrent(deviceContext, renderingContext); wglDeleteContext(temporaryRenderingContext); ReleaseDC(temporaryWindow, temporaryDeviceContext); DestroyWindow(temporaryWindow); MSG message; while(PeekMessage(&message, 0, 0, 0, PM_REMOVE)); #include "glloading.h" printf("Vendor : %s\nRenderer : %s\nOpenGL version : %s\nGLSL version : %s\n",glGetString(GL_VENDOR), glGetString(GL_RENDERER), glGetString(GL_VERSION), glGetString(GL_SHADING_LANGUAGE_VERSION)); ShowWindow(windowHandle, SW_SHOW); glViewport(0, 0, width, height); glClearColor(.0f,.0f,.0f,.0f); glClear(GL_COLOR_BUFFER_BIT); SwapBuffers(deviceContext); Gdiplus::GdiplusStartupInput gdiInput; ZeroMemory(&gdiInput, sizeof(gdiInput)); gdiInput.GdiplusVersion = 1; Gdiplus::GdiplusStartup((ULONG_PTR*)&gdiToken, &gdiInput, 0); /*int charsize = 64; int fontsize = 16*charsize; Gdiplus::Font f(L"Segoe UI Light", float(charsize)*.7f, Gdiplus::FontStyleItalic, Gdiplus::UnitPixel, 0); Gdiplus::Bitmap canvas(fontsize, fontsize, PixelFormat32bppARGB); Gdiplus::Graphics gfx((Gdiplus::Image*)&canvas); gfx.Clear(Gdiplus::Color(0,0,0)); Gdiplus::SolidBrush brush(Gdiplus::Color(255,255,255)); Gdiplus::Rect r(0,0, fontsize, fontsize); for(int i = 0; i<16; i++) for(int j = 0; j<16; j++) { wchar_t k = i*16+j; Gdiplus::PointF point(float(charsize)*(float(i)+.2f), float(charsize)*(float(j)+.1f)); gfx.DrawString(&k, 1, &f, point, &brush); }*/ startTime = GetTickCount(); frameStartTime = startTime+1000; frameCount = 0; defaultid = 0; }