// // The guts of the shadow determination algorithm. // void Renderer::determineShadows (vector<Caster> casters, const Light& light, Camera& camera) { glPushAttrib(GL_ALL_ATTRIB_BITS); glDepthMask(0); // Disable depth buffer changes. glDisable(GL_CULL_FACE); // Enable drawing of backfaces. glEnable(GL_STENCIL_TEST); // Enable the stencil buffer. glStencilFunc(GL_ALWAYS, 0, ~0); // Always pass the stencil test. glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); // If we draw shadow volumes then we need to specify a color, otherwise // we disable drawing into the frame buffer. if (global.drawShadowVolumes) { glColor4f(1.0, 0.0, 0.0, 0.2); } else { glColorMask(0, 0, 0, 0); } for (vector<Caster>::iterator caster = casters.begin(); caster != casters.end(); ++caster) { if (!caster->isCaster()) continue; // Get the matricies required to draw the caster, and load a matrix which // places the caster into Camera space. glPushMatrix(); const Matrix& localToWorld = caster->getLocalToWorldMatrix(); glMultMatrix(localToWorld); // Transform the light position into object (or local) space by inverting // the localToWorld matrix and transforming the light position. Vec3 lightPosLocal = light.getPosition(); invertMatrix(localToWorld).transform(lightPosLocal); caster->getModel()->bindExtrudeBuffer(); // Setup the shader program for use. extrudeShader->useProgram(); glUniform4f(glGetUniformLocation(extrudeShader->getId(), "lightPos"), lightPosLocal.x, lightPosLocal.y, lightPosLocal.z, lightPosLocal.w); // TODO: Add z-Fail testing here. // z-Pass algorithm. //setStencilOp(GL_KEEP, GL_INCR_WRAP, GL_KEEP, GL_DECR_WRAP); //drawVolumeSides(lightPosLocal, *caster); // z-fail method (Carmacks Reverse). Works for nearly all situations but // isn't as efficient as the z-pass method above as it draws both the // front and back caps whereas the other methods doesn't require this. if (1) { setStencilOp(GL_DECR_WRAP, GL_KEEP, GL_INCR_WRAP, GL_KEEP); drawVolumeSides(lightPosLocal, *caster); drawDarkCap(lightPosLocal, *caster); drawLightCap(lightPosLocal, *caster); } /* // This is an alternative method for drawing the shadow volumes which // works but takes two passes and isn't as efficient. This is the // z-pass method too. glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glStencilOp(GL_KEEP, GL_KEEP, GL_INCR); drawVolumeSides(lightPosLocal, *caster); glCullFace(GL_FRONT); glStencilOp(GL_KEEP, GL_KEEP, GL_DECR); drawVolumeSides(lightPosLocal, *caster); */ extrudeShader->disableProgram(); glPopMatrix(); } glPopAttrib(); }
static cairo_int_status_t _cairo_gl_composite_setup_painted_clipping (cairo_gl_composite_t *setup, cairo_gl_context_t *ctx, int vertex_size) { cairo_int_status_t status = CAIRO_INT_STATUS_SUCCESS; cairo_gl_surface_t *dst = setup->dst; cairo_clip_t *clip = setup->clip; if (clip->num_boxes == 1 && clip->path == NULL) { _scissor_to_box (dst, &clip->boxes[0]); goto disable_stencil_buffer_and_return; } if (! _cairo_gl_ensure_stencil (ctx, setup->dst)) { status = CAIRO_INT_STATUS_UNSUPPORTED; goto disable_stencil_buffer_and_return; } /* We only want to clear the part of the stencil buffer * that we are about to use. It also does not hurt to * scissor around the painted clip. */ _cairo_gl_scissor_to_rectangle (dst, _cairo_clip_get_extents (clip)); /* The clip is not rectangular, so use the stencil buffer. */ glDepthMask (GL_TRUE); glEnable (GL_STENCIL_TEST); /* Texture surfaces have private depth/stencil buffers, so we can * rely on any previous clip being cached there. */ if (_cairo_gl_surface_is_texture (setup->dst)) { cairo_clip_t *old_clip = setup->dst->clip_on_stencil_buffer; if (_cairo_clip_equal (old_clip, setup->clip)) goto activate_stencil_buffer_and_return; if (old_clip) { _cairo_clip_destroy (setup->dst->clip_on_stencil_buffer); } setup->dst->clip_on_stencil_buffer = _cairo_clip_copy (setup->clip); } glClearStencil (0); glClear (GL_STENCIL_BUFFER_BIT); glStencilOp (GL_REPLACE, GL_REPLACE, GL_REPLACE); glStencilFunc (GL_EQUAL, 1, 0xffffffff); glColorMask (0, 0, 0, 0); status = _cairo_gl_msaa_compositor_draw_clip (ctx, setup, clip); if (unlikely (status)) { glColorMask (1, 1, 1, 1); goto disable_stencil_buffer_and_return; } /* We want to only render to the stencil buffer, so draw everything now. Flushing also unbinds the VBO, which we want to rebind for regular drawing. */ _cairo_gl_composite_flush (ctx); _cairo_gl_composite_setup_vbo (ctx, vertex_size); activate_stencil_buffer_and_return: glColorMask (1, 1, 1, 1); glStencilOp (GL_KEEP, GL_KEEP, GL_KEEP); glStencilFunc (GL_EQUAL, 1, 0xffffffff); return CAIRO_INT_STATUS_SUCCESS; disable_stencil_buffer_and_return: _disable_stencil_buffer (); return status; }
void ColorMaskChunk::deactivate(DrawEnv *, UInt32) { glColorMask(true, true, true, true); }
void Graphics::SetSpriteMaskWriteMode() { glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_TRUE); }
void SceneRenderer::render( bool _lastFrame, bool _sameFrame, bool fullWindow) { static const GLfloat blindnessColor[4] = { 1.0f, 1.0f, 0.0f, 1.0f }; static const GLfloat dimnessColor[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; static const float dimDensity = 0.75f; bool lighting = BZDB.isTrue("lighting"); lastFrame = _lastFrame; sameFrame = _sameFrame; // avoid OpenGL calls as long as possible -- there's a good // chance we're waiting on the vertical retrace. // set the view frustum if (sceneIterator) sceneIterator->resetFrustum(&frustum); // get the important lights in the scene int i; int numLights = 0; if (!sameFrame) { clearLights(); if (sceneIterator && !blank && lighting) { // add lights sceneIterator->reset(); SceneNode* node; while ((node = sceneIterator->getNext()) != NULL) node->addLight(*this); numLights = lights.size(); // pick maxLights most important light sources // should go by full lighting function but we'll just go by distance if (numLights > maxLights) { const GLfloat* eye = frustum.getEye(); for (i = 0; i < maxLights; i++) { GLfloat maxImportance = lights[i]->getImportance(eye); for (int j = i + 1; j < numLights; j++) { GLfloat importance = lights[j]->getImportance(eye); if (importance > maxImportance) { OpenGLLight* temp = lights[i]; lights[j] = lights[i]; lights[i] = temp; maxImportance = importance; } } } numLights = maxLights; } } } // get the nodes to draw if (!blank) { // empty the render node lists in preparation for the next frame OpenGLGState::clearLists(); orderedList.clear(); shadowList.clear(); flareLightList.clear(); // make the lists of render nodes sorted in optimal rendering order if (sceneIterator) { sceneIterator->reset(); SceneNode* node; while ((node = sceneIterator->getNext()) != NULL) node->getRenderNodes(*this); } // sort ordered list in reverse depth order if (!inOrder) orderedList.sort(frustum.getEye()); } // prepare transforms // note -- lights should not be positioned before view is set frustum.executeDeepProjection(); glPushMatrix(); frustum.executeView(); // turn sunlight on -- the ground needs it if (lighting && sunOrMoonUp) { theSun.execute(SunLight); theSun.enableLight(SunLight); } // turn on fog for teleporter blindness if close to a teleporter float teleporterProximity = 0.0f; if (!blank && LocalPlayer::getMyTank() && (LocalPlayer::getMyTank()->getTeam() != ObserverTeam)) teleporterProximity = LocalPlayer::getMyTank()->getTeleporterProximity(); float worldSize = BZDB.eval(StateDatabase::BZDB_WORLDSIZE); bool reallyUseFogHack = useFogHack && (useQualityValue >= 2); if (reallyUseFogHack) { if (useDimming) { const float density = dimDensity; glFogi(GL_FOG_MODE, GL_LINEAR); glFogf(GL_FOG_START, -density * 1000.0f * worldSize); glFogf(GL_FOG_END, (1.0f - density) * 1000.0f * worldSize); glFogfv(GL_FOG_COLOR, dimnessColor); glEnable(GL_FOG); } else if (teleporterProximity > 0.0f && useFogHack) { const float density = (teleporterProximity > 0.75f) ? 1.0f : teleporterProximity / 0.75f; glFogi(GL_FOG_MODE, GL_LINEAR); glFogf(GL_FOG_START, -density * 1000.0f * worldSize); glFogf(GL_FOG_END, (1.0f - density) * 1000.0f * worldSize); glFogfv(GL_FOG_COLOR, blindnessColor); glEnable(GL_FOG); } } // set scissor glScissor(window.getOriginX(), window.getOriginY() + window.getHeight() - window.getViewHeight(), window.getWidth(), window.getViewHeight()); if (useDepthComplexityOn) { // glEnable(GL_STENCIL_TEST); // glClear(GL_STENCIL_BUFFER_BIT); // glStencilFunc(GL_ALWAYS, 0, 0xf); // glStencilOp(GL_KEEP, GL_INCR, GL_INCR); } if (useHiddenLineOn) { //glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // glClear(GL_COLOR_BUFFER_BIT); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); } else if (useWireframeOn) { //glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // glClear(GL_COLOR_BUFFER_BIT); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); } // prepare z buffer /* if (BZDB.isTrue("zbuffer")) { if (sameFrame && ++depthRange == numDepthRanges) depthRange = 0; if (exposed || useHiddenLineOn || --depthRange < 0) { depthRange = numDepthRanges - 1; glClear(GL_DEPTH_BUFFER_BIT); exposed = false; } if (!sameFrame && numDepthRanges != 1) { if (useHiddenLineOn) { glDepthRange(0.0, 1.0); } else { GLclampd x_near = (GLclampd)depthRange * depthRangeSize; glDepthRange(x_near, x_near + depthRangeSize); } } } */ // draw start of background (no depth testing) OpenGLGState::resetState(); if (background) { background->setBlank(blank); background->setInvert(invert); background->renderSkyAndGround(*this, fullWindow); } // prepare the other lights but don't turn them on yet -- // we may need to turn them on when drawing the background. if (lighting) { for (i = 0; i < numLights; i++) lights[i]->execute(i + reservedLights); } // draw rest of background if (background) background->render(*this); if (!blank) { if (lighting) { // now turn on the remaining lights for (i = 0; i < numLights; i++) OpenGLLight::enableLight(i + reservedLights); } frustum.executeProjection(); if (BZDB.isTrue("zbuffer")) glEnable(GL_DEPTH_TEST); if (useHiddenLineOn) { #if defined(GL_VERSION_1_1) glEnable(GL_POLYGON_OFFSET_FILL); #elif defined(GL_EXT_polygon_offset) glEnable(GL_POLYGON_OFFSET_EXT); #endif } // render the normal stuff doRender(); if (useHiddenLineOn) { #if defined(GL_VERSION_1_1) glDisable(GL_POLYGON_OFFSET_FILL); #elif defined(GL_EXT_polygon_offset) glDisable(GL_POLYGON_OFFSET_EXT); #endif glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); doRender(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } OpenGLGState::resetState(); // shut off lights if (lighting) { theSun.enableLight(SunLight, false); for (i = 0; i < numLights; i++) OpenGLLight::enableLight(i + reservedLights, false); } if (BZDB.isTrue("zbuffer")) glDisable(GL_DEPTH_TEST); // FIXME -- must do post-rendering: flare lights, etc. // flare lights are in world coordinates. trace ray to that world // position and calculate opacity. if opaque then don't render // flare, otherwise modulate input color by opacity and draw a // billboard texture (constant size in screen space). } // back to original state if (!useHiddenLineOn && useWireframeOn) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glPopMatrix(); if ((reallyUseFogHack && (teleporterProximity > 0.0f || useDimming))) glDisable(GL_FOG); if (!reallyUseFogHack) { float density = 0.0f; const GLfloat* color = NULL; if (useDimming) { density = dimDensity; color = dimnessColor; } else if (teleporterProximity > 0.0f) { density = (teleporterProximity > 0.75f) ? 1.0f : teleporterProximity / 0.75f; color = blindnessColor; } if (density > 0.0f && color != NULL) { glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glColor4f(color[0], color[1], color[2], density); glRectf(-1.0f, -1.0f, 1.0f, 1.0f); } } if (useDepthComplexityOn) { static const GLfloat depthColors[][3] = { { 0.0f, 0.0f, 0.0f }, // black -- 0 times { 0.5f, 0.0f, 1.0f }, // purple -- 1 time { 0.0f, 0.0f, 1.0f }, // blue -- 2 times { 0.0f, 1.0f, 1.0f }, // cyan -- 3 times { 0.0f, 1.0f, 0.0f }, // green -- 4 times { 1.0f, 1.0f, 0.0f }, // yellow -- 5 times { 1.0f, 0.5f, 0.0f }, // orange -- 6 times { 1.0f, 0.0f, 0.0f } // red -- 7 or more }; static const int numColors = countof(depthColors); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); for (i = 0; i < numColors; i++) { glStencilFunc(i == numColors - 1 ? GL_LEQUAL : GL_EQUAL, i, 0xf); glColor3fv(depthColors[i]); glRectf(-1.0f, -1.0f, 1.0f, 1.0f); } glDisable(GL_STENCIL_TEST); } }
void nuiGLPainter::DrawArray(nuiRenderArray* pArray) { mRenderOperations++; mBatches++; //glEnable(GL_TEXTURE_2D); //glEnable(GL_TEXTURE_2D); if (!mEnableDrawArray) { pArray->Release(); return; } static uint32 ops = 0; static uint32 skipped_ops = 0; ops++; const nuiMatrix& rM(mMatrixStack.top()); float bounds[6]; pArray->GetBounds(bounds); if (rM.Elt.M11 == 1.0f && rM.Elt.M22 == 1.0f && rM.Elt.M33 == 1.0f && rM.Elt.M44 == 1.0f && rM.Elt.M12 == 0.0f && rM.Elt.M13 == 0.0f //&& rM.Elt.M14 == 0.0f && rM.Elt.M21 == 0.0f && rM.Elt.M23 == 0.0f //&& rM.Elt.M24 == 0.0f && rM.Elt.M31 == 0.0f && rM.Elt.M32 == 0.0f && rM.Elt.M34 == 0.0f && rM.Elt.M41 == 0.0f && rM.Elt.M42 == 0.0f && rM.Elt.M43 == 0.0f) { bounds[0] += rM.Elt.M14; bounds[1] += rM.Elt.M24; //bounds[2] += rM.Elt.M34; bounds[3] += rM.Elt.M14; bounds[4] += rM.Elt.M24; //bounds[5] += rM.Elt.M34; if ( (bounds[0] > mClip.Right()) || (bounds[1] > mClip.Bottom()) || (bounds[3] < mClip.Left()) || (bounds[4] < mClip.Top()) ) { skipped_ops++; // #ifdef _DEBUG // if (!(skipped_ops % 100)) // printf("optim (%d / %d) - %2.2f%%\n", skipped_ops, ops, (float)skipped_ops * 100.0f / (float)ops); // #endif return; } } // else // { // nglVectorf v1(bounds[0], bounds[1], 0); // topleft(x, y) // nglVectorf v2(bounds[3], bounds[4], 0); // bottomright(x, y) // v1 = rM * v1; // v2 = rM * v2; // // if ( // (v1[0] > mClip.Right()) || // (v1[1] > mClip.Bottom()) || // (v2[0] < mClip.Left()) || // (v2[1] < mClip.Top()) // ) // { // return; // } // } uint32 s = pArray->GetSize(); total += s; totalinframe += s; mins = MIN(mins, s); maxs = MAX(maxs, s); //printf("DA (%d) min = %d max = %d\n", s, mins, maxs); if (!s) { pArray->Release(); return; } if (mClip.GetWidth() <= 0 || mClip.GetHeight() <= 0) { pArray->Release(); return; } mVertices += s; GLenum mode = pArray->GetMode(); //NGL_OUT(_T("GL Array Mode: %d vertice count %d\n"), mode, size); /* switch (pArray->GetMode()) { LOGENUM(GL_POINTS); LOGENUM(GL_LINES); LOGENUM(GL_LINE_LOOP); LOGENUM(GL_LINE_STRIP); //LOGENUM(GL_TRIANGLES); LOGENUM(GL_TRIANGLE_STRIP); LOGENUM(GL_TRIANGLE_FAN); //LOGENUM(GL_QUADS); LOGENUM(GL_QUAD_STRIP); LOGENUM(GL_POLYGON); } */ NUI_RETURN_IF_RENDERING_DISABLED; bool NeedTranslateHack = pArray->IsShape() || ((mode == GL_POINTS || mode == GL_LINES || mode == GL_LINE_LOOP || mode == GL_LINE_STRIP) && !pArray->Is3DMesh()); float hackX; float hackY; if (NeedTranslateHack) { const float ratio=0.5f; #ifdef _UIKIT_ hackX = ratio; hackY = ratio; #else if (mAngle == 0) { hackX = ratio; hackY = ratio; } else if (mAngle == 90) { hackX = 0; hackY = ratio; } else if (mAngle == 180) { hackX = 0; hackY = 0; } else/*mAngle == 270*/ { hackX = ratio; hackY = 0; } #endif glTranslatef(hackX, hackY, 0); } #ifdef NUI_USE_ANTIALIASING if (mState.mAntialiasing) { #ifdef NUI_USE_MULTISAMPLE_AA glHint(GL_MULTISAMPLE_FILTER_HINT_NV, GL_NICEST); glEnable(GL_MULTISAMPLE_ARB); nuiCheckForGLErrors(); #else glEnable(GL_POLYGON_SMOOTH); glEnable(GL_BLEND); BlendFuncSeparate(GL_SRC_ALPHA_SATURATE, GL_ONE); nuiCheckForGLErrors(); #endif } #endif // NUI_USE_ANTIALIASING if (pArray->IsArrayEnabled(nuiRenderArray::eVertex)) { glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(nuiRenderArray::Vertex), &pArray->GetVertices()[0].mX); nuiCheckForGLErrors(); } else glDisableClientState(GL_VERTEX_ARRAY); if (pArray->IsArrayEnabled(nuiRenderArray::eColor)) { glEnableClientState(GL_COLOR_ARRAY); glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(nuiRenderArray::Vertex), &pArray->GetVertices()[0].mR); nuiCheckForGLErrors(); } else { glDisableClientState(GL_COLOR_ARRAY); nuiColor c; switch (pArray->GetMode()) { case GL_POINTS: case GL_LINES: case GL_LINE_LOOP: case GL_LINE_STRIP: c = mState.mStrokeColor; break; case GL_TRIANGLES: case GL_TRIANGLE_STRIP: case GL_TRIANGLE_FAN: #ifndef _OPENGL_ES_ case GL_QUADS: case GL_QUAD_STRIP: case GL_POLYGON: #endif c = mState.mFillColor; break; } glColor4f(c.Red(), c.Green(), c.Blue(), c.Alpha()); nuiCheckForGLErrors(); } if (pArray->IsArrayEnabled(nuiRenderArray::eTexCoord)) { glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(2, GL_FLOAT, sizeof(nuiRenderArray::Vertex), &pArray->GetVertices()[0].mTX); nuiCheckForGLErrors(); } else { glDisableClientState(GL_TEXTURE_COORD_ARRAY); } //glDisableClientState(GL_COLOR_ARRAY); //glColor4f(0.5,0.5,0.5,0.5); /* if (pArray->IsArrayEnabled(nuiRenderArray::eNormal)) { glEnableClientState(GL_NORMAL_ARRAY); glNormalPointer(GL_FLOAT, sizeof(nuiRenderArray::Vertex)-12, &pArray->GetVertices()[0].mNX); nuiCheckForGLErrors(); } else glDisableClientState(GL_NORMAL_ARRAY); */ /* if (pArray->IsArrayEnabled(nuiRenderArray::eEdgeFlag)) { glEnableClientState(GL_EDGE_FLAG_ARRAY); glEdgeFlagPointer(sizeof(nuiRenderArray::Vertex), &pArray->GetVertices()[0].mEdgeFlag); nuiCheckForGLErrors(); } else glDisableClientState(GL_EDGE_FLAG_ARRAY); */ nuiCheckForGLErrors(); if (mpSurface && mTwoPassBlend) { glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE); uint32 arraycount = pArray->GetIndexArrayCount(); if (!arraycount) { glDrawArrays(mode, 0, s); } else { for (uint32 i = 0; i < arraycount; i++) { nuiRenderArray::IndexArray& array(pArray->GetIndexArray(i)); #ifdef _UIKIT_ glDrawElements(array.mMode, array.mIndices.size(), GL_UNSIGNED_SHORT, &(array.mIndices[0])); #else glDrawElements(array.mMode, array.mIndices.size(), GL_UNSIGNED_INT, &(array.mIndices[0])); #endif } } nuiCheckForGLErrors(); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_TRUE); glBlendFunc(mSrcAlpha, mDstAlpha); if (!arraycount) { glDrawArrays(mode, 0, s); } else { for (uint32 i = 0; i < arraycount; i++) { nuiRenderArray::IndexArray& array(pArray->GetIndexArray(i)); #ifdef _UIKIT_ glDrawElements(array.mMode, array.mIndices.size(), GL_UNSIGNED_SHORT, &(array.mIndices[0])); #else glDrawElements(array.mMode, array.mIndices.size(), GL_UNSIGNED_INT, &(array.mIndices[0])); #endif } } glBlendFunc(mSrcColor, mDstColor); nuiCheckForGLErrors(); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); } else { uint32 arraycount = pArray->GetIndexArrayCount(); if (!arraycount) { glDrawArrays(mode, 0, s); } else { for (uint32 i = 0; i < arraycount; i++) { nuiRenderArray::IndexArray& array(pArray->GetIndexArray(i)); #ifdef _UIKIT_ glDrawElements(array.mMode, array.mIndices.size(), GL_UNSIGNED_SHORT, &(array.mIndices[0])); #else glDrawElements(array.mMode, array.mIndices.size(), GL_UNSIGNED_INT, &(array.mIndices[0])); #endif } } nuiCheckForGLErrors(); } #ifdef NUI_USE_ANTIALIASING if (mState.mAntialiasing) { #ifdef NUI_USE_MULTISAMPLE_AA glDisable(GL_MULTISAMPLE_ARB); #else glDisable(GL_POLYGON_SMOOTH); glDisable(GL_BLEND); BlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); #endif nuiCheckForGLErrors(); } else #endif // NUI_USE_ANTIALIASING { //#TEST meeloo disabling AA texture // if (pArray->UseGLAATexture()) // { // glMatrixMode(GL_TEXTURE); // glPopMatrix(); // glMatrixMode(GL_MODELVIEW); // glPopMatrix(); // // if (mState.mpTexture && mState.mTexturing) // { // if (mTextureTarget != GL_TEXTURE_2D) // { // glDisable(GL_TEXTURE_2D); // glEnable(mTextureTarget); // } // // UploadTexture(mState.mpTexture); // } // else // { // glDisable(GL_TEXTURE_2D); // } // // if (!mState.mBlending) // glDisable(GL_BLEND); // if (mState.mBlendFunc != nuiBlendTransp) // { // GLenum src, dst; // nuiGetBlendFuncFactors(mState.mBlendFunc, src, dst); // glBlendFunc(src, dst); // } // //ApplyTexture(mState, true); // } // else if (NeedTranslateHack) glTranslatef(-hackX, -hackY, 0); } // glColor3f(1.0f, 1.0f, 1.0f); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); pArray->Release(); nuiCheckForGLErrors(); }
/* ================ R_RenderView ================ */ void R_RenderView (void) { double time1, time2; if (r_norefresh.value) return; if (!cl.worldmodel) Sys_Error ("R_RenderView: NULL worldmodel"); time1 = 0; /* avoid compiler warning */ if (r_speeds.value) { glFinish (); time1 = Sys_DoubleTime (); //johnfitz -- rendering statistics rs_brushpolys = rs_aliaspolys = rs_skypolys = rs_particles = rs_fogpolys = rs_megatexels = rs_dynamiclightmaps = rs_aliaspasses = rs_skypasses = rs_brushpasses = 0; } else if (gl_finish.value) glFinish (); R_SetupView (); //johnfitz -- this does everything that should be done once per frame //johnfitz -- stereo rendering -- full of hacky goodness if (r_stereo.value) { float eyesep = CLAMP(-8.0f, r_stereo.value, 8.0f); float fdepth = CLAMP(32.0f, r_stereodepth.value, 1024.0f); AngleVectors (r_refdef.viewangles, vpn, vright, vup); //render left eye (red) glColorMask(1, 0, 0, 1); VectorMA (r_refdef.vieworg, -0.5f * eyesep, vright, r_refdef.vieworg); frustum_skew = 0.5 * eyesep * NEARCLIP / fdepth; srand((int) (cl.time * 1000)); //sync random stuff between eyes R_RenderScene (); //render right eye (cyan) glClear (GL_DEPTH_BUFFER_BIT); glColorMask(0, 1, 1, 1); VectorMA (r_refdef.vieworg, 1.0f * eyesep, vright, r_refdef.vieworg); frustum_skew = -frustum_skew; srand((int) (cl.time * 1000)); //sync random stuff between eyes R_RenderScene (); //restore glColorMask(1, 1, 1, 1); VectorMA (r_refdef.vieworg, -0.5f * eyesep, vright, r_refdef.vieworg); frustum_skew = 0.0f; } else { R_RenderScene (); } //johnfitz //johnfitz -- modified r_speeds output time2 = Sys_DoubleTime (); if (r_pos.value) Con_Printf ("x %i y %i z %i (pitch %i yaw %i roll %i)\n", (int)cl_entities[cl.viewentity].origin[0], (int)cl_entities[cl.viewentity].origin[1], (int)cl_entities[cl.viewentity].origin[2], (int)cl.viewangles[PITCH], (int)cl.viewangles[YAW], (int)cl.viewangles[ROLL]); else if (r_speeds.value == 2) Con_Printf ("%3i ms %4i/%4i wpoly %4i/%4i epoly %3i lmap %4i/%4i sky %1.1f mtex\n", (int)((time2-time1)*1000), rs_brushpolys, rs_brushpasses, rs_aliaspolys, rs_aliaspasses, rs_dynamiclightmaps, rs_skypolys, rs_skypasses, TexMgr_FrameUsage ()); else if (r_speeds.value) Con_Printf ("%3i ms %4i wpoly %4i epoly %3i lmap\n", (int)((time2-time1)*1000), rs_brushpolys, rs_aliaspolys, rs_dynamiclightmaps); //johnfitz }
void GLGSRender::ExecCMD() { //return; if(!LoadProgram()) { ConLog.Error("LoadProgram failed."); Emu.Pause(); return; } if(!m_fbo.IsCreated() || RSXThread::m_width != last_width || RSXThread::m_height != last_height || last_depth_format != m_surface_depth_format) { ConLog.Warning("New FBO (%dx%d)", RSXThread::m_width, RSXThread::m_height); last_width = RSXThread::m_width; last_height = RSXThread::m_height; last_depth_format = m_surface_depth_format; m_fbo.Create(); checkForGlError("m_fbo.Create"); m_fbo.Bind(); m_rbo.Create(4 + 1); checkForGlError("m_rbo.Create"); for(int i=0; i<4; ++i) { m_rbo.Bind(i); m_rbo.Storage(GL_RGBA, RSXThread::m_width, RSXThread::m_height); checkForGlError("m_rbo.Storage(GL_RGBA)"); } m_rbo.Bind(4); switch(m_surface_depth_format) { case 1: m_rbo.Storage(GL_DEPTH_COMPONENT16, RSXThread::m_width, RSXThread::m_height); checkForGlError("m_rbo.Storage(GL_DEPTH_COMPONENT16)"); break; case 2: m_rbo.Storage(GL_DEPTH24_STENCIL8, RSXThread::m_width, RSXThread::m_height); checkForGlError("m_rbo.Storage(GL_DEPTH24_STENCIL8)"); break; default: ConLog.Error("Bad depth format! (%d)", m_surface_depth_format); assert(0); break; } for(int i=0; i<4; ++i) { m_fbo.Renderbuffer(GL_COLOR_ATTACHMENT0 + i, m_rbo.GetId(i)); checkForGlError(wxString::Format("m_fbo.Renderbuffer(GL_COLOR_ATTACHMENT%d)", i)); } m_fbo.Renderbuffer(GL_DEPTH_ATTACHMENT, m_rbo.GetId(4)); checkForGlError("m_fbo.Renderbuffer(GL_DEPTH_ATTACHMENT)"); if(m_surface_depth_format == 2) { m_fbo.Renderbuffer(GL_STENCIL_ATTACHMENT, m_rbo.GetId(4)); checkForGlError("m_fbo.Renderbuffer(GL_STENCIL_ATTACHMENT)"); } } if(!m_set_surface_clip_horizontal) { m_surface_clip_x = 0; m_surface_clip_w = RSXThread::m_width; } if(!m_set_surface_clip_vertical) { m_surface_clip_y = 0; m_surface_clip_h = RSXThread::m_height; } m_fbo.Bind(); if(Ini.GSDumpDepthBuffer.GetValue()) WriteDepthBuffer(); static const GLenum draw_buffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 }; switch(m_surface_colour_target) { case 0x0: break; case 0x1: glDrawBuffer(draw_buffers[0]); break; case 0x2: glDrawBuffer(draw_buffers[1]); break; case 0x13: glDrawBuffers(2, draw_buffers); break; case 0x17: glDrawBuffers(3, draw_buffers); break; case 0x1f: glDrawBuffers(4, draw_buffers); break; default: ConLog.Error("Bad surface colour target: %d", m_surface_colour_target); break; } if(m_set_color_mask) { glColorMask(m_color_mask_r, m_color_mask_g, m_color_mask_b, m_color_mask_a); checkForGlError("glColorMask"); } if(m_set_viewport_horizontal && m_set_viewport_vertical) { glViewport(m_viewport_x, RSXThread::m_height-m_viewport_y-m_viewport_h, m_viewport_w, m_viewport_h); checkForGlError("glViewport"); } if(m_set_scissor_horizontal && m_set_scissor_vertical) { glScissor(m_scissor_x, RSXThread::m_height-m_scissor_y-m_scissor_h, m_scissor_w, m_scissor_h); checkForGlError("glScissor"); } if(m_clear_surface_mask) { GLbitfield f = 0; if (m_clear_surface_mask & 0x1) { glClearDepth(m_clear_surface_z / (float)0xffffff); f |= GL_DEPTH_BUFFER_BIT; } if (m_clear_surface_mask & 0x2) { glClearStencil(m_clear_surface_s); f |= GL_STENCIL_BUFFER_BIT; } if (m_clear_surface_mask & 0xF0) { glClearColor( m_clear_surface_color_r / 255.0f, m_clear_surface_color_g / 255.0f, m_clear_surface_color_b / 255.0f, m_clear_surface_color_a / 255.0f); f |= GL_COLOR_BUFFER_BIT; } glClear(f); } if(m_set_front_polygon_mode) { glPolygonMode(GL_FRONT, m_front_polygon_mode); checkForGlError("glPolygonMode"); } Enable(m_depth_test_enable, GL_DEPTH_TEST); Enable(m_set_alpha_test, GL_ALPHA_TEST); Enable(m_set_depth_bounds_test, GL_DEPTH_BOUNDS_TEST_EXT); Enable(m_set_blend, GL_BLEND); Enable(m_set_logic_op, GL_LOGIC_OP); Enable(m_set_cull_face_enable, GL_CULL_FACE); Enable(m_set_dither, GL_DITHER); Enable(m_set_stencil_test, GL_STENCIL_TEST); Enable(m_set_line_smooth, GL_LINE_SMOOTH); Enable(m_set_poly_smooth, GL_POLYGON_SMOOTH); Enable(m_set_poly_offset_fill, GL_POLYGON_OFFSET_FILL); Enable(m_set_poly_offset_line, GL_POLYGON_OFFSET_LINE); Enable(m_set_poly_offset_point, GL_POLYGON_OFFSET_POINT); //Enable(m_set_restart_index, GL_PRIMITIVE_RESTART); //Requires OpenGL 3.1+ if(m_set_clip_plane) { Enable(m_clip_plane_0, GL_CLIP_PLANE0); Enable(m_clip_plane_1, GL_CLIP_PLANE1); Enable(m_clip_plane_2, GL_CLIP_PLANE2); Enable(m_clip_plane_3, GL_CLIP_PLANE3); Enable(m_clip_plane_4, GL_CLIP_PLANE4); Enable(m_clip_plane_5, GL_CLIP_PLANE5); checkForGlError("m_set_clip_plane"); } checkForGlError("glEnable"); if(m_set_two_sided_stencil_test_enable) { if(m_set_stencil_fail && m_set_stencil_zfail && m_set_stencil_zpass) { glStencilOpSeparate(GL_FRONT, m_stencil_fail, m_stencil_zfail, m_stencil_zpass); checkForGlError("glStencilOpSeparate"); } if(m_set_stencil_mask) { glStencilMaskSeparate(GL_FRONT, m_stencil_mask); checkForGlError("glStencilMaskSeparate"); } if(m_set_stencil_func && m_set_stencil_func_ref && m_set_stencil_func_mask) { glStencilFuncSeparate(GL_FRONT, m_stencil_func, m_stencil_func_ref, m_stencil_func_mask); checkForGlError("glStencilFuncSeparate"); } if(m_set_back_stencil_fail && m_set_back_stencil_zfail && m_set_back_stencil_zpass) { glStencilOpSeparate(GL_BACK, m_back_stencil_fail, m_back_stencil_zfail, m_back_stencil_zpass); checkForGlError("glStencilOpSeparate(GL_BACK)"); } if(m_set_back_stencil_mask) { glStencilMaskSeparate(GL_BACK, m_back_stencil_mask); checkForGlError("glStencilMaskSeparate(GL_BACK)"); } if(m_set_back_stencil_func && m_set_back_stencil_func_ref && m_set_back_stencil_func_mask) { glStencilFuncSeparate(GL_BACK, m_back_stencil_func, m_back_stencil_func_ref, m_back_stencil_func_mask); checkForGlError("glStencilFuncSeparate(GL_BACK)"); } } else { if(m_set_stencil_fail && m_set_stencil_zfail && m_set_stencil_zpass) { glStencilOp(m_stencil_fail, m_stencil_zfail, m_stencil_zpass); checkForGlError("glStencilOp"); } if(m_set_stencil_mask) { glStencilMask(m_stencil_mask); checkForGlError("glStencilMask"); } if(m_set_stencil_func && m_set_stencil_func_ref && m_set_stencil_func_mask) { glStencilFunc(m_stencil_func, m_stencil_func_ref, m_stencil_func_mask); checkForGlError("glStencilFunc"); } } if(m_set_shade_mode) { glShadeModel(m_shade_mode); checkForGlError("glShadeModel"); } if(m_set_depth_mask) { glDepthMask(m_depth_mask); checkForGlError("glDepthMask"); } if(m_set_depth_func) { glDepthFunc(m_depth_func); //ConLog.Warning("glDepthFunc(0x%x)", m_depth_func); checkForGlError("glDepthFunc"); } if(m_set_depth_bounds) { //ConLog.Warning("glDepthBounds(%f, %f)", m_depth_bounds_min, m_depth_bounds_max); glDepthBounds(m_depth_bounds_min, m_depth_bounds_max); checkForGlError("glDepthBounds"); } if(m_set_clip) { //ConLog.Warning("glDepthRangef(%f, %f)", m_clip_min, m_clip_max); glDepthRangef(m_clip_min, m_clip_max); checkForGlError("glDepthRangef"); } if(m_set_line_width) { glLineWidth(m_line_width / 255.f); checkForGlError("glLineWidth"); } if(m_set_blend_equation) { glBlendEquationSeparate(m_blend_equation_rgb, m_blend_equation_alpha); checkForGlError("glBlendEquationSeparate"); } if(m_set_blend_sfactor && m_set_blend_dfactor) { glBlendFuncSeparate(m_blend_sfactor_rgb, m_blend_dfactor_rgb, m_blend_sfactor_alpha, m_blend_dfactor_alpha); checkForGlError("glBlendFuncSeparate"); } if(m_set_blend_color) { glBlendColor(m_blend_color_r, m_blend_color_g, m_blend_color_b, m_blend_color_a); checkForGlError("glBlendColor"); } if(m_set_cull_face) { glCullFace(m_cull_face); checkForGlError("glCullFace"); } if(m_set_alpha_func && m_set_alpha_ref) { glAlphaFunc(m_alpha_func, m_alpha_ref); checkForGlError("glAlphaFunc"); } if(m_set_fog_mode) { glFogi(GL_FOG_MODE, m_fog_mode); checkForGlError("glFogi(GL_FOG_MODE)"); } if(m_set_fog_params) { glFogf(GL_FOG_START, m_fog_param0); checkForGlError("glFogf(GL_FOG_START)"); glFogf(GL_FOG_END, m_fog_param1); checkForGlError("glFogf(GL_FOG_END)"); } if(m_set_restart_index) { ConLog.Warning("m_set_restart_index requires glPrimitiveRestartIndex()"); //glPrimitiveRestartIndex(m_restart_index); //Requires OpenGL 3.1+ //checkForGlError("glPrimitiveRestartIndex"); } if(m_indexed_array.m_count && m_draw_array_count) { ConLog.Warning("m_indexed_array.m_count && draw_array_count"); } for(u32 i=0; i<m_textures_count; ++i) { if(!m_textures[i].IsEnabled()) continue; glActiveTexture(GL_TEXTURE0 + i); checkForGlError("glActiveTexture"); m_gl_textures[i].Create(); m_gl_textures[i].Bind(); checkForGlError(wxString::Format("m_gl_textures[%d].Bind", i)); m_program.SetTex(i); m_gl_textures[i].Init(m_textures[i]); checkForGlError(wxString::Format("m_gl_textures[%d].Init", i)); } m_vao.Bind(); if(m_indexed_array.m_count) { LoadVertexData(m_indexed_array.index_min, m_indexed_array.index_max - m_indexed_array.index_min + 1); } EnableVertexData(m_indexed_array.m_count ? true : false); InitVertexData(); InitFragmentData(); if(m_indexed_array.m_count) { switch(m_indexed_array.m_type) { case 0: glDrawElements(m_draw_mode - 1, m_indexed_array.m_count, GL_UNSIGNED_INT, nullptr); checkForGlError("glDrawElements #4"); break; case 1: glDrawElements(m_draw_mode - 1, m_indexed_array.m_count, GL_UNSIGNED_SHORT, nullptr); checkForGlError("glDrawElements #2"); break; default: ConLog.Error("Bad indexed array type (%d)", m_indexed_array.m_type); break; } DisableVertexData(); m_indexed_array.Reset(); } if(m_draw_array_count) { //ConLog.Warning("glDrawArrays(%d,%d,%d)", m_draw_mode - 1, m_draw_array_first, m_draw_array_count); glDrawArrays(m_draw_mode - 1, 0, m_draw_array_count); checkForGlError("glDrawArrays"); DisableVertexData(); } if(Ini.GSDumpColorBuffers.GetValue()) WriteBuffers(); }
PsychError SCREENTransformTexture(void) { PsychWindowRecordType *sourceRecord, *targetRecord, *proxyRecord, *sourceRecord2; int testarg, tmpimagingmode, specialFlags, usefloatformat, d; PsychFBO *fboptr; GLint fboInternalFormat; psych_bool needzbuffer; // All subfunctions should have these two lines. PsychPushHelp(useString, synopsisString, seeAlsoString); if(PsychIsGiveHelp()) {PsychGiveHelp(); return(PsychError_none); }; PsychErrorExit(PsychCapNumInputArgs(5)); PsychErrorExit(PsychRequireNumInputArgs(2)); PsychErrorExit(PsychCapNumOutputArgs(1)); // OpenGL FBO's supported? Otherwise this is a no-go... if (glBindFramebufferEXT == NULL || glUseProgram == NULL) { // Game over! printf("PTB-ERROR: Sorry, your graphics driver & hardware does not support the required OpenGL framebuffer object extension or\n"); printf("PTB-ERROR: the OpenGL shading language for hardware accelerated fragment processing. This function is therefore disabled.\n"); printf("PTB-ERROR: You will need at least a NVidia GeforceFX-5200, a ATI Radeon 9600 or a Intel GMA-950 graphics card for this\n"); printf("PTB-ERROR: to work. If you have such a card (or a more recent one) then you'll need to update your graphics drivers.\n\n"); PsychErrorExitMsg(PsychError_user, "Screen('TransformTexture') command unsupported on your combination of graphics hardware & driver."); } // Get the window structure for the source texture. PsychAllocInWindowRecordArg(1, TRUE, &sourceRecord); if (!PsychIsTexture(sourceRecord)) PsychErrorExitMsg(PsychError_user, "'sourceTexture' argument must be a handle to a texture or offscreen window."); // Get the window structure for the proxy object. PsychAllocInWindowRecordArg(2, TRUE, &proxyRecord); if (proxyRecord->windowType!=kPsychProxyWindow) PsychErrorExitMsg(PsychError_user, "'transformProxyPtr' argument must be a handle to a proxy object."); // Test if optional specialFlags are provided: specialFlags=0; PsychCopyInIntegerArg(5, FALSE, &specialFlags); // Activate rendering context of the proxy object and soft-reset the // drawing engine, so we're in a well defined state. The value 1 means: Reset safely, ie. do any // framebuffer backups that might be needed before NULL-ing the binding: PsychSetDrawingTarget(0x1); PsychSetGLContext(proxyRecord); // Save all state: glPushAttrib(GL_ALL_ATTRIB_BITS); // Disable alpha-blending: glDisable(GL_BLEND); // Reset color write mask to "all enabled" glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_TRUE); // Disable any shaders: PsychSetShader(proxyRecord, 0); // Transform sourceRecord source texture into a normalized, upright texture if it isn't already in // that format. We require this standard orientation for simplified shader design. if (!(specialFlags & 1)) PsychNormalizeTextureOrientation(sourceRecord); // Test if optional 2nd source texture is provided: testarg=0; PsychCopyInIntegerArg(3, FALSE, &testarg); if (testarg!=0) { // Tes. Get the window structure for the 2nd source texture. PsychAllocInWindowRecordArg(3, TRUE, &sourceRecord2); if (!PsychIsTexture(sourceRecord2)) PsychErrorExitMsg(PsychError_user, "'sourceTexture2' argument must be a handle to a texture or offscreen window."); // Transform sourceRecord2 source texture into a normalized, upright texture if it isn't already in // that format. We require this standard orientation for simplified shader design. if (!(specialFlags & 1)) PsychNormalizeTextureOrientation(sourceRecord2); } else { // No secondary source texture: sourceRecord2 = NULL; } // Restore proper rendering context: PsychSetGLContext(proxyRecord); // Test if optional target texture is provided: testarg=0; PsychCopyInIntegerArg(4, FALSE, &testarg); // Do we need to create a new one from scratch? if (testarg==0) { // No valid textureHandle provided. Create a new empty textureRecord which clones some // of the properties of the sourceRecord targetRecord = NULL; PsychCreateWindowRecord(&targetRecord); PsychInitWindowRecordTextureFields(targetRecord); targetRecord->windowType=kPsychTexture; targetRecord->screenNumber = sourceRecord->screenNumber; // Assign parent window and copy its inheritable properties: PsychAssignParentWindow(targetRecord, sourceRecord); targetRecord->depth = sourceRecord->depth; // Assume this texture has four channels. FIXME: Is this problematic? targetRecord->nrchannels = 4; PsychCopyRect(targetRecord->rect, sourceRecord->rect); targetRecord->texturetarget = sourceRecord->texturetarget; // Orientation is set to 2 - like an upright Offscreen window texture: targetRecord->textureOrientation = 2; // Mark it valid and return handle to userspace: PsychSetWindowRecordValid(targetRecord); } else { // Get the window structure for the target texture. PsychAllocInWindowRecordArg(4, TRUE, &targetRecord); if (!PsychIsTexture(targetRecord)) PsychErrorExitMsg(PsychError_user, "'targetTexture' argument must be a handle to a texture or offscreen window."); } // Make sure our source textures have at least a pseudo FBO for read-access: PsychCreateShadowFBOForTexture(sourceRecord, FALSE, -1); if (sourceRecord2) PsychCreateShadowFBOForTexture(sourceRecord2, FALSE, -1); // Make sure our target texture has a full-blown FBO attached as a rendertarget. // As our proxy object defines the image processing ops, it also defines the // required imagingMode properties for the target texture: PsychCreateShadowFBOForTexture(targetRecord, TRUE, proxyRecord->imagingMode); // Assign GLSL filter-/lookup-shaders if needed: usefloatformat is queried. // The 'userRequest' flag is set depending on specialFlags setting & 2. glBindTexture(targetRecord->texturetarget, targetRecord->textureNumber); glGetTexLevelParameteriv(targetRecord->texturetarget, 0, GL_TEXTURE_RED_SIZE, (GLint*) &d); if (d <= 0) glGetTexLevelParameteriv(targetRecord->texturetarget, 0, GL_TEXTURE_LUMINANCE_SIZE, (GLint*) &d); glBindTexture(targetRecord->texturetarget, 0); usefloatformat = 0; if (d == 16) usefloatformat = 1; if (d >= 32) usefloatformat = 2; PsychAssignHighPrecisionTextureShaders(targetRecord, sourceRecord, usefloatformat, (specialFlags & 2) ? 0 : 1); // Make sure our proxy has suitable bounce buffers if we need any: if (proxyRecord->imagingMode & (kPsychNeedDualPass | kPsychNeedMultiPass)) { // Needs multi-pass processing. Create bounce buffer if neccessary: PsychCopyRect(proxyRecord->rect, targetRecord->rect); PsychCreateShadowFBOForTexture(proxyRecord, TRUE, proxyRecord->imagingMode); } // Make sure we don't have VRAM memory feedback loops: if (sourceRecord->textureNumber == targetRecord->textureNumber) { PsychErrorExitMsg(PsychError_user, "Source texture and target texture must be different!"); } // Apply image processing operation: Use ressources and OpenGL context of proxyRecord, run user defined blit chain, // Don't supply user specific data (NULL), don't supply override blitter (NULL), source is read-only (TRUE), no // swizzle allowed (FALSE), sourceRecord is source, targetRecord is destination, bounce buffers provided by proxyRecord, // no secondary FBO available (NULL). PsychPipelineExecuteHook(proxyRecord, kPsychUserDefinedBlit, NULL, NULL, TRUE, FALSE, &(sourceRecord->fboTable[sourceRecord->drawBufferFBO[0]]), (sourceRecord2) ? &(sourceRecord2->fboTable[sourceRecord2->drawBufferFBO[0]]) : NULL, &(targetRecord->fboTable[targetRecord->drawBufferFBO[0]]), (proxyRecord->drawBufferFBO[0]!=-1) ? &(proxyRecord->fboTable[proxyRecord->drawBufferFBO[0]]) : NULL); // Restore previous settings: glPopAttrib(); //Return the window index and the rect argument. PsychCopyOutDoubleArg(1, FALSE, targetRecord->windowIndex); // Done. return(PsychError_none); }
void device_enable_color(device_t device, bool red, bool green, bool blue, bool alpha) { glColorMask(red, green, blue, alpha); }
//---------- // 表示関数 //---------- void display( void ) { glClear( GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT ); glDisable( GL_CULL_FACE ); glDisable( GL_ALPHA_TEST ); glDisable( GL_BLEND ); g_clARTK.display(); glEnable( GL_CULL_FACE ); glEnable( GL_ALPHA_TEST ); glEnable( GL_BLEND ); if( g_clARTK.isMarkerFound() ) { double dMat[16]; glMatrixMode( GL_PROJECTION ); g_clARTK.getProjectionMat( dMat ); glLoadMatrixd( dMat ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); glPushMatrix(); g_clARTK.getModelViewMat( dMat ); glLoadMatrixd( dMat ); glScalef( 1.0f, 1.0f, -1.0f ); // 左手系 → 右手系 g_clPMDModel.render(); // ステンシルバッファに影の形を描画 glDisable( GL_CULL_FACE ); glDisable( GL_TEXTURE_2D ); glDisable( GL_LIGHTING ); glEnable( GL_STENCIL_TEST ); glStencilFunc( GL_ALWAYS, 1, ~0 ); glStencilOp( GL_REPLACE, GL_KEEP, GL_REPLACE ); glColorMask( 0, 0, 0, 0 ); glDepthMask( 0 ); glMultMatrixf( (const float *)g_matPlanarProjection ); g_clPMDModel.renderForShadow(); // 影用の描画 glColorMask( 1, 1, 1, 1 ); // ステンシルバッファの影の形を塗りつぶす float fWndW = glutGet( GLUT_WINDOW_WIDTH ), fWndH = glutGet( GLUT_WINDOW_HEIGHT ); glStencilFunc( GL_EQUAL, 1, ~0); glStencilOp( GL_KEEP, GL_KEEP ,GL_KEEP ); glDisable( GL_DEPTH_TEST ); glMatrixMode( GL_PROJECTION ); glPushMatrix(); glLoadIdentity(); gluOrtho2D( 0.0f, fWndW, 0.0f, fWndH ); glMatrixMode( GL_MODELVIEW ); glPushMatrix(); glLoadIdentity(); glColor4f( 0.2f, 0.2f, 0.2f, 0.5f ); glBegin( GL_TRIANGLE_FAN ); glVertex2f( 0.0f, fWndH ); glVertex2f( fWndW, fWndH ); glVertex2f( fWndW, 0.0f ); glVertex2f( 0.0f, 0.0f ); glEnd(); glMatrixMode( GL_PROJECTION ); glPopMatrix(); glMatrixMode( GL_MODELVIEW ); glPopMatrix(); glDepthMask( 1 ); glEnable( GL_LIGHTING ); glEnable( GL_DEPTH_TEST ); glDisable( GL_STENCIL_TEST ); glPopMatrix(); } calcFps(); glutSwapBuffers(); }
//---------------------------------------------------------- void ofGLRenderer::clearAlpha() { glColorMask(0, 0, 0, 1); glClearColor(0, 0, 0, 1); glClear(GL_COLOR_BUFFER_BIT); glColorMask(1, 1, 1, 1); }
void RenderScene() { g_globalCam.Update(); // Clear Depth and color buffers // glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Enabled texturing and depth testing // glEnable(GL_TEXTURE_2D); // Enable Texturing glEnable(GL_DEPTH_TEST); // Enable Depth tests glDepthFunc(GL_LEQUAL); // LESSEQUAL depth test glEnable( GL_CULL_FACE ); glCullFace( GL_BACK ); glFrontFace( GL_CCW ); // Do a depth only pass // int rtColor = (g_bMSAA) ? g_msaaColor : DEFAULT_HANDLE; int rtDepth = (g_bMSAA) ? g_msaaDepth : DEFAULT_HANDLE; g_pTexInterface->BindRenderTarget(&rtColor, 1, rtDepth); glColorMask(0, 0, 0, 0); if(g_bMSAA) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); RenderGeometry( ); int def = DEFAULT_HANDLE; glColorMask(1, 1, 1, 1); // Render the gbuffer to non-msaa targets // RenderSceneGBuffer(); RenderLightBuffer(); rtColor = (g_bMSAA) ? g_msaaColor : DEFAULT_HANDLE; rtDepth = (g_bMSAA) ? g_msaaDepth : DEFAULT_HANDLE; g_pTexInterface->BindRenderTarget(&rtColor, 1, rtDepth); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); rtColor = (g_bMSAA) ? g_normalDepthColor : g_lightBuffer; vec2 viewDims = {(float)GetScreenWidth(), (float)GetScreenHeight()}; g_pShaderInterface->BindShader( g_compositeShader ); g_pShaderInterface->SetFloat( "g_viewDims", viewDims, 2 ); g_pShaderInterface->SetStateMatrix( "g_matWorldViewProj", MATRIX_MODELVIEW | MATRIX_PROJECTION ); g_pShaderInterface->SetTexture( "g_lightBuffer", rtColor ); g_pShaderInterface->SetTexture("g_diffuseTexture", g_groundTexture); int textured = 1; g_pShaderInterface->SetInt( "g_bIsTextured", &textured, 0 ); glDepthFunc(GL_LEQUAL); RenderGeometry(); g_pShaderInterface->UnbindShader(); if(g_bMSAA) { g_pTexInterface->BindTexture(g_lightBuffer); RenderTexturedFullscreenQuad(); // Rebind default backbuffer // g_pTexInterface->ResolveMSAATarget(g_resolveTexture); g_pTexInterface->BindRenderTarget(&def, 1, DEFAULT_HANDLE); glDisable(GL_DEPTH_TEST); g_pTexInterface->BindTexture(g_resolveTexture); // resolve tex RenderTexturedFullscreenQuad(); } g_pTexInterface->EvictTextures(); #ifdef RENDER_DEBUG glDepthFunc(GL_ALWAYS); renderDebug(); glDepthFunc(GL_LEQUAL); #endif glFlush(); }
//-------------------------------------------------------------- void testApp::draw(){ // if (QuadBufferCapable) glDrawBuffer(GL_BACK_LEFT); // else glDrawBuffer(GL_BACK); // glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); ofBackground(0); int _x = 0; int _y = 0; int _width = outputX; int _height = outputY; switch (outputMode) { case ELM_MONO: fboLeft.draw(_x,_y,_width,_height); ofPushStyle(); fboGui.draw(_x,_y,_width,_height); ofPopStyle(); break; case ELM_STEREO_ANAGLYPH: ofPushStyle(); glColorMask(true, false, false, true); if (swapLeftRight) fboRight.draw(_x,_y,_width,_height); else fboLeft.draw(_x,_y,_width,_height); glColorMask(false, true, true, true); if (swapLeftRight) fboLeft.draw(_x,_y,_width,_height); else fboRight.draw(_x,_y,_width,_height); glColorMask(true, true, true, true); ofPopStyle(); ofPushStyle(); fboGui.draw(_x,_y,_width,_height); ofPopStyle(); break; case ELM_STEREO_OPENGL: glDrawBuffer(GL_BACK_LEFT); if (swapLeftRight) fboRight.draw(_x,_y,_width,_height); else fboLeft.draw(_x,_y,_width,_height); fboGui.draw(_x,_y,_width,_height); glDrawBuffer(GL_BACK_RIGHT); if (swapLeftRight) fboLeft.draw(_x,_y,_width,_height); else fboRight.draw(_x,_y,_width,_height); fboGui.draw(_x,_y,_width,_height); break; case ELM_STEREO_LEFTRIGHT: ofPushStyle(); if (swapLeftRight) { fboRight.draw(_x,_y,_width*.5,_height); fboLeft.draw(_x+_width*.5,_y,_width*.5,_height); } else { fboLeft.draw(_x,_y,_width*.5,_height); fboRight.draw(_x+_width*.5,_y,_width*.5,_height); } ofPopStyle(); ofPushStyle(); fboGui.draw(_x,_y,_width*.5,_height); ofPopStyle(); break; case ELM_STEREO_TOPBOTTOM: ofPushStyle(); if (swapLeftRight) { fboRight.draw(_x,_y,_width,_height*.5); fboLeft.draw(_x,_y+_height*.5,_width,_height*.5); } else { fboLeft.draw(_x,_y,_width,_height*.5); fboRight.draw(_x,_y+_height*.5,_width,_height*.5); } ofPopStyle(); ofPushStyle(); fboGui.draw(_x,_y,_width,_height*.5); ofPopStyle(); break; default: break; } //da togliere in modalitˆ proeizione // logo.draw(20, 20, 45, 45); }
void RenderGL(void) { //======================================================_SHADOWS_BEGIN_=========================================================================== //======================================================_SHADOWS_BEGIN_=========================================================================== //======================================================_SHADOWS_BEGIN_=========================================================================== //======================================================_SHADOWS_BEGIN_=========================================================================== //============================================================================================================================= glBindFramebuffer(GL_FRAMEBUFFER, fboId_2D);//-----------------------F.B.O. //---------------------------------------------------------------- //glColor4f(color is changed using fragment program) glClearColor(1.0, 1.0, 1.0, 0.0); glClear (GL_COLOR_BUFFER_BIT); glViewport(0, 0, TEXTURE_WIDTH, TEXTURE_HEIGHT); //---------------------------------------------------------------- glDisable(GL_BLEND); glDisable(GL_DEPTH_TEST); PerspectiveMatrix(ProjectionShadow, 45, 1.0, 0.001, 1000.0); Rotate(ProjectionShadow, 0.0, 1.0, 0.0, 20.0); Rotate(ProjectionShadow, 1.0, 0.0, 0.0, 45.0); glUseProgram(SHADER_shadow);//---------<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< //############################################################################################################################################################|__SHADOW_01 //============================================================================================================================================================|__LAYER__01 glColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_TRUE); //===================================================== darkness_shadow[0] = 0.5; darkness_shadow[1] = 0.5; darkness_shadow[2] = 0.5; //#include "_MODEL_FOLDERS_/flowerShield/flowerShield_Shadow_01.cpp" //==================================================================================== //#include "_MODEL_FOLDERS_/flowerShield/flowerShield_Shadow_00.cpp" //============================================================================================================================================================|__LAYER__02 glColorMask(GL_FALSE, GL_TRUE, GL_FALSE, GL_TRUE); //=========================================================== //--------------------------------------------------------- //############################################################################################################################################################|__SHADOW_02 //============================================================================================================================================================|__LAYER__01 glColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_TRUE); //=========================================================== darkness_shadow[0] = 0.3; darkness_shadow[1] = 0.3; darkness_shadow[2] = 0.3; //============================================================================================================================================================|__LAYER__02 glColorMask(GL_FALSE, GL_TRUE, GL_FALSE, GL_TRUE); //=========================================================== //------------------------------------------------------------------------------------------------------------------------------------------------------------------- LoadIdentity(textureMatrix); AssignMatrix(textureMatrix, ProjectionShadow); //=========================================================== glEnable(GL_DEPTH_TEST); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glBindFramebuffer(GL_FRAMEBUFFER, 0); //======================================================_SHADOWS_END_============================================================================= //======================================================_SHADOWS_END_============================================================================= //======================================================_SHADOWS_END_============================================================================= //======================================================_SHADOWS_END_============================================================================= //################################################################################################################################################################################################## //################################################################################################################################################################################################## //################################################################################################################################################################################################## //################################################################################################################################################################################################## //======================================================================================================================================================== //---------------------------------------------------RETURN_TO_MAIN_FRAMEBUFFER____________________!!!!!!!!!!!!!!!!!!!!!!!!!!!! //---------------------------------------------------RETURN_TO_MAIN_FRAMEBUFFER____________________!!!!!!!!!!!!!!!!!!!!!!!!!!!! //======================================================================================================================================================== #ifdef __APPLE__ glBindFramebuffer(GL_FRAMEBUFFER, msaaFramebuffer); #endif //======================================================================================================================================================== //---------------------------------------------------RETURN_TO_MAIN_FRAMEBUFFER____________________!!!!!!!!!!!!!!!!!!!!!!!!!!!! //---------------------------------------------------RETURN_TO_MAIN_FRAMEBUFFER____________________!!!!!!!!!!!!!!!!!!!!!!!!!!!! //======================================================================================================================================================== //========================================================================================================================================================= glClearColor( 0.0f, 0.0f, 0.0f, 0.5f ); glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //---------------------------------------------------------------------------------- glViewport(0, 0, viewWidth, viewHeight); PerspectiveMatrix(projection, 45,(float)viewWidth / (float)viewHeight, 0.1, 10000); //========================================================================================================================================================= #ifdef __APPLE__ Rotate(projection, 0.0, 0.0, 1.0, -90.0);//_____FOR_iOS_LANDSCAPE_VIEW projection[12] = eyePosition[1]; projection[13] = eyePosition[0]; projection[15] = eyePosition[2]; #endif //========================================================================================================================================================= #ifdef WIN32 projection[12] = eyePosition[0]; projection[13] = eyePosition[1]; projection[15] = eyePosition[2]; #endif //========================================================================================================================================================= Rotate(projection, 1.0, 0.0, 0.0, look_UP_DOWN); Rotate(projection, 0.0, 1.0, 0.0, -look_LEFT_RIGHT); //################################################################################################################################################################# //==================================================================================== #include "_MODEL_FOLDERS_/horseParts/torso/torso_Render.cpp" //==================================================================================== #include "_MODEL_FOLDERS_/horseParts/tail/tail_Render.cpp" //==================================================================================== #include "_MODEL_FOLDERS_/horseParts/neck/neck_Render.cpp" //==================================================================================== #include "_MODEL_FOLDERS_/horseParts/head/head_Render.cpp" //==================================================================================== #include "_MODEL_FOLDERS_/horseParts/frontRightUpperLeg/frontRightUpperLeg_Render.cpp" //===================================================== #include "_MODEL_FOLDERS_/horseParts/frontRightLowerLeg/frontRightLowerLeg_Render.cpp" //===================================================== #include "_MODEL_FOLDERS_/horseParts/frontRightFoot/frontRightFoot_Render.cpp" //==================================================================================== #include "_MODEL_FOLDERS_/horseParts/backRightUpperLeg/backRightUpperLeg_Render.cpp" //===================================================== #include "_MODEL_FOLDERS_/horseParts/backRightLowerLeg/backRightLowerLeg_Render.cpp" //===================================================== #include "_MODEL_FOLDERS_/horseParts/backRightFoot/backRightFoot_Render.cpp" //==================================================================================== #include "_MODEL_FOLDERS_/horseParts/frontLeftUpperLeg/frontLeftUpperLeg_Render.cpp" //===================================================== #include "_MODEL_FOLDERS_/horseParts/frontLeftLowerLeg/frontLeftLowerLeg_Render.cpp" //===================================================== #include "_MODEL_FOLDERS_/horseParts/frontLeftFoot/frontLeftFoot_Render.cpp" //==================================================================================== #include "_MODEL_FOLDERS_/horseParts/backLeftUpperLeg/backLeftUpperLeg_Render.cpp" //===================================================== #include "_MODEL_FOLDERS_/horseParts/backLeftLowerLeg/backLeftLowerLeg_Render.cpp" //===================================================== #include "_MODEL_FOLDERS_/horseParts/backLeftFoot/backLeftFoot_Render.cpp" //==================================================================================== #ifdef WIN32 SwapBuffers( hDC ); #endif }
void DisplayDeviceOpenGL::render(const Renderable* r) const { if(!r->isEnabled()) { // Renderable item not enabled then early return. return; } StencilScopePtr stencil_scope; if(r->hasClipSettings()) { ModelManager2D mm(static_cast<int>(r->getPosition().x), static_cast<int>(r->getPosition().y)); auto clip_shape = r->getStencilMask(); bool cam_set = false; if(clip_shape->getCamera() == nullptr && r->getCamera() != nullptr) { cam_set = true; clip_shape->setCamera(r->getCamera()); } stencil_scope.reset(new StencilScopeOGL(r->getStencilSettings())); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); glDepthMask(GL_FALSE); glClear(GL_STENCIL_BUFFER_BIT); render(clip_shape.get()); stencil_scope->applyNewSettings(keep_stencil_settings); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glDepthMask(GL_TRUE); if(cam_set) { clip_shape->setCamera(nullptr); } } auto shader = r->getShader(); shader->makeActive(); BlendEquationScopeOGL be_scope(*r); BlendModeScopeOGL bm_scope(*r); // apply lighting/depth check/depth write here. bool use_lighting = r->isLightingStateSet() ? r->useLighting() : false; // Set the depth enable. if(r->isDepthEnableStateSet()) { if(get_current_depth_enable() != r->isDepthEnabled()) { if(r->isDepthEnabled()) { glEnable(GL_DEPTH_TEST); } else { glDisable(GL_DEPTH_TEST); } get_current_depth_enable() = r->isDepthEnabled(); } } else { // We assume that depth is disabled if not specified. if(get_current_depth_enable() == true) { glDisable(GL_DEPTH_TEST); get_current_depth_enable() = false; } } glm::mat4 pmat(1.0f); glm::mat4 vmat(1.0f); if(r->getCamera()) { // set camera here. pmat = r->getCamera()->getProjectionMat(); vmat = r->getCamera()->getViewMat(); } else if(get_default_camera() != nullptr) { pmat = get_default_camera()->getProjectionMat(); vmat = get_default_camera()->getViewMat(); } if(use_lighting) { for(auto lp : r->getLights()) { /// xxx need to set lights here. } } if(r->getRenderTarget()) { r->getRenderTarget()->apply(); } if(shader->getPUniform() != ShaderProgram::INVALID_UNIFORM) { shader->setUniformValue(shader->getPUniform(), glm::value_ptr(pmat)); } if(shader->getMvUniform() != ShaderProgram::INVALID_UNIFORM) { glm::mat4 mvmat = vmat; if(is_global_model_matrix_valid() && !r->ignoreGlobalModelMatrix()) { mvmat *= get_global_model_matrix() * r->getModelMatrix(); } else { mvmat *= r->getModelMatrix(); } shader->setUniformValue(shader->getMvUniform(), glm::value_ptr(mvmat)); } if(shader->getMvpUniform() != ShaderProgram::INVALID_UNIFORM) { glm::mat4 pvmat(1.0f); if(is_global_model_matrix_valid() && !r->ignoreGlobalModelMatrix()) { pvmat = pmat * vmat * get_global_model_matrix() * r->getModelMatrix(); } else { pvmat = pmat * vmat * r->getModelMatrix(); } shader->setUniformValue(shader->getMvpUniform(), glm::value_ptr(pvmat)); } if(shader->getColorUniform() != ShaderProgram::INVALID_UNIFORM) { if(r->isColorSet()) { shader->setUniformValue(shader->getColorUniform(), r->getColor().asFloatVector()); } else { shader->setUniformValue(shader->getColorUniform(), ColorScope::getCurrentColor().asFloatVector()); } } shader->setUniformsForTexture(r->getTexture()); // XXX we should make this either or with setting the mvp/color uniforms above. auto uniform_draw_fn = shader->getUniformDrawFunction(); if(uniform_draw_fn) { uniform_draw_fn(shader); } // Loop through uniform render variables and set them. /*for(auto& urv : r->UniformRenderVariables()) { for(auto& rvd : urv->VariableDescritionList()) { auto rvdd = std::dynamic_pointer_cast<RenderVariableDeviceData>(rvd->GetDisplayData()); ASSERT_LOG(rvdd != nullptr, "Unable to cast DeviceData to RenderVariableDeviceData."); shader->SetUniformValue(rvdd->GetActiveMapIterator(), urv->Value()); } }*/ // Need to figure the interaction with shaders. /// XXX Need to create a mapping between attributes and the index value below. for(auto as : r->getAttributeSet()) { if(!as->isEnabled()) { continue; } //ASSERT_LOG(as->getCount() > 0, "No (or negative) number of vertices in attribute set. " << as->getCount()); if((!as->isMultiDrawEnabled() && as->getCount() <= 0) || (as->isMultiDrawEnabled() && as->getMultiDrawCount() <= 0)) { //LOG_WARN("No (or negative) number of vertices in attribute set. " << as->getCount()); continue; } GLenum draw_mode = convert_drawing_mode(as->getDrawMode()); // apply blend, if any, from attribute set. BlendEquationScopeOGL be_scope(*as); BlendModeScopeOGL bm_scope(*as); if(shader->getColorUniform() != ShaderProgram::INVALID_UNIFORM && as->isColorSet()) { shader->setUniformValue(shader->getColorUniform(), as->getColor().asFloatVector()); } for(auto& attr : as->getAttributes()) { if(attr->isEnabled()) { shader->applyAttribute(attr); } } if(as->isInstanced()) { if(as->isIndexed()) { as->bindIndex(); // XXX as->GetIndexArray() should be as->GetIndexArray()+as->GetOffset() glDrawElementsInstanced(draw_mode, static_cast<GLsizei>(as->getCount()), convert_index_type(as->getIndexType()), as->getIndexArray(), as->getInstanceCount()); as->unbindIndex(); } else { glDrawArraysInstanced(draw_mode, static_cast<GLint>(as->getOffset()), static_cast<GLsizei>(as->getCount()), as->getInstanceCount()); } } else { if(as->isIndexed()) { as->bindIndex(); // XXX as->GetIndexArray() should be as->GetIndexArray()+as->GetOffset() glDrawElements(draw_mode, static_cast<GLsizei>(as->getCount()), convert_index_type(as->getIndexType()), as->getIndexArray()); as->unbindIndex(); } else { if(as->isMultiDrawEnabled()) { glMultiDrawArrays(draw_mode, as->getMultiOffsetArray().data(), as->getMultiCountArray().data(), as->getMultiDrawCount()); } else { glDrawArrays(draw_mode, static_cast<GLint>(as->getOffset()), static_cast<GLsizei>(as->getCount())); } } } shader->cleanUpAfterDraw(); glBindBuffer(GL_ARRAY_BUFFER, 0); } if(r->getRenderTarget()) { r->getRenderTarget()->unapply(); } }
void nuiGLPainter::SetState(const nuiRenderState& rState, bool ForceApply) { //TEST_FBO_CREATION(); NUI_RETURN_IF_RENDERING_DISABLED; nuiCheckForGLErrors(); // blending if (ForceApply || mState.mBlending != rState.mBlending) { mState.mBlending = rState.mBlending; if (mState.mBlending) { glEnable(GL_BLEND); } else { glDisable(GL_BLEND); } } if (ForceApply || mState.mBlendFunc != rState.mBlendFunc) { mState.mBlendFunc = rState.mBlendFunc; GLenum src, dst; nuiGetBlendFuncFactors(rState.mBlendFunc, src, dst); BlendFuncSeparate(src, dst); nuiCheckForGLErrors(); } if (ForceApply || mState.mDepthTest != rState.mDepthTest) { mState.mDepthTest = rState.mDepthTest; if (mState.mDepthTest) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST); } if (ForceApply || mState.mDepthWrite != rState.mDepthWrite) { mState.mDepthWrite = rState.mDepthWrite; glDepthMask(mState.mDepthWrite); } // We don't care about the font in the lower layer of rendering //nuiFont* mpFont; // ApplyTexture(rState, ForceApply); // Rendering buffers: if (ForceApply || mState.mColorBuffer != rState.mColorBuffer) { mState.mColorBuffer = rState.mColorBuffer; GLboolean m = mState.mColorBuffer ? GL_TRUE : GL_FALSE; glColorMask(m, m, m, m); nuiCheckForGLErrors(); } if (mClip.mEnabled || ForceApply) { uint32 width = mWidth; uint32 height = mHeight; if (mpSurface) { width = mpSurface->GetWidth(); height = mpSurface->GetHeight(); } nuiRect clip(mClip); int x,y,w,h; uint angle = (mpSurface && mpSurface->GetRenderToTexture()) ? 0 : mAngle; if (angle == 90) { x = ToBelow(clip.Top()); y = ToBelow(clip.Left()); w = ToBelow(clip.GetHeight()); h = ToBelow(clip.GetWidth()); } else if (angle == 180) { w = ToBelow(clip.GetWidth()); h = ToBelow(clip.GetHeight()); x = ToBelow(width - w - clip.Left()); y = ToBelow(clip.Top()); } else if (angle == 270) { w = ToBelow(clip.GetHeight()); h = ToBelow(clip.GetWidth()); x = ToBelow(height - clip.Top() - w); y = ToBelow(width - clip.Left() - h); } else { NGL_ASSERT(!angle); x = ToBelow(clip.Left()); y = ToBelow(height - clip.Bottom()); w = ToBelow(clip.GetWidth()); h = ToBelow(clip.GetHeight()); } //NGL_OUT(_T("To Screen Clip {%d, %d, %d, %d}\n"), x,y,w,h); if (!mScissorOn || ForceApply) { glEnable(GL_SCISSOR_TEST); mScissorOn = true; } if (mScissorX != x || mScissorY != y || mScissorW != w || mScissorH != h || ForceApply) { mScissorX = x; mScissorY = y; mScissorW = w; mScissorH = h; x *= NUI_SCALE_FACTOR; y *= NUI_SCALE_FACTOR; w *= NUI_SCALE_FACTOR; h *= NUI_SCALE_FACTOR; glScissor(x, y, w, h); } nuiCheckForGLErrors(); } else { if (mScissorOn || ForceApply) { glDisable(GL_SCISSOR_TEST); mScissorOn = false; } } mState.mClearColor = rState.mClearColor; mState.mStrokeColor = rState.mStrokeColor; mState.mFillColor = rState.mFillColor; nuiCheckForGLErrors(); }
/* * OpenGL (GLUT) calls this routine to display the scene */ void display() { // Wait for first reshape if (H==0) return; // Set initial pattern if (N==0) { // Clear screen and set color glClearColor(0,0,0,0); glClear(GL_COLOR_BUFFER_BIT); glColor4f(1,0,0,1); // Draw pattern from file LoadPattern(file); } // // Compute next generation // else { // Set shader glUseProgram(shader); // Set offsets int id = glGetUniformLocation(shader,"dX"); if (id>=0) glUniform1f(id,dX); id = glGetUniformLocation(shader,"dY"); if (id>=0) glUniform1f(id,dY); id = glGetUniformLocation(shader,"img"); if (id>=0) glUniform1i(id,0); // Copy original scene to texture glBindTexture(GL_TEXTURE_2D,img); glCopyTexImage2D(GL_TEXTURE_2D,0,GL_RGBA8,0,0,W,H,0); // Redraw the texture glClear(GL_COLOR_BUFFER_BIT); glEnable(GL_TEXTURE_2D); glBegin(GL_QUADS); glTexCoord2f(0,0); glVertex2f(-1,-1); glTexCoord2f(0,1); glVertex2f(-1,+1); glTexCoord2f(1,1); glVertex2f(+1,+1); glTexCoord2f(1,0); glVertex2f(+1,-1); glEnd(); glDisable(GL_TEXTURE_2D); // Shader off glUseProgram(0); } // Lock alpha since to not interfere with game glColorMask(1,1,1,0); // Display parameters glColor4f(1,1,0,0); glWindowPos2i(5,5); if (warn) Print("Pattern too large for screen "); if (move) Print("FPS=%d ",FramesPerSecond()); Print("Generation=%d",N); glColorMask(1,1,1,1); // Render the scene and make it visible ErrCheck("display"); glFlush(); glutSwapBuffers(); // Increment generations N++; }
static __inline__ void draw_map(window_info *win,float zoom_multip, float px, float py) { float sx = 0.0f, sy = 0.0f; int i; float x, y; glPushMatrix(); sx = float_minimap_size/2; sy = float_minimap_size/2; glTranslatef(sx, sy, 0.0f); glClearStencil(0); glClear(GL_STENCIL_BUFFER_BIT); glEnable(GL_STENCIL_TEST); glStencilFunc(GL_ALWAYS, 1, 1); glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); glDepthMask(GL_FALSE); glColor3f(0.0f,0.0f,0.0f); glBegin(GL_POLYGON); for (i=0; i<=360; i +=10) { x = sin((i)*0.0174532925f)/2*float_minimap_size; y = cos((i)*0.0174532925f)/2*float_minimap_size; glVertex2f(x, y); } glEnd(); glStencilFunc(GL_EQUAL, 1, 1); glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); // re-enable the drawing in the current buffer glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glDepthMask(GL_TRUE); glEnable(GL_TEXTURE_2D); //draw the map #ifdef NEW_TEXTURES bind_texture(minimap_texture); #else /* NEW_TEXTURES */ bind_texture_id(minimap_texture); #endif /* NEW_TEXTURES */ glColor4f(1.0f,1.0f,1.0f,1.0f); rotate_at_player(zoom_multip,px,py); glBegin(GL_QUADS); #ifdef NEW_TEXTURES glTexCoord2f(0.0f, 1.0f); glVertex2f(-float_minimap_size/2, float_minimap_size/2); glTexCoord2f(1.0f, 1.0f); glVertex2f(float_minimap_size/2, float_minimap_size/2); glTexCoord2f(1.0f, 0.0f); glVertex2f(float_minimap_size/2, -float_minimap_size/2); glTexCoord2f(0.0f, 0.0f); glVertex2f(-float_minimap_size/2, -float_minimap_size/2); #else /* NEW_TEXTURES */ glTexCoord2f(0.0f, 0.0f); glVertex2f(-float_minimap_size/2, float_minimap_size/2); glTexCoord2f(1.0f, 0.0f); glVertex2f(float_minimap_size/2, float_minimap_size/2); glTexCoord2f(1.0f, 1.0f); glVertex2f(float_minimap_size/2, -float_minimap_size/2); glTexCoord2f(0.0f, 1.0f); glVertex2f(-float_minimap_size/2, -float_minimap_size/2); #endif /* NEW_TEXTURES */ glEnd(); glDisable(GL_STENCIL_TEST); glPopMatrix(); if (compass_tex) { //draw the compass texture draw_compass(); } }
void Blur_init(){ blur=Blur_basic; sw=larger_pow2(screen->w); sh=larger_pow2(screen->h); GLint mx; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mx); consoleLog("Blur_init: required texture size is %dx%d\n", sw, sh); if(sw>mx || sh>mx){ consoleLog("Blur_init: too big texture, disabling blur\n"); blur=Blur_none; return; } consoleLog("Blur_init: allocating screen buffer\n"); glGenTextures(1, &tex_screen); glBindTexture(GL_TEXTURE_2D, tex_screen); #if GL_EXT_framebuffer_object if(use_hdr){ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, sw,sh, 0, GL_RGB, GL_HALF_FLOAT_ARB, NULL); }else{ #endif glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, sw,sh, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); #if GL_EXT_framebuffer_object } #endif glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glClearColor(0.f, 0.f, 0.0f, 1.f); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE); glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, screen->w, screen->h); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); clearTexture(sw, sh); #if GL_ARB_shader_objects #if GL_ARB_depth_texture if(cap_glsl){ consoleLog("Blur_init: allocating depth buffer\n"); glGenTextures(1, &tex_depth); glBindTexture(GL_TEXTURE_2D, tex_depth); int comp; GLint i; glGetIntegerv(GL_DEPTH_BITS, &i); switch(i){ case 16: comp=GL_DEPTH_COMPONENT16_ARB; break; case 24: comp=GL_DEPTH_COMPONENT24_ARB; break; case 32: comp=GL_DEPTH_COMPONENT32_ARB; break; default: comp=GL_DEPTH_COMPONENT; break; } comp=GL_DEPTH_COMPONENT; if(use_hdr) comp=GL_DEPTH_COMPONENT24_ARB; glTexImage2D(GL_TEXTURE_2D, 0, comp, sw,sh, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); } #endif #endif #if GL_ARB_shader_objects if(cap_glsl){ prg_blurSimple=create_program("res/shaders/blur1.vs", "res/shaders/blur1.fs"); if(prg_blurSimple) consoleLog("Blur_init: compiled program \"blur1\"\n"); else consoleLog("Blur_init: couldn't compile program \"blur1\"\n"); #if GL_ARB_depth_texture prg_blurDepth=create_program("res/shaders/blur2.vs", "res/shaders/blur2.fs"); if(prg_blurDepth) consoleLog("Blur_init: compiled program \"blur2\"\n"); else consoleLog("Blur_init: couldn't compile program \"blur2\"\n"); #endif }else{ #endif consoleLog("Blur_init: no programs to compile\n"); #if GL_ARB_shader_objects } #endif #if GL_ARB_shader_objects if(cap_glsl){ blur=Blur_glsl_simple; #if GL_ARB_depth_texture blur=Blur_glsl_depth; #endif } #endif }
void Graphics::SetSpriteDrawingMode() { glDisable(GL_SCISSOR_TEST); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE); }
/// Draw the shadow for a shape static void pie_DrawShadow(iIMDShape *shape, int flag, int flag_data, Vector3f* light) { unsigned int i, j, n; Vector3f *pVertices; iIMDPoly *pPolys; static std::vector<EDGE> edgelist; // Static, to save allocations. static std::vector<EDGE> edgelistFlipped; // Static, to save allocations. static std::vector<EDGE> edgelistFiltered; // Static, to save allocations. EDGE *drawlist = NULL; unsigned edge_count; pVertices = shape->points; if( flag & pie_STATIC_SHADOW && shape->shadowEdgeList ) { drawlist = shape->shadowEdgeList; edge_count = shape->nShadowEdges; } else { edgelist.clear(); for (i = 0, pPolys = shape->polys; i < shape->npolys; ++i, ++pPolys) { Vector3f p[3]; for(j = 0; j < 3; j++) { int current = pPolys->pindex[j]; p[j] = Vector3f(pVertices[current].x, scale_y(pVertices[current].y, flag, flag_data), pVertices[current].z); } Vector3f normal = crossProduct(p[2] - p[0], p[1] - p[0]); if (normal * *light > 0) { for (n = 1; n < pPolys->npnts; n++) { // link to the previous vertex addToEdgeList(pPolys->pindex[n-1], pPolys->pindex[n], edgelist); } // back to the first addToEdgeList(pPolys->pindex[pPolys->npnts-1], pPolys->pindex[0], edgelist); } } // Remove duplicate pairs from the edge list. For example, in the list ((1 2), (2 6), (6 2), (3, 4)), remove (2 6) and (6 2). edgelistFlipped = edgelist; std::for_each(edgelistFlipped.begin(), edgelistFlipped.end(), flipEdge); std::sort(edgelist.begin(), edgelist.end(), edgeLessThan); std::sort(edgelistFlipped.begin(), edgelistFlipped.end(), edgeLessThan); edgelistFiltered.resize(edgelist.size()); edgelistFiltered.erase(std::set_difference(edgelist.begin(), edgelist.end(), edgelistFlipped.begin(), edgelistFlipped.end(), edgelistFiltered.begin(), edgeLessThan), edgelistFiltered.end()); drawlist = &edgelistFiltered[0]; edge_count = edgelistFiltered.size(); //debug(LOG_WARNING, "we have %i edges", edge_count); if(flag & pie_STATIC_SHADOW) { // then store it in the imd shape->nShadowEdges = edge_count; shape->shadowEdgeList = (EDGE *)realloc(shape->shadowEdgeList, sizeof(EDGE) * shape->nShadowEdges); std::copy(drawlist, drawlist + edge_count, shape->shadowEdgeList); } } // draw the shadow volume glBegin(GL_QUADS); glNormal3f(0.0, 1.0, 0.0); for(i=0;i<edge_count;i++) { int a = drawlist[i].from, b = drawlist[i].to; glVertex3f(pVertices[b].x, scale_y(pVertices[b].y, flag, flag_data), pVertices[b].z); glVertex3f(pVertices[b].x+light->x, scale_y(pVertices[b].y, flag, flag_data)+light->y, pVertices[b].z+light->z); glVertex3f(pVertices[a].x+light->x, scale_y(pVertices[a].y, flag, flag_data)+light->y, pVertices[a].z+light->z); glVertex3f(pVertices[a].x, scale_y(pVertices[a].y, flag, flag_data), pVertices[a].z); } glEnd(); #ifdef SHOW_SHADOW_EDGES glDisable(GL_DEPTH_TEST); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glColor4ub(0xFF, 0, 0, 0xFF); glBegin(GL_LINES); for(i = 0; i < edge_count; i++) { int a = drawlist[i].from, b = drawlist[i].to; if(a < 0) { continue; } glVertex3f(pVertices[b].x, scale_y(pVertices[b].y, flag, flag_data), pVertices[b].z); glVertex3f(pVertices[a].x, scale_y(pVertices[a].y, flag, flag_data), pVertices[a].z); } glEnd(); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); glEnable(GL_DEPTH_TEST); #endif }
void Graphics::SetSpriteMaskEnabledMode() { glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE); }
static void pie_DrawShadows(void) { const float width = pie_GetVideoBufferWidth(); const float height = pie_GetVideoBufferHeight(); GLenum op_depth_pass_front = GL_INCR, op_depth_pass_back = GL_DECR; pie_SetTexturePage(TEXPAGE_NONE); glPushMatrix(); pie_SetAlphaTest(false); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); glDepthFunc(GL_LESS); glDepthMask(GL_FALSE); glEnable(GL_STENCIL_TEST); // Check if we have the required extensions if (GLEW_EXT_stencil_wrap) { op_depth_pass_front = GL_INCR_WRAP_EXT; op_depth_pass_back = GL_DECR_WRAP_EXT; } // generic 1-pass version if (GLEW_EXT_stencil_two_side) { glEnable(GL_STENCIL_TEST_TWO_SIDE_EXT); glDisable(GL_CULL_FACE); glStencilMask(~0); glActiveStencilFaceEXT(GL_BACK); glStencilOp(GL_KEEP, GL_KEEP, op_depth_pass_back); glStencilFunc(GL_ALWAYS, 0, ~0); glActiveStencilFaceEXT(GL_FRONT); glStencilOp(GL_KEEP, GL_KEEP, op_depth_pass_front); glStencilFunc(GL_ALWAYS, 0, ~0); pie_ShadowDrawLoop(); glDisable(GL_STENCIL_TEST_TWO_SIDE_EXT); } // check for ATI-specific 1-pass version else if (GLEW_ATI_separate_stencil) { glDisable(GL_CULL_FACE); glStencilMask(~0); glStencilOpSeparateATI(GL_BACK, GL_KEEP, GL_KEEP, op_depth_pass_back); glStencilOpSeparateATI(GL_FRONT, GL_KEEP, GL_KEEP, op_depth_pass_front); glStencilFunc(GL_ALWAYS, 0, ~0); pie_ShadowDrawLoop(); } // fall back to default 2-pass version else { glStencilMask(~0); glStencilFunc(GL_ALWAYS, 0, ~0); glEnable(GL_CULL_FACE); // Setup stencil for front-facing polygons glCullFace(GL_BACK); glStencilOp(GL_KEEP, GL_KEEP, op_depth_pass_front); pie_ShadowDrawLoop(); // Setup stencil for back-facing polygons glCullFace(GL_FRONT); glStencilOp(GL_KEEP, GL_KEEP, op_depth_pass_back); pie_ShadowDrawLoop(); } pie_SetRendMode(REND_ALPHA); glEnable(GL_CULL_FACE); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); glStencilMask(~0); glStencilFunc(GL_LESS, 0, ~0); glColor4f(0, 0, 0, 0.5); pie_PerspectiveEnd(); glLoadIdentity(); glDisable(GL_DEPTH_TEST); glBegin(GL_TRIANGLE_STRIP); glVertex2f(0, 0); glVertex2f(width, 0); glVertex2f(0, height); glVertex2f(width, height); glEnd(); pie_PerspectiveBegin(); pie_SetRendMode(REND_OPAQUE); glDisable(GL_STENCIL_TEST); glEnable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); glPopMatrix(); scshapes.clear(); }
void VertexManager::vFlush(bool useDstAlpha) { GLVertexFormat* nativeVertexFmt = (GLVertexFormat*)VertexLoaderManager::GetCurrentVertexFormat(); u32 stride = nativeVertexFmt->GetVertexStride(); if (m_last_vao != nativeVertexFmt->VAO) { glBindVertexArray(nativeVertexFmt->VAO); m_last_vao = nativeVertexFmt->VAO; } PrepareDrawBuffers(stride); // Makes sure we can actually do Dual source blending bool dualSourcePossible = g_ActiveConfig.backend_info.bSupportsDualSourceBlend; // If host supports GL_ARB_blend_func_extended, we can do dst alpha in // the same pass as regular rendering. if (useDstAlpha && dualSourcePossible) { ProgramShaderCache::SetShader(DSTALPHA_DUAL_SOURCE_BLEND, m_current_primitive_type); } else { ProgramShaderCache::SetShader(DSTALPHA_NONE, m_current_primitive_type); } // upload global constants ProgramShaderCache::UploadConstants(); // setup the pointers nativeVertexFmt->SetupVertexPointers(); Draw(stride); // run through vertex groups again to set alpha if (useDstAlpha && !dualSourcePossible) { ProgramShaderCache::SetShader(DSTALPHA_ALPHA_PASS, m_current_primitive_type); // only update alpha glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_TRUE); glDisable(GL_BLEND); Draw(stride); // restore color mask g_renderer->SetColorMask(); if (bpmem.blendmode.blendenable || bpmem.blendmode.subtract) glEnable(GL_BLEND); } #if defined(_DEBUG) || defined(DEBUGFAST) if (g_ActiveConfig.iLog & CONF_SAVESHADERS) { // save the shaders ProgramShaderCache::PCacheEntry prog = ProgramShaderCache::GetShaderProgram(); std::string filename = StringFromFormat( "%sps%.3d.txt", File::GetUserPath(D_DUMPFRAMES_IDX).c_str(), g_ActiveConfig.iSaveTargetId); std::ofstream fps; OpenFStream(fps, filename, std::ios_base::out); fps << prog.shader.strpprog; filename = StringFromFormat("%svs%.3d.txt", File::GetUserPath(D_DUMPFRAMES_IDX).c_str(), g_ActiveConfig.iSaveTargetId); std::ofstream fvs; OpenFStream(fvs, filename, std::ios_base::out); fvs << prog.shader.strvprog; } if (g_ActiveConfig.iLog & CONF_SAVETARGETS) { std::string filename = StringFromFormat("%starg%.3d.png", File::GetUserPath(D_DUMPFRAMES_IDX).c_str(), g_ActiveConfig.iSaveTargetId); TargetRectangle tr; tr.left = 0; tr.right = Renderer::GetTargetWidth(); tr.top = 0; tr.bottom = Renderer::GetTargetHeight(); g_renderer->SaveScreenshot(filename, tr); } #endif g_Config.iSaveTargetId++; ClearEFBCache(); }
void IrrDriver::renderGLSL(float dt) { World *world = World::getWorld(); // Never NULL. // Overrides video::SOverrideMaterial &overridemat = m_video_driver->getOverrideMaterial(); overridemat.EnablePasses = scene::ESNRP_SOLID | scene::ESNRP_TRANSPARENT; overridemat.EnableFlags = 0; if (m_wireframe) { overridemat.Material.Wireframe = 1; overridemat.EnableFlags |= video::EMF_WIREFRAME; } if (m_mipviz) { overridemat.Material.MaterialType = m_shaders->getShader(ES_MIPVIZ); overridemat.EnableFlags |= video::EMF_MATERIAL_TYPE; overridemat.EnablePasses = scene::ESNRP_SOLID; } // Get a list of all glowing things. The driver's list contains the static ones, // here we add items, as they may disappear each frame. std::vector<GlowData> glows = m_glowing; std::vector<GlowNode *> transparent_glow_nodes; ItemManager * const items = ItemManager::get(); const u32 itemcount = items->getNumberOfItems(); u32 i; // For each static node, give it a glow representation const u32 staticglows = glows.size(); for (i = 0; i < staticglows; i++) { scene::ISceneNode * const node = glows[i].node; const float radius = (node->getBoundingBox().getExtent().getLength() / 2) * 2.0f; GlowNode * const repnode = new GlowNode(irr_driver->getSceneManager(), radius); repnode->setPosition(node->getTransformedBoundingBox().getCenter()); transparent_glow_nodes.push_back(repnode); } for (i = 0; i < itemcount; i++) { Item * const item = items->getItem(i); if (!item) continue; const Item::ItemType type = item->getType(); if (type != Item::ITEM_NITRO_BIG && type != Item::ITEM_NITRO_SMALL && type != Item::ITEM_BONUS_BOX && type != Item::ITEM_BANANA && type != Item::ITEM_BUBBLEGUM) continue; LODNode * const lod = (LODNode *) item->getSceneNode(); if (!lod->isVisible()) continue; const int level = lod->getLevel(); if (level < 0) continue; scene::ISceneNode * const node = lod->getAllNodes()[level]; node->updateAbsolutePosition(); GlowData dat; dat.node = node; dat.r = 1.0f; dat.g = 1.0f; dat.b = 1.0f; const video::SColorf &c = ItemManager::getGlowColor(type); dat.r = c.getRed(); dat.g = c.getGreen(); dat.b = c.getBlue(); glows.push_back(dat); // Push back its representation too const float radius = (node->getBoundingBox().getExtent().getLength() / 2) * 2.0f; GlowNode * const repnode = new GlowNode(irr_driver->getSceneManager(), radius); repnode->setPosition(node->getTransformedBoundingBox().getCenter()); transparent_glow_nodes.push_back(repnode); } // Start the RTT for post-processing. // We do this before beginScene() because we want to capture the glClear() // because of tracks that do not have skyboxes (generally add-on tracks) m_post_processing->begin(); m_video_driver->setRenderTarget(m_rtts->getRTT(RTT_COLOR), false, false); m_video_driver->beginScene(/*backBuffer clear*/ true, /*zBuffer*/ true, world->getClearColor()); // Clear normal and depth to zero m_video_driver->setRenderTarget(m_rtts->getRTT(RTT_NORMAL_AND_DEPTH), true, false, video::SColor(0,0,0,0)); irr_driver->getVideoDriver()->enableMaterial2D(); RaceGUIBase *rg = world->getRaceGUI(); if (rg) rg->update(dt); for(unsigned int cam = 0; cam < Camera::getNumCameras(); cam++) { Camera * const camera = Camera::getCamera(cam); scene::ICameraSceneNode * const camnode = camera->getCameraSceneNode(); #ifdef ENABLE_PROFILER std::ostringstream oss; oss << "drawAll() for kart " << cam << std::flush; PROFILER_PUSH_CPU_MARKER(oss.str().c_str(), (cam+1)*60, 0x00, 0x00); #endif camera->activate(); rg->preRenderCallback(camera); // adjusts start referee const u32 bgnodes = m_background.size(); /* if (bgnodes) { // If there are background nodes (3d skybox), draw them now. m_video_driver->setRenderTarget(m_rtts->getRTT(RTT_COLOR), false, false); m_renderpass = scene::ESNRP_SKY_BOX; m_scene_manager->drawAll(m_renderpass); const video::SOverrideMaterial prev = overridemat; overridemat.Enabled = 1; overridemat.EnableFlags = video::EMF_MATERIAL_TYPE; overridemat.Material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; for (i = 0; i < bgnodes; i++) { m_background[i]->setPosition(camnode->getPosition() * 0.97f); m_background[i]->updateAbsolutePosition(); m_background[i]->render(); } overridemat = prev; m_video_driver->setRenderTarget(m_rtts->getRTT(RTT_COLOR), false, true); }*/ // Fire up the MRT irr_driver->getVideoDriver()->setRenderTarget(irr_driver->getRTT(RTT_NORMAL_AND_DEPTH), false, false); PROFILER_PUSH_CPU_MARKER("- Solid Pass 1", 0xFF, 0x00, 0x00); m_renderpass = scene::ESNRP_CAMERA | scene::ESNRP_SOLID; glDepthFunc(GL_LEQUAL); glEnable(GL_DEPTH_TEST); glDisable(GL_ALPHA_TEST); glDepthMask(GL_TRUE); glDisable(GL_BLEND); glEnable(GL_CULL_FACE); irr_driver->setPhase(SOLID_NORMAL_AND_DEPTH_PASS); m_scene_manager->drawAll(m_renderpass); irr_driver->setProjMatrix(irr_driver->getVideoDriver()->getTransform(video::ETS_PROJECTION)); irr_driver->setViewMatrix(irr_driver->getVideoDriver()->getTransform(video::ETS_VIEW)); irr_driver->genProjViewMatrix(); PROFILER_POP_CPU_MARKER(); // Todo : reenable glow and shadows //ShadowImportanceProvider * const sicb = (ShadowImportanceProvider *) // irr_driver->getCallback(ES_SHADOW_IMPORTANCE); //sicb->updateIPVMatrix(); // Used to cull glowing items & lights const core::aabbox3df cambox = camnode->getViewFrustum()->getBoundingBox(); PROFILER_PUSH_CPU_MARKER("- Shadow", 0x30, 0x6F, 0x90); // Shadows if (!m_mipviz && !m_wireframe && UserConfigParams::m_shadows) //&& World::getWorld()->getTrack()->hasShadows()) { renderShadows(camnode, camera); } PROFILER_POP_CPU_MARKER(); PROFILER_PUSH_CPU_MARKER("- Light", 0x00, 0xFF, 0x00); // Lights renderLights(cambox, camnode, overridemat, cam, dt); PROFILER_POP_CPU_MARKER(); PROFILER_PUSH_CPU_MARKER("- Solid Pass 2", 0x00, 0x00, 0xFF); irr_driver->setPhase(SOLID_LIT_PASS); glEnable(GL_DEPTH_TEST); glDisable(GL_ALPHA_TEST); glDepthMask(GL_FALSE); glDisable(GL_BLEND); m_renderpass = scene::ESNRP_CAMERA | scene::ESNRP_SOLID; m_scene_manager->drawAll(m_renderpass); PROFILER_POP_CPU_MARKER(); if (World::getWorld()->getTrack()->isFogEnabled()) { PROFILER_PUSH_CPU_MARKER("- Fog", 0xFF, 0x00, 0x00); m_post_processing->renderFog(irr_driver->getInvProjMatrix()); PROFILER_POP_CPU_MARKER(); } PROFILER_PUSH_CPU_MARKER("- Glow", 0xFF, 0xFF, 0x00); // Render anything glowing. if (!m_mipviz && !m_wireframe) { irr_driver->setPhase(GLOW_PASS); renderGlow(overridemat, glows, cambox, cam); } // end glow PROFILER_POP_CPU_MARKER(); PROFILER_PUSH_CPU_MARKER("- Skybox", 0xFF, 0x00, 0xFF); renderSkybox(); PROFILER_POP_CPU_MARKER(); PROFILER_PUSH_CPU_MARKER("- Lensflare/godray", 0x00, 0xFF, 0xFF); // Is the lens flare enabled & visible? Check last frame's query. const bool hasflare = World::getWorld()->getTrack()->hasLensFlare(); const bool hasgodrays = World::getWorld()->getTrack()->hasGodRays(); if (true)//hasflare || hasgodrays) { irr::video::COpenGLDriver* gl_driver = (irr::video::COpenGLDriver*)m_device->getVideoDriver(); GLuint res = 0; if (m_query_issued) gl_driver->extGlGetQueryObjectuiv(m_lensflare_query, GL_QUERY_RESULT, &res); m_post_processing->setSunPixels(res); // Prepare the query for the next frame. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); gl_driver->extGlBeginQuery(GL_SAMPLES_PASSED_ARB, m_lensflare_query); m_scene_manager->setCurrentRendertime(scene::ESNRP_SOLID); m_scene_manager->drawAll(scene::ESNRP_CAMERA); irr_driver->setPhase(GLOW_PASS); m_sun_interposer->render(); gl_driver->extGlEndQuery(GL_SAMPLES_PASSED_ARB); m_query_issued = true; m_lensflare->setStrength(res / 4000.0f); if (hasflare) m_lensflare->OnRegisterSceneNode(); // Make sure the color mask is reset glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); } PROFILER_POP_CPU_MARKER(); // We need to re-render camera due to the per-cam-node hack. PROFILER_PUSH_CPU_MARKER("- Transparent Pass", 0xFF, 0x00, 0x00); irr_driver->setPhase(TRANSPARENT_PASS); m_renderpass = scene::ESNRP_CAMERA | scene::ESNRP_TRANSPARENT; glEnable(GL_DEPTH_TEST); glDisable(GL_ALPHA_TEST); glDepthMask(GL_FALSE); glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_CULL_FACE); m_scene_manager->drawAll(m_renderpass); PROFILER_POP_CPU_MARKER(); PROFILER_PUSH_CPU_MARKER("- Particles", 0xFF, 0xFF, 0x00); m_renderpass = scene::ESNRP_CAMERA | scene::ESNRP_TRANSPARENT_EFFECT; glDepthMask(GL_FALSE); glDisable(GL_CULL_FACE); glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); m_scene_manager->drawAll(m_renderpass); PROFILER_POP_CPU_MARKER(); PROFILER_PUSH_CPU_MARKER("- Displacement", 0x00, 0x00, 0xFF); // Handle displacing nodes, if any const u32 displacingcount = m_displacing.size(); if (displacingcount) { renderDisplacement(overridemat, cam); } PROFILER_POP_CPU_MARKER(); // Drawing for this cam done, cleanup const u32 glowrepcount = transparent_glow_nodes.size(); for (i = 0; i < glowrepcount; i++) { transparent_glow_nodes[i]->remove(); transparent_glow_nodes[i]->drop(); } PROFILER_POP_CPU_MARKER(); // Note that drawAll must be called before rendering // the bullet debug view, since otherwise the camera // is not set up properly. This is only used for // the bullet debug view. if (UserConfigParams::m_artist_debug_mode) World::getWorld()->getPhysics()->draw(); } // for i<world->getNumKarts() PROFILER_PUSH_CPU_MARKER("Postprocessing", 0xFF, 0xFF, 0x00); // Render the post-processed scene m_post_processing->render(); PROFILER_POP_CPU_MARKER(); // Set the viewport back to the full screen for race gui m_video_driver->setViewPort(core::recti(0, 0, UserConfigParams::m_width, UserConfigParams::m_height)); for(unsigned int i=0; i<Camera::getNumCameras(); i++) { Camera *camera = Camera::getCamera(i); char marker_name[100]; sprintf(marker_name, "renderPlayerView() for kart %d", i); PROFILER_PUSH_CPU_MARKER(marker_name, 0x00, 0x00, (i+1)*60); rg->renderPlayerView(camera, dt); PROFILER_POP_CPU_MARKER(); } // for i<getNumKarts PROFILER_PUSH_CPU_MARKER("GUIEngine", 0x75, 0x75, 0x75); // Either render the gui, or the global elements of the race gui. GUIEngine::render(dt); PROFILER_POP_CPU_MARKER(); // Render the profiler if(UserConfigParams::m_profiler_enabled) { PROFILER_DRAW(); } #ifdef DEBUG drawDebugMeshes(); #endif PROFILER_PUSH_CPU_MARKER("EndSccene", 0x45, 0x75, 0x45); m_video_driver->endScene(); PROFILER_POP_CPU_MARKER(); getPostProcessing()->update(dt); }
void MapView::plotGrid() { // Update viewer position according to mouse input: std::pair<TooN::Vector<6>, TooN::Vector<6> > pv6 = myGLWindow->GetMousePoseUpdate(); TooN::SE3<> se3CamFromMC; se3CamFromMC.get_translation() = mse3ViewerFromWorld * TooN::makeVector(0,0,0); mse3ViewerFromWorld = TooN::SE3<>::exp(pv6.first) * se3CamFromMC * TooN::SE3<>::exp(pv6.second).inverse() * se3CamFromMC.inverse() * mse3ViewerFromWorld; myGLWindow->SetupViewport(); glClearColor(0,0,0,0); glClearDepth(1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glEnable(GL_POINT_SMOOTH); //glEnable(GL_LINE_SMOOTH); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColorMask(1,1,1,1); glDisable(GL_DEPTH_TEST); // draw grid SetupFrustum(); SetupModelView(); glLineWidth(1*lineWidthFactor); double gridBigSpacing = 1; double gridSmallSpacing = 0.2; double gridBigMax = 30; double gridSmallMax = 5; // fine grid glBegin(GL_LINES); for(double x=-gridSmallMax; x<=gridSmallMax;x+=gridSmallSpacing) { if(x != 0 && (x-floor(x)) > 0.1) { glColor3f(0.2f,0.2f,0.2f); glVertex3d(x, -gridSmallMax, 0.0); glVertex3d(x, gridSmallMax, 0.0); } } for(double y=-gridSmallMax; y<=gridSmallMax;y+=gridSmallSpacing) { if(y != 0 && (y-floor(y)) > 0.1) { glColor3f(0.25f,0.25f,0.25f); glVertex3d(-gridSmallMax,y, 0.0); glVertex3d(gridSmallMax,y, 0.0); } } glEnd(); //big grid glLineWidth(2*lineWidthFactor); glBegin(GL_LINES); for(double x=-gridBigMax; x<=gridBigMax;x+=gridBigSpacing) { if(x != 0) { glColor3f(0.6f,0.6f,0.6f); glVertex3d(x, -gridBigMax, 0.0); glVertex3d(x, gridBigMax, 0.0); } } for(double y=-gridBigMax; y<=gridBigMax;y+=gridBigSpacing) { if(y != 0) { glColor3f(0.6f,0.6f,0.6f); glVertex3d(-gridBigMax,y, 0.0); glVertex3d(gridBigMax,y, 0.0); } } glEnd(); //xy lines glLineWidth(2.5*lineWidthFactor); glBegin(GL_LINES); glColor3f(1,1,1); glVertex3d(-gridBigMax,0, 0.0); glVertex3d(gridBigMax,0, 0.0); glVertex3d(0,-gridBigMax, 0.0); glVertex3d(0,gridBigMax, 0.0); // colored xy lines glColor3f(1,0,0); glVertex3d(0,0,0); glVertex3d(1,0,0); glColor3f(0,1,0); glVertex3d(0,0,0); glVertex3d(0,1,0); glColor3f(1,1,1); glVertex3d(0,0,0); glVertex3d(0,0,1); glEnd(); }
void ColorMaskChunk::activate(DrawEnv *, UInt32) { glColorMask(getMaskR(), getMaskG(), getMaskB(), getMaskA()); }