// Rendu de l'environnement (pour la réflexion de l'eau ou non) void SceneTerrain::RenderEnvironment(bool bWaterReflection, bool bDepthMap) { ResourceManager& res = ResourceManager::getInstance(); VarManager& var = VarManager::getInstance(); Camera& cam = Camera::getInstance(); vec4 white(1.0f, 1.0f, 1.0f, 1.0f); vec4 black(0.0f, 0.0f, 0.0f, 1.0f); vec4 orange(1.0f, 0.5f, 0.0f, 1.0f); vec4 yellow(1.0f, 1.0f, 0.8f, 1.0f); float sun_cosy = cosf(m_vSunAngle.y); glPushAttrib(GL_ENABLE_BIT); if(!bDepthMap) { vec4 vSunColor = white.lerp(orange, yellow, 0.25f + sun_cosy * 0.75f); if(cam.getEye().y < var.getf("water_height")) { bWaterReflection = false; var.set("enable_underwater", true); } else { var.set("enable_underwater", false); } // Affichage du ciel et du soleil Sky::getInstance().DrawSkyAndSun( Camera::getInstance().getEye(), vec3(m_vSunVector), m_pSkybox->getHandle(), bWaterReflection ); // Si c'est pour la réflexion, on dessine la scène à l'envers if(bWaterReflection) { glDisable(GL_CULL_FACE); glLoadIdentity(); glScalef(-1.0f, 1.0f, 1.0f); cam.RenderLookAt(true, var.getf("water_height")); } glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); vec3 zeros(0.0f, 0.0f, 0.0f); glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, zeros); glLightfv(GL_LIGHT0, GL_POSITION, m_vSunVector); glLightfv(GL_LIGHT0, GL_AMBIENT, white); glLightfv(GL_LIGHT0, GL_DIFFUSE, vSunColor); glLightfv(GL_LIGHT0, GL_SPECULAR, vSunColor); } // Affichage des maisons à l'arrache m_pShaderLighting->Activate(); { glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, white/6); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, white); res.getTexture2D("wall_diffuse.jpg")->Bind(0); res.getTexture2D("wall_NM_height.tga")->Bind(1); m_pShaderLighting->UniformTexture("texDiffuse", 0); m_pShaderLighting->UniformTexture("texNormalHeightMap", 1); m_pShaderLighting->Uniform("mode", 1); m_pShaderLighting->Uniform("enable_shadow_mapping", 0); m_pShaderLighting->Uniform("tile_factor", 2.0f); glPushMatrix(); glTranslatef(172.0f, 5.18f, 175.2f); res.getMesh("terrain_house.obj")->Draw(); glPopMatrix(); glPushMatrix(); glTranslatef(19.0f, 35.8f, -123.1f); res.getMesh("terrain_house.obj")->Draw(); glPopMatrix(); glPushMatrix(); glTranslatef(1.338f, 18.02f, 259.0f); res.getMesh("terrain_house.obj")->Draw(); glPopMatrix(); glPushMatrix(); glTranslatef(178.6f, 32.42f, 26.31f); res.getMesh("terrain_house.obj")->Draw(); glPopMatrix(); res.getTexture2D("wall_NM_height.tga")->Unbind(1); res.getTexture2D("wall_diffuse.jpg")->Unbind(0); } m_pShaderLighting->Deactivate(); if(!bDepthMap) { vec4 vGroundAmbient = white.lerp(white*0.2f, black, sun_cosy); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, vGroundAmbient); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, white); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, white); glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 50.0f); glMatrixMode(GL_TEXTURE); glActiveTexture(GL_TEXTURE0); glLoadMatrixf( m_matSunModelviewProj ); glMatrixMode(GL_MODELVIEW); // Activation des textures GLuint idx=0; for(GLuint i=0; i<m_tTextures.size(); i++) m_tTextures[i]->Bind(idx++); m_pTerrainDiffuseMap->Bind(idx++); if(!bDepthMap) { for(GLuint i=0; i<TERRAIN_SHADOWMAPS_COUNT; i++) m_fboDepthMapFromLight[i].Bind(idx++); } // Affichage du terrain m_pShaderTerrain->Activate(); { m_pShaderTerrain->Uniform("detail_scale", 120.0f); m_pShaderTerrain->Uniform("diffuse_scale", 70.0f); m_pShaderTerrain->Uniform("water_height", var.getf("water_height")); m_pShaderTerrain->Uniform("water_reflection_rendering", bWaterReflection); m_pShaderTerrain->Uniform("time", Timer::getInstance().getCurrentTime()); m_pShaderTerrain->UniformTexture("texNormalHeightMap", 0); m_pShaderTerrain->UniformTexture("texDiffuse0", 1); m_pShaderTerrain->UniformTexture("texDiffuse1", 2); m_pShaderTerrain->UniformTexture("texDiffuse2", 3); m_pShaderTerrain->UniformTexture("texWaterCaustics", 4); m_pShaderTerrain->UniformTexture("texDiffuseMap", 5); m_pShaderTerrain->UniformTexture("texDepthMapFromLight0", 6); m_pShaderTerrain->UniformTexture("texDepthMapFromLight1", 7); m_pShaderTerrain->Uniform("depth_map_size", 512); int ret = m_pTerrain->DrawGround(bWaterReflection); var.set(bWaterReflection? "terrain_chunks_reflected_drawn" : "terrain_chunks_drawn", ret); m_pTerrain->DrawInfinitePlane(Camera::getInstance().getEye(), 2.0f*var.getf("cam_zfar")); } m_pShaderTerrain->Deactivate(); // Désactivation des textures if(!bDepthMap) { for(GLint i=TERRAIN_SHADOWMAPS_COUNT-1; i>=0; i--) m_fboDepthMapFromLight[i].Unbind(--idx); } m_pTerrainDiffuseMap->Unbind(--idx); for(GLint i=(GLint)m_tTextures.size()-1; i>=0; i--) m_tTextures[i]->Unbind(--idx); // Affichage de l'herbe if(!bWaterReflection) { glEnable(GL_BLEND); m_pShaderGrass->Activate(); { res.getTexture2D("grass_billboards.tga")->Bind(0); for(GLuint i=0; i<TERRAIN_SHADOWMAPS_COUNT; i++) m_fboDepthMapFromLight[i].Bind(1+i); m_pShaderGrass->UniformTexture("texDiffuse", 0); m_pShaderGrass->UniformTexture("texDepthMapFromLight0", 1); m_pShaderGrass->UniformTexture("texDepthMapFromLight1", 2); m_pShaderGrass->Uniform("depth_map_size", 512); m_pShaderGrass->Uniform("time", Timer::getInstance().getCurrentTime()); m_pShaderGrass->Uniform("lod_metric", TERRAIN_GRASS_MAX_DISTANCE); m_pTerrain->DrawGrass(bWaterReflection); for(GLint i=TERRAIN_SHADOWMAPS_COUNT-1; i>=0; i--) m_fboDepthMapFromLight[i].Unbind(1+i); res.getTexture2D("grass_billboards.tga")->Unbind(0); } m_pShaderGrass->Deactivate(); glDisable(GL_BLEND); } glMatrixMode(GL_TEXTURE); glActiveTexture(GL_TEXTURE0); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); } m_pShaderTree->Activate(); { glMatrixMode(GL_TEXTURE); glActiveTexture(GL_TEXTURE0); glLoadMatrixf( Frustum::getInstance().getModelviewInvMatrix() ); glMatrixMode(GL_MODELVIEW); GLuint idx=0; res.getTexture2D("palm_texture.tga")->Bind(idx++); if(!bDepthMap) { for(GLuint i=0; i<TERRAIN_SHADOWMAPS_COUNT; i++) m_fboDepthMapFromLight[i].Bind(idx++); } m_pShaderTree->UniformTexture("texDiffuse", 0); m_pShaderTree->UniformTexture("texDepthMapFromLight0", 1); m_pShaderTree->UniformTexture("texDepthMapFromLight1", 2); m_pShaderTree->Uniform("time", Timer::getInstance().getCurrentTime()); m_pTerrain->DrawObjects(bWaterReflection); res.getTexture2D("palm_texture.tga")->Unbind(--idx); if(!bDepthMap) { for(GLint i=TERRAIN_SHADOWMAPS_COUNT-1; i>=0; i--) m_fboDepthMapFromLight[i].Unbind(--idx); } glMatrixMode(GL_TEXTURE); glActiveTexture(GL_TEXTURE0); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); } m_pShaderTree->Deactivate(); glPopAttrib(); }
/* ============= R_SetupGL ============= */ void R_SetupGL (void) { float screenaspect; float yfov; int i; extern int glwidth, glheight; int x, x2, y2, y, w, h; // // set up viewpoint // glMatrixMode(GL_PROJECTION); glLoadIdentity (); x = r_refdef.vrect.x * glwidth/vid.width; x2 = (r_refdef.vrect.x + r_refdef.vrect.width) * glwidth/vid.width; y = (vid.height-r_refdef.vrect.y) * glheight/vid.height; y2 = (vid.height - (r_refdef.vrect.y + r_refdef.vrect.height)) * glheight/vid.height; // fudge around because of frac screen scale if (x > 0) x--; if (x2 < glwidth) x2++; if (y2 < 0) y2--; if (y < glheight) y++; w = x2 - x; h = y - y2; if (envmap) { x = y2 = 0; w = h = 256; } glViewport (glx + x, gly + y2, w, h); screenaspect = (float)r_refdef.vrect.width/r_refdef.vrect.height; // yfov = 2*atan((float)r_refdef.vrect.height/r_refdef.vrect.width)*180/M_PI; MYgluPerspective (r_refdef.fov_y, screenaspect, 4, 4096); if (mirror) { if (mirror_plane->normal[2]) glScalef (1, -1, 1); else glScalef (-1, 1, 1); glCullFace(GL_BACK); } else glCullFace(GL_FRONT); glMatrixMode(GL_MODELVIEW); #ifdef DO_OWN_MATRIX_MATH float mv[16]; setIdentityM(mv, 0); rotateM(mv, -90, 1, 0, 0); // put Z going up rotateM(mv, 90, 0, 0, 1); // put Z going up rotateM(mv, -r_refdef.viewangles[2], 1, 0, 0); rotateM(mv, -r_refdef.viewangles[0], 0, 1, 0); rotateM(mv, -r_refdef.viewangles[1], 0, 0, 1); translateM(mv, 0, -r_refdef.vieworg[0], -r_refdef.vieworg[1], -r_refdef.vieworg[2]); glLoadMatrixf(mv); memcpy(r_world_matrix, mv, sizeof(r_world_matrix)); #else glLoadIdentity (); glRotatef (-90, 1, 0, 0); // put Z going up glRotatef (90, 0, 0, 1); // put Z going up glRotatef (-r_refdef.viewangles[2], 1, 0, 0); glRotatef (-r_refdef.viewangles[0], 0, 1, 0); glRotatef (-r_refdef.viewangles[1], 0, 0, 1); glTranslatef (-r_refdef.vieworg[0], -r_refdef.vieworg[1], -r_refdef.vieworg[2]); #ifdef USE_OPENGLES static qboolean initialized; static qboolean haveGL_OES_matrix_get; static qboolean haveGL_OES_query_matrix; #if 0 if (! initialized) { const char* extensions = (const char*) glGetString(GL_EXTENSIONS); haveGL_OES_matrix_get = strstr(extensions, "GL_OES_matrix_get") != NULL; haveGL_OES_query_matrix = strstr(extensions, "GL_OES_query_matrix") != NULL; initialized = true; } if (haveGL_OES_query_matrix) { GLfixed mantissa[16]; GLint exponent[16]; glQueryMatrixxOES( mantissa, exponent ); for(int i = 0; i < 16; i++) { r_world_matrix[i] = scalbnf(mantissa[i], exponent[i]-16); } } else if (haveGL_OES_matrix_get) { glGetIntegerv (MODELVIEW_MATRIX_FLOAT_AS_INT_BITS_OES, (GLint*) r_world_matrix); } else #endif { // No way to get the world matix, set to identity memset(r_world_matrix, 0, sizeof(r_world_matrix)); for(i = 0; i < 16; i += 5) { r_world_matrix[i] = 1.0f; } } #else glGetFloatv (GL_MODELVIEW_MATRIX, r_world_matrix); #endif #endif // DO_OWN_MATRIX_MATH // // set drawing parms // if (gl_cull.value) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE); glDisable(GL_BLEND); glDisable(GL_ALPHA_TEST); glEnable(GL_DEPTH_TEST); }
static void GL_LoadMatrix(float m[4][4]) { glLoadMatrixf((float*)m); }
/* ‘ункци¤ построени¤ объекта анимации. * ј–√”ћ≈Ќ“џ: * - указатель на "себ¤" - сам объект анимации: * ok2UNIT_CUBE *Unit; * - указатель на контекст анимации: * ok2ANIM *Ani; * ¬ќ«¬–јўј≈ћќ≈ «Ќј„≈Ќ»≈: Ќет. */ static VOID CubeUnitRender( ok2UNIT_CUBE *Unit, ok2ANIM *Ani ) { /* INT i, s = 5, N = 0; VEC p = {1, 0, 0}; static FLT Delta = 0.1; MATR WVP; Delta += Ani->JZ * Ani->GlobalDeltaTime; //Ani->MatrWorld = MatrRotateY(30); //Ani->MatrView = MatrLookAt(VecSet(15, 15, 15), VecSet(0, 0, 0), VecSet(0, 1, 0)); Ani->MatrView = MatrLookAt(PointTransform(VecSet(20, 20, Ani->JX * Delta + 20), MatrRotateX(80 * Ani->JY)), VecSet(0, 0, 0), VecSet(0, 1, 0)); Ani->MatrWorld = MatrMulMatr(Ani->MatrWorld, MatrRotateX(Ani->DeltaTime * 80)); for (i = 0; i < 12; i++) { Ani->MatrWorld = MatrMulMatr(MatrTranslate(0.0, 5.0, 0.0), Ani->MatrWorld); Ani->MatrWorld = MatrMulMatr(MatrRotate(30, 1.0, 0.0, 1.0), Ani->MatrWorld); WVP = MatrMulMatr(Ani->MatrWorld, MatrMulMatr(Ani->MatrView, Ani->MatrProjection)); glLoadMatrixf(WVP.A[0]); OK2_RndGObjDraw(&Unit->Cow, Ani->hDC); } //OK2_RndGObjDraw(&Unit->Cow, Ani->hDC); */ INT i; MATR WVP; static DBL time; /* оси и позици¤ наблюдател¤ */ Ani->MatrWorld = MatrIdenity(); Ani->MatrView = MatrLookAt( PointTransform(PointTransform(VecSet(25, 25, 25), MatrRotateY(Ani->JR * 180)), MatrRotateZ(Ani->JY * 180)), VecSet(0, 0, 0), VecSet(0, 1, 0)); WVP = MatrMulMatr(OK2_Anim.MatrWorld, MatrMulMatr(OK2_Anim.MatrView, OK2_Anim.MatrProjection)); glLoadMatrixf(WVP.A[0]); glLineWidth(3); glBegin(GL_LINES); glColor3d(1, 0.5, 0.5); glVertex3d(-3, 0, 0); glVertex4d(1, 0, 0, 0); glColor3d(0.5, 1, 0.5); glVertex3d(0, -3, 0); glVertex4d(0, 1, 0, 0); glColor3d(0.5, 0.5, 1); glVertex3d(0, 0, -3); glVertex4d(0, 0, 1, 0); glEnd(); glColorMask(1, 1, 1, 0); for (i = -3; i < 30; i++) { glBegin(GL_TRIANGLE_STRIP); glVertex3d(-0.1, -0.1, i); glVertex3d(-0.1, 0.1, i); glVertex3d( 0.1, -0.1, i); glVertex3d( 0.1, 0.1, i); glEnd(); } /* –исуем примитивы */ time += Ani->GlobalDeltaTime; if (time > 1) { time = 0; OK2_ShadProgClose(OK2_ShaderProg); OK2_ShaderProg = OK2_ShadProgInit("a.vert", "a.frag"); } glLineWidth(1); if (Ani->Keys['Q']) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); else glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); //Ani->MatrWorld = MatrTranslate(0, 0, 0.30 * sin(Ani->Time)); Ani->MatrWorld = MatrMulMatr(Ani->MatrWorld, MatrRotateY(30.0 * Ani->Time)); /* for (i = 0; i < 12; i++) { Ani->MatrWorld = MatrMulMatr(MatrRotate(30.0, 0.0, 1.0, 0.0), Ani->MatrWorld); Ani->MatrWorld = MatrMulMatr(MatrTranslate(1.0, 0.0, 0.0), Ani->MatrWorld); OK2_GeomDraw(&Unit->Geom); } */ /* for (i = 0; i < 6; i++) DrawUnitInPosition(&Unit->Geom[i], Ani, Unit->Scale`[i], 10.0, 30.0); */ Ani->MatrWorld = MatrMulMatr(Ani->MatrWorld, MatrScale(0.001, 0.001, 0.001)); for (i = 0; i < 12; i++) { Ani->MatrWorld = MatrMulMatr(MatrRotate(30.0, 0.0, 1.0, 0.0), Ani->MatrWorld); Ani->MatrWorld = MatrMulMatr(MatrTranslate(20000.0, 0.0, 0.0), Ani->MatrWorld); //Ani->MatrWorld = MatrMulMatr(MatrRotate(30.0, 0.0, 1.0, 0.0), Ani->MatrWorld); OK2_GeomDraw(&Unit->Geom[3]); Ani->MatrWorld = MatrMulMatr(MatrTranslate(-20000.0, 0.0, 0.0), Ani->MatrWorld); } //Ani->MatrWorld = MatrMulMatr(Ani->MatrWorld, MatrScale(50, 50, 50)); } /* End of 'OK2_AnimUnitRender' function */
void SimulatorViewport::draw(Application* application) { resetOpenGL(); User* user = Kernel::getInstance()->users.front(); glm::mat4 camera; if (cameraDevice && cameraDevice->isInitialized()) camera = cameraDevice->getData(); glm::mat4 projectionMatrix = getProjectionMatrix(); glEnable(GL_DEPTH_TEST); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glLoadMatrixf(glm::value_ptr(projectionMatrix)); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glLoadMatrixf(glm::value_ptr(camera)); glPushMatrix(); application->draw(projectionMatrix, camera); glPopMatrix(); resetOpenGL(); shader->use(); shader->setUniform(Uniforms::projectionMatrix, projectionMatrix); shader->setUniform(Uniforms::viewMatrix, camera * user->matrix); faceModel->draw([this](const glm::mat4& modelMatrix) { }); glPushAttrib(GL_ENABLE_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glLoadMatrixf(glm::value_ptr(projectionMatrix)); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glLoadMatrixf(glm::value_ptr(camera)); glUseProgram(0); glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor4f(1, 1, 1, 0.25f); glBegin(GL_QUADS); for (std::list<ViewPortCorners>::iterator it = viewports.begin(); it != viewports.end(); it++) { glVertex3fv(glm::value_ptr(it->tl)); glVertex3fv(glm::value_ptr(it->tr)); glVertex3fv(glm::value_ptr(it->br)); glVertex3fv(glm::value_ptr(it->bl)); } glEnd(); glDisable(GL_DEPTH_TEST); glColor4f(1, 1, 1, 0.75f); for (std::list<ViewPortCorners>::iterator it = viewports.begin(); it != viewports.end(); it++) { glBegin(GL_LINE_LOOP); glVertex3fv(glm::value_ptr(it->tl)); glVertex3fv(glm::value_ptr(it->tr)); glVertex3fv(glm::value_ptr(it->br)); glVertex3fv(glm::value_ptr(it->bl)); glEnd(); } glColor4f(1, 1, 1, 1); glDisable(GL_LIGHTING); glEnable(GL_TEXTURE_2D); glEnable(GL_DEPTH_TEST); glPopAttrib(); }
void ARHelper::draw() { ofSetColor(0xffffff); if (mode == SKETCH) { convert.draw(0, 0,ofGetWidth(),ofGetHeight()); } else if (mode == FILL) { convert.draw(0, -(displayH-ofGetHeight())/2,displayW,displayH); //glViewport(0, -(displayH-ofGetHeight())/2, displayW,displayH); } glViewport(0, 0, ofGetWidth(), ofGetHeight() ); //else if(mode == FIT)convert.draw(0, 0,ofGetWidth(),ofGetHeight()); //this is where we use the calculated matrix from ARToolkitPlus to put //in our graphics at the location and orientation of the marker. //- the matrix has the 0,0 point as the center of the marker. glMatrixMode( GL_PROJECTION ); glLoadMatrixf(tracker->getProjectionMatrix()); float m[ 16 ]; #ifdef SINGE_MARKER if (markerId !=-1) { for (int i=0; i<16; i++) m[i] = tracker->getModelViewMatrix()[i]; if (modelHandler!=NULL && int(conf*100.0f)>tol)modelHandler->updateModelMatrix(markerId , m,(float*) tracker->getProjectionMatrix()); } #else int numDetected = tracker->getNumDetectedMarkers(); for (int i=0; i<numDetected; i++) { ARToolKitPlus::ARMarkerInfo marker = tracker->getDetectedMarker(i); float m34[ 3 ][ 4 ]; float c[ 2 ] = { 0.0f, 0.0f }; float w = 40.0f; tracker->rppGetTransMat( &marker, c, w, m34 ); float m[ 16 ]; //this is some crazy matrix transformative stuff. I think initially it came out of one of the arToolkit functions.... but i got it from here: http://chihara.naist.jp/people/STAFF/imura/computer/OpenGL/artp/disp_content for ( int i = 0; i < 3; i++ ) { for ( int j = 0; j < 4; j++ ) { m[ j * 4 + i ] = m34[ i ][ j ]; } } for ( int j = 0; j < 3; j++ ) { m[ j * 4 + 3 ] = 0.0f; } m[ 3 * 4 + 3 ] = 1.0f; if (modelHandler!=NULL )modelHandler->updateModelMatrix(marker.id , m,(float*) tracker->getProjectionMatrix()); //if (modelHandler!=NULL)modelHandler->updateModelMatrix(marker.id , m); debugDraw(marker.id,m); } #endif //#ifdef SINGE_MARKER glEnable(GL_DEPTH_TEST); if (modelHandler!=NULL)modelHandler->draw(); north.draw(-256,-256); glDisable(GL_DEPTH_TEST); glDisable(GL_DEPTH_TEST); debugDraw(markerId,m); glEnable(GL_DEPTH_TEST); GLdouble model_view[16]; GLdouble projection[16]; GLint viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); for (int i=0; i<16; i++) { model_view[i] = tracker->getModelViewMatrix()[i]; projection[i] = tracker->getProjectionMatrix()[i]; } if (modelHandler!=NULL) for (int i = 0 ; i<modelHandler->getModel().size() ; i++) { modelHandler->getModel()[i]->findScreenCoord(projection,viewport); } GLdouble ret_x, ret_y, ret_z; gluProject(0,0,0, model_view, projection, viewport, &ret_x, &ret_y, &ret_z); float x = ret_x; float y = ofGetHeight()-ret_y; markerV.set(x,y); ofSetupScreen(); if (bDebug) { ofNoFill(); ofSetColor(255,255,255,125); ofRect(-50+x,-50+y,100,100); ofRect(0,(ofGetHeight()/2)-IMAGE_AREA,ofGetWidth(),IMAGE_AREA*2); } { glDisable(GL_DEPTH_TEST); if (modelHandler!=NULL)modelHandler->draw2D(); glEnable(GL_DEPTH_TEST); } }
void OpenGLRender::blitText(IND_Font *pFo, char *pText, int pX, int pY, int pOffset, int pLineSpacing, float pScaleX, float pScaleY, BYTE pR, BYTE pG, BYTE pB, BYTE pA, BYTE pFadeR, BYTE pFadeG, BYTE pFadeB, BYTE pFadeA, IND_Filter pLinearFilter, IND_BlendingType pSo, IND_BlendingType pDs, IND_Align pAlign) { // ----- Transform ----- bool correctParams = true; if(!pFo->getSurface()) { correctParams = false; } if (correctParams) { setTransform2d(pX, pY, 0, 0, 0, pScaleX, pScaleY, 0, 0, 0, 0, pFo->getSurface()->getWidthBlock(), pFo->getSurface()->getHeightBlock(), 0); setRainbow2d(pFo->_font._surface->getTypeInt(), 1, 0, 0, pLinearFilter, pR, pG, pB, pA, pFadeR, pFadeG, pFadeB, pFadeA, pSo, pDs); // ----- Drawing text ----- BYTE mChar1; BYTE mChar2; int mCont1 = 0; int mCont2 = 0; int mTranslationX = 0; int mTranslationY = 0; bool mErrorChar; // Char that doesn't exist int mSentencePos; int mLongActualSentence; GLfloat mLineTransform[16]; //Maintains a transform inside the entity coord system GLfloat mEntityTransform[16]; //Maintains transform for the whole entity coord system mCont1 = 0; mChar1 = pText [mCont1++]; //Store entity transform glGetFloatv(GL_MODELVIEW_MATRIX,mEntityTransform); //LOOP - Blit character by character while (mChar1 != 0) { // If it's a new line or it's the first line if (mChar1 == '\n' || mCont1 == 1) { // First line if (mCont1 == 1) { mSentencePos = 0; //Any other line } else { mSentencePos = mCont1; } // Set the alignment switch (pAlign) { case IND_CENTER: { mLongActualSentence = static_cast<int>(getLongInPixels(pFo, pText, mSentencePos, pOffset) * pScaleX); mTranslationX = (int)(mLongActualSentence / 2); break; } case IND_RIGHT: { mLongActualSentence = static_cast<int>(getLongInPixels(pFo, pText, mSentencePos, pOffset) * pScaleX); mTranslationX = (int)(mLongActualSentence); break; } case IND_LEFT: { break; } } //Load line transform matrix taking into account entity transform //This effectively resets transform to first character in the new line IND_Matrix transform; _math.matrix4DSetTranslation(transform, static_cast<float>(-mTranslationX), static_cast<float>(mTranslationY), 0.0f); transform.arrayRepresentation(mLineTransform); glLoadMatrixf(mEntityTransform); glMultMatrixf(mLineTransform); mTranslationY += static_cast<int>((pLineSpacing * pScaleY)); } //Was first new line or first line // It's a normal character if (mChar1 != '\n') { mErrorChar = 0; mCont2 = 0; mChar2 = pFo->getLetters() [mCont2++]._letter; // Seek its location in the bitmap while (mChar2 != mChar1 && mCont2 < pFo->getNumChars()) { mChar2 = pFo->getLetters() [mCont2++]._letter; } if (mCont2 == pFo->getNumChars()) mErrorChar = 1; mCont2--; if (!mErrorChar) { //#warning lookout //mvTransformPresetState(); //Need to preset transform state, as the blit operation will reset the state!!!! blitRegionSurface(pFo->getSurface(), pFo->getLetters() [mCont2]._offsetX + 1, pFo->getLetters() [mCont2]._offsetY + 1, pFo->getLetters() [mCont2]._widthChar - 1, pFo->getLetters() [mCont2]._heightChar - 1); } //Displacement of the character. //Displacement transform accumulates for every character in the line float charTranslateX = ((pFo->getLetters() [mCont2]._widthChar) + pOffset) * pScaleX; glTranslatef(charTranslateX,0.0f,0.0f); }//Was normal character // Advance one character mChar1 = pText [mCont1++]; }//LOOP END - Blit character by character } }
/*!**************************************************************************** @Function RenderScene @Return bool true if no error occured @Description Main rendering loop function of the program. The shell will call this function every frame. eglSwapBuffers() will be performed by PVRShell automatically. PVRShell will also manage important OS events. Will also manage relevent OS events. The user has access to these events through an abstraction layer provided by PVRShell. ******************************************************************************/ bool OGLESPVRScopeExample::RenderScene() { // Keyboard input (cursor up/down to cycle through counters) if(PVRShellIsKeyPressed(PVRShellKeyNameUP)) { m_i32Counter++; if(m_i32Counter > (int) m_pScopeGraph->GetCounterNum()) m_i32Counter = m_pScopeGraph->GetCounterNum(); } if(PVRShellIsKeyPressed(PVRShellKeyNameDOWN)) { m_i32Counter--; if(m_i32Counter < 0) m_i32Counter = 0; } if(PVRShellIsKeyPressed(PVRShellKeyNameACTION2)) m_pScopeGraph->ShowCounter(m_i32Counter, !m_pScopeGraph->IsCounterShown(m_i32Counter)); // Keyboard input (cursor left/right to change active group) if(PVRShellIsKeyPressed(PVRShellKeyNameRIGHT)) { m_pScopeGraph->SetActiveGroup(m_pScopeGraph->GetActiveGroup()+1); } if(PVRShellIsKeyPressed(PVRShellKeyNameLEFT)) { m_pScopeGraph->SetActiveGroup(m_pScopeGraph->GetActiveGroup()-1); } // Clears the color and depth buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Loads the projection matrix glMatrixMode(GL_PROJECTION); glLoadMatrixf(m_mProjection.f); // Specify the modelview matrix PVRTMat4 mModel; SPODNode& Node = m_Scene.pNode[0]; m_Scene.GetWorldMatrix(mModel, Node); // Rotate and Translate the model matrix m_fAngleY += (2*PVRT_PIf/60)/7; // Set model view projection matrix PVRTMat4 mModelView; mModelView = m_mView * PVRTMat4::RotationY(m_fAngleY) * mModel; glMatrixMode(GL_MODELVIEW); glLoadMatrixf(mModelView.f); /* Load the light direction from the scene if we have one */ // Enables lighting. See BasicTnL for a detailed explanation glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); // Set light direction PVRTVec4 vLightDirModel; vLightDirModel = mModel.inverse() * PVRTVec4(1, 1, 1, 0); glLightfv(GL_LIGHT0, GL_POSITION, (float*)&vLightDirModel.x); // Enable the vertex position attribute array glEnableClientState(GL_VERTEX_ARRAY); // bind the texture glBindTexture(GL_TEXTURE_2D, m_uiTexture); /* Now that the model-view matrix is set and the materials are ready, call another function to actually draw the mesh. */ DrawMesh(Node.nIdx); // Disable the vertex positions glDisableClientState(GL_VERTEX_ARRAY); char Description[256]; if(m_pScopeGraph->GetCounterNum()) { sprintf(Description, "Active Grp %i\n\nCounter %i (Grp %i) \nName: %s\nShown: %s\nuser y-axis: %.2f max: %.2f%s", m_pScopeGraph->GetActiveGroup(), m_i32Counter, m_pScopeGraph->GetCounterGroup(m_i32Counter), m_pScopeGraph->GetCounterName(m_i32Counter), m_pScopeGraph->IsCounterShown(m_i32Counter) ? "Yes" : "No", m_pScopeGraph->GetMaximum(m_i32Counter), m_pScopeGraph->GetMaximumOfData(m_i32Counter), m_pScopeGraph->IsCounterPercentage(m_i32Counter) ? "%%" : ""); } else { sprintf(Description, "No counters present"); } // Displays the demo name using the tools. For a detailed explanation, see the training course IntroducingPVRTools m_Print3D.DisplayDefaultTitle("PVRScopeExample", Description, ePVRTPrint3DSDKLogo); m_Print3D.Flush(); // Update counters and draw the graph m_pScopeGraph->Ping(); return true; }
int main(int argc, char *argv[]) { SDL_Surface *screen; if ( SDL_Init(SDL_INIT_VIDEO) != 0 ) { printf("Unable to initialize SDL: %s\n", SDL_GetError()); return 1; } SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); screen = SDL_SetVideoMode( 640, 480, 24, SDL_OPENGL ); if ( !screen ) { printf("Unable to set video mode: %s\n", SDL_GetError()); return 1; } glClearColor( 0, 0, 0, 0 ); glClear( GL_COLOR_BUFFER_BIT ); // Fog glEnable(GL_FOG); glFogf(GL_FOG_START, 100); glFogf(GL_FOG_END, 2000); glFogi(GL_FOG_MODE, GL_LINEAR); GLfloat fogcolor[4] = { 0.9, 0.1, 0.35, 0 }; glFogfv(GL_FOG_COLOR, fogcolor); // Create a texture GLuint texture; glGenTextures( 1, &texture ); glBindTexture( GL_TEXTURE_2D, texture ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); GLubyte textureData[16*16*4]; for (int x = 0; x < 16; x++) { for (int y = 0; y < 16; y++) { *((int*)&textureData[(x*16 + y) * 4]) = x*16 + ((y*16) << 8); } } glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, 16, 16, 0, GL_RGBA, GL_UNSIGNED_BYTE, textureData ); // Create a second texture GLuint texture2; glGenTextures( 1, &texture2 ); glBindTexture( GL_TEXTURE_2D, texture2 ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); GLubyte texture2Data[] = { 0xff, 0, 0, 0xff, 0, 0xff, 0, 0xaa, 0, 0, 0xff, 0x55, 0x80, 0x90, 0x70, 0 }; glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, 2, 2, 0, GL_RGBA, GL_UNSIGNED_BYTE, texture2Data ); // BEGIN #if USE_GLEW glewInit(); #endif glMatrixMode(GL_PROJECTION); glLoadIdentity(); // original: glFrustum(-0.6435469817188064, 0.6435469817188064 ,-0.48266022190470925, 0.48266022190470925 ,0.5400000214576721, 2048); glFrustum(-0.6435469817188064, 0.1435469817188064 ,-0.48266022190470925, 0.88266022190470925 ,0.5400000214576721, 2048); glRotatef(-30, 1, 1, 1); //GLfloat pm[] = { 1.372136116027832, 0, 0, 0, 0, 0.7910231351852417, 0, 0, -0.6352481842041016, 0.29297152161598206, -1.0005275011062622, -1, 0, 0, -1.080284833908081, 0 }; //glLoadMatrixf(pm); glMatrixMode(GL_MODELVIEW); GLfloat matrixData[] = { -1, 0, 0, 0, 0, 0,-1, 0, 0, 1, 0, 0, 0, 0, 0, 1 }; glLoadMatrixf(matrixData); //glTranslated(-512,-512,-527); // XXX this should be uncommented, but if it is then nothing is shown glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glClear(GL_DEPTH_BUFFER_BIT); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glActiveTexture(GL_TEXTURE0); glEnableClientState(GL_VERTEX_ARRAY); GLuint arrayBuffer, elementBuffer; glGenBuffers(1, &arrayBuffer); glGenBuffers(1, &elementBuffer); GLubyte arrayData[] = { /* [0, 0, 0, 67] ==> 128 float [0, 0, 128, 67] ==> 256 float [0, 0, 0, 68] ==> 512 float [0, 0, 128, 68] ==> 1024 float [vertex x ] [vertex y ] [vertex z ] [nr] [texture u ] [texture v ] [lm u ] [lm v ] [color r,g,b,a ] */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 68, 11, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, // 0 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 68, 23, 20, 0, 0, 0, 0, 0, 67, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, // 1 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 35, 30, 0, 0, 0, 0, 0, 67, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 2 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 68, 47, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 3 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 68, 51, 50, 0, 0, 0, 0, 0, 67, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, // 4 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 68, 64, 60, 0, 0, 0, 0, 128, 67, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, // 5 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 68, 70, 70, 0, 0, 0, 0, 128, 67, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 6 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 89, 80, 0, 0, 0, 0, 0, 67, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 7 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 68, 94, 90, 0, 0, 0, 0, 0, 0, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 8 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 20, 10, 0, 0, 0, 0, 0, 67, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 9 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 68, 31, 20, 0, 0, 0, 0, 0, 67, 0, 0, 128, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 10 0, 0, 0, 0, 0, 0, 128, 68, 0, 0, 0, 68, 42, 30, 0, 0, 0, 0, 0, 0, 0, 0, 128, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 11 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 53, 40, 0, 0, 0, 0, 0, 67, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 12 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 68, 64, 50, 0, 0, 0, 0, 128, 67, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 13 0, 0, 128, 68, 0, 0, 128, 68, 0, 0, 0, 68, 75, 60, 0, 0, 0, 0, 128, 67, 0, 0, 128, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 14 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 68, 86, 70, 0, 0, 0, 0, 0, 67, 0, 0, 128, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 15 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 128, 68, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128 }; assert(sizeof(arrayData) == 1408); glBindBuffer(GL_ARRAY_BUFFER, arrayBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(arrayData), arrayData, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); GLushort elementData[] = { 1, 2, 0, 2, 3, 0, 5, 6, 4, 6, 7, 4, 9, 10, 8, 10, 11, 8, 13, 14, 12, 14, 15, 12 }; assert(sizeof(elementData) == 48); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementBuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elementData), elementData, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, arrayBuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementBuffer); // sauer vertex data is apparently 0-12: V3F, 12: N1B, 16-24: T2F, 24-28: T2S, 28-32: C4B glVertexPointer(3, GL_FLOAT, 32, (void*)0); // all these apply to the ARRAY_BUFFER that is bound glTexCoordPointer(2, GL_FLOAT, 32, (void*)16); glClientActiveTexture(GL_TEXTURE1); // XXX seems to be ignored in native build glTexCoordPointer(2, GL_SHORT, 32, (void*)24); glClientActiveTexture(GL_TEXTURE0); // likely not needed, it is a cleanup glNormalPointer(GL_BYTE, 32, (void*)12); glColorPointer(4, GL_UNSIGNED_BYTE, 32, (void*)28); glBindTexture(GL_TEXTURE_2D, texture); // diffuse? glActiveTexture(GL_TEXTURE0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture2); // lightmap? glActiveTexture(GL_TEXTURE0); GLint ok; const char *vertexShader = "uniform vec4 texgenscroll;\n" "void main(void)\n" "{\n" " gl_Position = ftransform();\n" " gl_TexCoord[0].xy = gl_MultiTexCoord0.xy/10000.0 + (0.001*texgenscroll.xy) + gl_Normal.xy;\n" // added /100 here " gl_TexCoord[1].xy = gl_MultiTexCoord1.xy/100.0 * 3.051851e-05;\n" " gl_FogFragCoord = gl_Position.z;\n" "}\n"; const char *fragmentShader = "uniform vec4 colorparams;\n" "uniform sampler2D diffusemap, lightmap;\n" "void main(void)\n" "{\n" " vec4 diffuse = texture2D(diffusemap, gl_TexCoord[0].xy);\n" " vec4 lm = texture2D(lightmap, gl_TexCoord[1].xy);\n" " diffuse *= colorparams;\n" " vec4 color = diffuse * lm;\n" " gl_FragColor.rgb = mix((gl_Fog.color).rgb, color.rgb, clamp((gl_Fog.end - gl_FogFragCoord) * gl_Fog.scale, 0.0, 1.0));\n" //" gl_FragColor.rgb = 0.0001 * color.rgb + ((gl_Fog.color).rgb * (1.0-clamp((gl_FogFragCoord)* 1.0/1000.0, 0.0, 1.0)));\n" "}\n"; GLuint vs = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vs, 1, &vertexShader, NULL); glCompileShader(vs); glGetShaderiv(vs, GL_COMPILE_STATUS, &ok); assert(ok); GLuint fs = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fs, 1, &fragmentShader, NULL); glCompileShader(fs); glGetShaderiv(fs, GL_COMPILE_STATUS, &ok); assert(ok); GLuint program = glCreateProgram(); glAttachShader(program, vs); glAttachShader(program, fs); glLinkProgram(program); glGetProgramiv(program, GL_LINK_STATUS, &ok); assert(ok); glUseProgram(program); GLint lightmapLocation = glGetUniformLocation(program, "lightmap"); assert(lightmapLocation >= 0); glUniform1i(lightmapLocation, 1); // sampler2D? Is it the texture unit? GLint diffusemapLocation = glGetUniformLocation(program, "diffusemap"); assert(diffusemapLocation >= 0); glUniform1i(diffusemapLocation, 0); GLint texgenscrollLocation = glGetUniformLocation(program, "texgenscroll"); assert(texgenscrollLocation >= 0); GLint colorparamsLocation = glGetUniformLocation(program, "colorparams"); assert(colorparamsLocation >= 0); GLfloat texgenscrollData[] = { 0, 0, 0, 0 }; glUniform4fv(texgenscrollLocation, 1, texgenscrollData); GLfloat colorparamsData[] = { 2, 2, 2, 1 }; glUniform4fv(colorparamsLocation, 1, colorparamsData); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)12); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*) 0); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)24); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)36); // END SDL_GL_SwapBuffers(); #if !EMSCRIPTEN SDL_Delay(1500); #endif SDL_Quit(); return 0; }
/******************************************************************************* * Function Name : InitView * Inputs : uWidth, uHeight * Returns : true if no error occured * Description : Code in InitView() will be called by the Shell upon a change * in the rendering context. * Used to initialize variables that are dependant on the rendering * context (e.g. textures, vertex buffers, etc.) *******************************************************************************/ bool OGLESLighting::InitView() { CPVRTString ErrorStr; SPVRTContext sContext; PVRTMat4 mProjection; int i; // Is the screen rotated? bool bRotate = PVRShellGet(prefIsRotated) && PVRShellGet(prefFullScreen); // Initialize Print3D textures if(m_Print3D.SetTextures(&sContext, PVRShellGet(prefWidth), PVRShellGet(prefHeight), bRotate) != PVR_SUCCESS) { PVRShellSet(prefExitMessage, "ERROR: Cannot initialise Print3D\n"); return false; } // Load textures if(!LoadTextures(&ErrorStr)) { PVRShellSet(prefExitMessage, ErrorStr.c_str()); return false; } // Initialize VBO data LoadVbos(); // Setup all materials float Ambient[] = {0.1f, 0.1f, 0.1f, 1.0f}; float Diffuse[] = {0.5f, 0.5f, 0.5f, 1.0f}; float Specular[]= {1.0f, 1.0f, 1.0f, 1.0f}; glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, Ambient); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, Diffuse); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, Specular); glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 10.0f); // Nice and shiny so we don't get aliasing from the 1/2 angle // Initialize all lights srand(0); for(i = 0; i < 8; ++i) InitLight(m_psLightData[i]); // Perspective matrix // Calculate the projection matrix mProjection = PVRTMat4::PerspectiveFovRH(20.0f*(PVRT_PIf/180.0f), (float)PVRShellGet(prefWidth)/(float)PVRShellGet(prefHeight), 10.0f, 1200.0f, PVRTMat4::OGL, bRotate); glMatrixMode(GL_PROJECTION); glLoadMatrixf(mProjection.f); // Modelview matrix glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0.0f, 0.0f, -500.0f); // Setup culling glEnable(GL_CULL_FACE); // Enable texturing glEnable(GL_TEXTURE_2D); /* Build an array to map the textures within the pod file to the textures we loaded earlier. */ m_pui32Textures = new GLuint[m_Scene.nNumMaterial]; for(i = 0; i < (int) m_Scene.nNumMaterial; ++i) { m_pui32Textures[i] = 0; SPODMaterial* pMaterial = &m_Scene.pMaterial[i]; if(!strcmp(pMaterial->pszName, "Stone")) m_pui32Textures[i] = m_ui32Stone; } // Set the clear colour glClearColor(0.0f, 0.0f, 0.0f, 1.0f); return true; }
static void tex_mat_set_texture_cb(void *userData, int mat_nr, void *attribs) { /* texture draw mode without GLSL */ TexMatCallback *data = (TexMatCallback *)userData; GPUVertexAttribs *gattribs = attribs; Image *ima; ImageUser *iuser; bNode *node; int texture_set = 0; /* draw image texture if we find one */ if (ED_object_get_active_image(data->ob, mat_nr, &ima, &iuser, &node, NULL)) { /* get openl texture */ int mipmap = 1; int bindcode = (ima) ? GPU_verify_image(ima, iuser, 0, 0, mipmap, false) : 0; float zero[4] = {0.0f, 0.0f, 0.0f, 0.0f}; if (bindcode) { NodeTexBase *texbase = node->storage; /* disable existing material */ GPU_disable_material(); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, zero); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, zero); glMateriali(GL_FRONT_AND_BACK, GL_SHININESS, 0); /* bind texture */ glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE); glEnable(GL_COLOR_MATERIAL); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, ima->bindcode); glColor3f(1.0f, 1.0f, 1.0f); glMatrixMode(GL_TEXTURE); glLoadMatrixf(texbase->tex_mapping.mat); glMatrixMode(GL_MODELVIEW); /* use active UV texture layer */ memset(gattribs, 0, sizeof(*gattribs)); gattribs->layer[0].type = CD_MTFACE; gattribs->layer[0].name[0] = '\0'; gattribs->layer[0].gltexco = 1; gattribs->totlayer = 1; texture_set = 1; } } if (!texture_set) { glMatrixMode(GL_TEXTURE); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); /* disable texture */ glDisable(GL_TEXTURE_2D); glDisable(GL_COLOR_MATERIAL); /* draw single color */ GPU_enable_material(mat_nr, attribs); } }
// 使用OpenGL來繪圖 void RenderFrameOpenGL(void) { // `取得視窗大小` int w, h; GutGetWindowSize(w, h); // `清除畫面` glClearColor(0.4f, 0.4f, 0.4f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); Vector4 camera_lookat(0.0f, 0.0f, 0.0f); Matrix4x4 ortho_proj = GutMatrixOrthoRH_OpenGL(20.0f, 20.0f, 0.1f, 100.0f); { // `前視圖` glViewport(0, h/2, w/2, h/2); // view matrix Vector4 camera_pos(0.0f, -20.0f, 0.0f); Vector4 camera_up(0.0f, 0.0f, 1.0f); g_view_matrix = GutMatrixLookAtRH(camera_pos, camera_lookat, camera_up); // projection matrix glMatrixMode(GL_PROJECTION); glLoadMatrixf(&ortho_proj[0][0]); // render objects RenderSolarSystemOpenGL(); } { // `上視圖` glViewport(w/2, h/2, w/2, h/2); // view matrix Vector4 camera_pos(0.0f, 0.0f, 20.0f); Vector4 camera_up(0.0f, 1.0f, 0.0f); g_view_matrix = GutMatrixLookAtRH(camera_pos, camera_lookat, camera_up); // projection matrix glMatrixMode(GL_PROJECTION); glLoadMatrixf(&ortho_proj[0][0]); // render objects RenderSolarSystemOpenGL(); } { // `右視圖` glViewport(0, 0, w/2, h/2); // view matrix Vector4 camera_pos(20.0f, 0.0f, 0.0f); Vector4 camera_up(0.0f, 0.0f, 1.0f); g_view_matrix = GutMatrixLookAtRH(camera_pos, camera_lookat, camera_up); // projection matrix glMatrixMode(GL_PROJECTION); glLoadMatrixf(&ortho_proj[0][0]); // render objects RenderSolarSystemOpenGL(); } { // `使用者視角` glViewport(w/2, 0, w/2, h/2); // object * view matrix Matrix4x4 object_matrix = g_Control.GetObjectMatrix(); Matrix4x4 view_matrix = g_Control.GetViewMatrix(); g_view_matrix = object_matrix * view_matrix; // projection matrix glMatrixMode(GL_PROJECTION); glLoadMatrixf(&g_projection_matrix[0][0]); // render objects RenderSolarSystemOpenGL(); } { // `畫出viewport的邊界` glViewport(0, 0, w, h); glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT); glEnableClientState(GL_VERTEX_ARRAY); // projection matrix glMatrixMode(GL_PROJECTION); glLoadIdentity(); // worldview matrix glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // `畫邊界` glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glVertexPointer(3, GL_FLOAT, sizeof(Vertex_VC), g_Border); glDrawArrays(GL_LINES, 0, 4); glPopClientAttrib(); } // `把背景backbuffer的畫面呈現出來` GutSwapBuffersOpenGL(); }
void Matrix44::load() { glMatrixMode( GL_MODELVIEW ); glLoadMatrixf(m); }
void _glLoadMatrixf( Array<Float> params,int offset ) { glLoadMatrixf( ¶ms[offset] ); }
JNIEXPORT void JNICALL Java_be_niob_apps_ARLoader_ARLoaderRenderer_renderFrame(JNIEnv* env, jobject) { //LOG("Java_be_niob_apps_ARLoader_ARLoader_renderFrame"); // Clear color and depth buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Render video background: QCAR::State state = QCAR::Renderer::getInstance().begin(); #ifdef USE_OPENGL_ES_1_1 // Set GL11 flags: glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); #endif glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); // Did we find any trackables this frame? for(int tIdx = 0; tIdx < state.getNumActiveTrackables(); tIdx++) { // Get the trackable: const QCAR::Trackable* trackable = state.getActiveTrackable(tIdx); QCAR::Matrix44F modelViewMatrix = QCAR::Tool::convertPose2GLMatrix(trackable->getPose()); // Choose the texture based on the target name: int textureIndex = (!strcmp(trackable->getName(), "stones")) ? 0 : 1; const Texture* const thisTexture = textures[textureIndex]; #ifdef USE_OPENGL_ES_1_1 // Load projection matrix: glMatrixMode(GL_PROJECTION); glLoadMatrixf(projectionMatrix.data); // Load model view matrix: glMatrixMode(GL_MODELVIEW); glLoadMatrixf(modelViewMatrix.data); glTranslatef(0.f, 0.f, kObjectScale); glScalef(kObjectScale, kObjectScale, kObjectScale); //mesh->render(); // Draw object: /*glBindTexture(GL_TEXTURE_2D, thisTexture->mTextureID); glTexCoordPointer(2, GL_FLOAT, 0, (const GLvoid*) &teapotTexCoords[0]); glVertexPointer(3, GL_FLOAT, 0, (const GLvoid*) &teapotVertices[0]); glNormalPointer(GL_FLOAT, 0, (const GLvoid*) &teapotNormals[0]); glDrawElements(GL_TRIANGLES, NUM_TEAPOT_OBJECT_INDEX, GL_UNSIGNED_SHORT, (const GLvoid*) &teapotIndices[0]);*/ #else QCAR::Matrix44F modelViewProjection; SampleUtils::translatePoseMatrix(0.0f, 0.0f, kObjectScale, &modelViewMatrix.data[0]); SampleUtils::scalePoseMatrix(kObjectScale, kObjectScale, kObjectScale, &modelViewMatrix.data[0]); SampleUtils::multiplyMatrix(&projectionMatrix.data[0], &modelViewMatrix.data[0] , &modelViewProjection.data[0]); glUseProgram(shaderProgramID); /*glVertexAttribPointer(vertexHandle, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid*) &teapotVertices[0]); glVertexAttribPointer(normalHandle, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid*) &teapotNormals[0]); glVertexAttribPointer(textureCoordHandle, 2, GL_FLOAT, GL_FALSE, 0, (const GLvoid*) &teapotTexCoords[0]); glEnableVertexAttribArray(vertexHandle); glEnableVertexAttribArray(normalHandle); glEnableVertexAttribArray(textureCoordHandle); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, thisTexture->mTextureID); glUniformMatrix4fv(mvpMatrixHandle, 1, GL_FALSE, (GLfloat*)&modelViewProjection.data[0] ); glDrawElements(GL_TRIANGLES, NUM_TEAPOT_OBJECT_INDEX, GL_UNSIGNED_SHORT, (const GLvoid*) &teapotIndices[0]); glVertexAttribPointer(vertexHandle, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid*) &bananaVerts[0]); glVertexAttribPointer(normalHandle, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid*) &bananaNormals[0]); glVertexAttribPointer(textureCoordHandle, 2, GL_FLOAT, GL_FALSE, 0, (const GLvoid*) &bananaTexCoords[0]); glEnableVertexAttribArray(vertexHandle); glEnableVertexAttribArray(normalHandle); glEnableVertexAttribArray(textureCoordHandle); glBindTexture(GL_TEXTURE_2D, mesh->texture); glUniformMatrix4fv(mvpMatrixHandle, 1, GL_FALSE, (GLfloat*)&modelViewProjection.data[0] ); glDrawArrays(GL_TRIANGLES, 0, bananaNumVerts); */ glVertexAttribPointer(vertexHandle, 3, GL_FLOAT, GL_FALSE, 0, mesh->vBuffer); glVertexAttribPointer(normalHandle, 3, GL_FLOAT, GL_FALSE, 0, mesh->nBuffer); glVertexAttribPointer(textureCoordHandle, 2, GL_FLOAT, GL_FALSE, 0, mesh->tBuffer); glEnableVertexAttribArray(vertexHandle); glEnableVertexAttribArray(normalHandle); glEnableVertexAttribArray(textureCoordHandle); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, thisTexture->mTextureID); glUniformMatrix4fv(mvpMatrixHandle, 1, GL_FALSE, (GLfloat*)&modelViewProjection.data[0] ); glDrawArrays(GL_TRIANGLES, 0, mesh->numberOfvertices); SampleUtils::checkGlError("ImageTargets renderFrame"); #endif } glDisable(GL_DEPTH_TEST); #ifdef USE_OPENGL_ES_1_1 glDisable(GL_TEXTURE_2D); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); #else glDisableVertexAttribArray(vertexHandle); glDisableVertexAttribArray(normalHandle); glDisableVertexAttribArray(textureCoordHandle); #endif QCAR::Renderer::getInstance().end(); }
void ApplyShadowMaps (short nStartSeg, fix nEyeOffset, int nWindow) { static float mTexBiasf [] = { 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f}; static float mPlanef [] = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f}; static GLenum nTexCoord [] = {GL_S, GL_T, GL_R, GL_Q}; CFloatMatrix mProjection; CFloatMatrix mModelView; int i; CCamera *cameraP; #if 1 OglActiveTexture (GL_TEXTURE0, 0); glEnable (GL_TEXTURE_2D); glEnable (GL_TEXTURE_GEN_S); glEnable (GL_TEXTURE_GEN_T); glEnable (GL_TEXTURE_GEN_R); glEnable (GL_TEXTURE_GEN_Q); for (i = 0; i < 4; i++) glTexGeni (nTexCoord [i], GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR); for (i = 0; i < 4; i++) glTexGenfv (nTexCoord [i], GL_EYE_PLANE, mPlanef + 4 * i); glGetFloatv (GL_PROJECTION_MATRIX, mProjection.Vec ()); glMatrixMode (GL_TEXTURE); for (i = 0, cameraP = gameData.render.shadows.shadowMaps; i < 1/*gameData.render.shadows.nShadowMaps*/; i++) { glBindTexture (GL_TEXTURE_2D, cameraP->FrameBuffer ().RenderBuffer ()); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE_ARB, GL_COMPARE_R_TO_TEXTURE_ARB); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC_ARB, GL_LEQUAL); glLoadMatrixf (mTexBiasf); glMultMatrixf (mProjection.Vec ()); CFixMatrix::Transpose (mModelView, cameraP->GetObject ()->info.position.mOrient); glMultMatrixf (mModelView.Vec ()); } glMatrixMode (GL_MODELVIEW); #endif RenderMine (nStartSeg, nEyeOffset, nWindow); #if 1 glMatrixMode (GL_TEXTURE); glLoadIdentity (); glMatrixMode (GL_MODELVIEW); glDisable (GL_TEXTURE_GEN_S); glDisable (GL_TEXTURE_GEN_T); glDisable (GL_TEXTURE_GEN_R); glDisable (GL_TEXTURE_GEN_Q); OglActiveTexture (GL_TEXTURE0, 0); glDisable (GL_TEXTURE_2D); #endif DestroyShadowMaps (); }
JNIEXPORT void JNICALL Java_com_qualcomm_QCARSamples_ImageTargets_ImageTargetsRenderer_renderFrame(JNIEnv *, jobject) { //LOG("Java_com_qualcomm_QCARSamples_ImageTargets_GLRenderer_renderFrame"); // Clear color and depth buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Get the state from QCAR and mark the beginning of a rendering section QCAR::State state = QCAR::Renderer::getInstance().begin(); // Explicitly render the Video Background QCAR::Renderer::getInstance().drawVideoBackground(); #ifdef USE_OPENGL_ES_1_1 // Set GL11 flags: glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); #endif glEnable(GL_DEPTH_TEST); // We must detect if background reflection is active and adjust the culling direction. // If the reflection is active, this means the post matrix has been reflected as well, // therefore standard counter clockwise face culling will result in "inside out" models. glEnable(GL_CULL_FACE); glCullFace(GL_BACK); if(QCAR::Renderer::getInstance().getVideoBackgroundConfig().mReflection == QCAR::VIDEO_BACKGROUND_REFLECTION_ON) glFrontFace(GL_CW); //Front camera else glFrontFace(GL_CCW); //Back camera // Did we find any trackables this frame? for(int tIdx = 0; tIdx < state.getNumTrackableResults(); tIdx++) { // Get the trackable: const QCAR::TrackableResult* result = state.getTrackableResult(tIdx); const QCAR::Trackable& trackable = result->getTrackable(); QCAR::Matrix44F modelViewMatrix = QCAR::Tool::convertPose2GLMatrix(result->getPose()); // Choose the texture based on the target name: int textureIndex = newTextureIndex; /** if (strcmp(trackable.getName(), "chips") == 0) { textureIndex = 0; } else if (strcmp(trackable.getName(), "stones") == 0) { textureIndex = 1; } else if (strcmp(trackable.getName(), "EarthTarget1") == 0) { textureIndex = 3; } else { textureIndex = 2; } **/ const Texture* const thisTexture = textures[textureIndex]; #ifdef USE_OPENGL_ES_1_1 // Load projection matrix: glMatrixMode(GL_PROJECTION); glLoadMatrixf(projectionMatrix.data); // Load model view matrix: glMatrixMode(GL_MODELVIEW); glLoadMatrixf(modelViewMatrix.data); glTranslatef(0.f, 0.f, kObjectScale); glScalef(kObjectScale, kObjectScale, kObjectScale); // Draw object: glBindTexture(GL_TEXTURE_2D, thisTexture->mTextureID); //************OLD DEPRACATED TEAPOT INFORMATION************ glTexCoordPointer(2, GL_FLOAT, 0, (const GLvoid*) &teapotTexCoords[0]); glVertexPointer(3, GL_FLOAT, 0, (const GLvoid*) &teapotVertices[0]); glNormalPointer(GL_FLOAT, 0, (const GLvoid*) &teapotNormals[0]); glDrawElements(GL_TRIANGLES, NUM_TEAPOT_OBJECT_INDEX, GL_UNSIGNED_SHORT, (const GLvoid*) &teapotIndices[0]); //************BANANA INFORMATION************ // // set input data to arrays // glVertexPointer(3, GL_FLOAT, 0, bananaVerts); // glNormalPointer(GL_FLOAT, 0, bananaNormals); // glTexCoordPointer(2, GL_FLOAT, 0, bananaTexCoords); // // // draw data // glDrawArrays(GL_TRIANGLES, 0, bananaNumVerts); //**************ATAT INFORMATION*************** // // set input data to arrays // glVertexPointer(3, GL_FLOAT, 0, atatVerts); // glNormalPointer(GL_FLOAT, 0, atatNormals); // glTexCoordPointer(2, GL_FLOAT, 0, atatTexCoords); // // // draw data // glDrawArrays(GL_TRIANGLES, 0, atatNumVerts); #else QCAR::Matrix44F modelViewProjection; SampleUtils::translatePoseMatrix(0.0f, 0.0f, kObjectScale, &modelViewMatrix.data[0]); SampleUtils::scalePoseMatrix(kObjectScale, kObjectScale, kObjectScale, &modelViewMatrix.data[0]); SampleUtils::multiplyMatrix(&projectionMatrix.data[0], &modelViewMatrix.data[0] , &modelViewProjection.data[0]); glUseProgram(shaderProgramID); //************OLD DEPRACATED TEAPOT INFORMATION************ glVertexAttribPointer(vertexHandle, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid*) &teapotVertices[0]); glVertexAttribPointer(normalHandle, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid*) &teapotNormals[0]); glVertexAttribPointer(textureCoordHandle, 2, GL_FLOAT, GL_FALSE, 0, (const GLvoid*) &teapotTexCoords[0]); //************BANANA INFORMATION************ // glVertexAttribPointer(vertexHandle, 3, GL_FLOAT, GL_FALSE, 0, // (const GLvoid*) &atatVerts[0]); // glVertexAttribPointer(normalHandle, 3, GL_FLOAT, GL_FALSE, 0, // (const GLvoid*) &atatNormals[0]); // glVertexAttribPointer(textureCoordHandle, 2, GL_FLOAT, GL_FALSE, 0, // (const GLvoid*) &atatTexCoords[0]); glEnableVertexAttribArray(vertexHandle); glEnableVertexAttribArray(normalHandle); glEnableVertexAttribArray(textureCoordHandle); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, thisTexture->mTextureID); glUniform1i(texSampler2DHandle, 0 /*GL_TEXTURE0*/); glUniformMatrix4fv(mvpMatrixHandle, 1, GL_FALSE, (GLfloat*)&modelViewProjection.data[0] ); //****************DEPRACATED TEAPOT INFORMATION************ glDrawElements(GL_TRIANGLES, NUM_TEAPOT_OBJECT_INDEX, GL_UNSIGNED_SHORT, (const GLvoid*) &teapotIndices[0]); //****************BANANA INFORMATION****************** // glDrawArrays(GL_TRIANGLES, 0, bananaNumVerts); //****************ATAT INFORMATION******************** // glDrawArrays(GL_TRIANGLES, 0, atatNumVerts); SampleUtils::checkGlError("ImageTargets renderFrame"); #endif } glDisable(GL_DEPTH_TEST); #ifdef USE_OPENGL_ES_1_1 glDisable(GL_TEXTURE_2D); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); #else glDisableVertexAttribArray(vertexHandle); glDisableVertexAttribArray(normalHandle); glDisableVertexAttribArray(textureCoordHandle); #endif QCAR::Renderer::getInstance().end(); }
void OpenGLWindow::Clear( ) { Matrix4x4 View, Projection, YRot, Scale; float ViewRaw[ 16 ], ProjectionRaw[ 16 ]; static float Y = 0.0f; m_Camera.SetDimensions( m_Width, m_Height ); m_Camera.SetLookPoint( 0.0f, 0.0f, 0.0f ); m_Camera.SetAspectRatio( ( float ) m_Width / ( float ) m_Height ); m_Camera.CalculateProjectionMatrix( ); m_Camera.CalculateViewMatrix( ); m_Camera.GetProjectionMatrix( Projection ); m_Camera.GetViewMatrix( View ); YRot.CreateRotationY( Y ); Scale.CreateScale( m_ViewScale ); Y += 0.01f; Projection = Projection * Scale; View.CopyToFloatArray( ViewRaw ); Projection.CopyToFloatArray( ProjectionRaw ); glViewport( 0, 0, m_Width, m_Height ); glScissor( 0, 0, m_Width, m_Height ); glClearColor( m_Red, m_Green, m_Blue, 1.0f ); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT ); glMatrixMode( GL_PROJECTION ); glLoadMatrixf( ProjectionRaw ); glMatrixMode( GL_MODELVIEW ); glLoadMatrixf( ViewRaw ); glBegin( GL_LINES ); glColor3f( 0.0f, 1.0f, 0.0f ); glVertex3f( 0.0f, 0.0f, 0.0f ); glVertex3f( 0.0f, 10.0f, 0.0f ); glColor3f( 1.0f, 0.0f, 0.0f ); glVertex3f( 0.0f, 0.0f, 0.0f ); glVertex3f( 10.0f, 0.0f, 0.0f ); glColor3f( 0.0f, 0.0f, 1.0f ); glVertex3f( 0.0f, 0.0f, 0.0f ); glVertex3f( 0.0f, 0.0f, 10.0f ); glColor3f( 1.0f, 1.0f, 1.0f ); // Left glVertex3f( -5.0f, -5.0f, -5.0f ); glVertex3f( -5.0f, -5.0f, 5.0f ); glVertex3f( -5.0f, -5.0f, 5.0f ); glVertex3f( -5.0f, 5.0f, 5.0f ); glVertex3f( -5.0f, 5.0f, 5.0f ); glVertex3f( -5.0f, 5.0f, -5.0f ); glVertex3f( -5.0f, 5.0f, -5.0f ); glVertex3f( -5.0f, -5.0f, -5.0f ); // Top glVertex3f( -5.0f, 5.0f, -5.0f ); glVertex3f( 5.0f, 5.0f, -5.0f ); glVertex3f( 5.0f, 5.0f, 5.0f ); glVertex3f( -5.0f, 5.0f, 5.0f ); // Bottom glVertex3f( -5.0f, -5.0f, -5.0f ); glVertex3f( 5.0f, -5.0f, -5.0f ); glVertex3f( 5.0f, -5.0f, 5.0f ); glVertex3f( -5.0f, -5.0f, 5.0f ); // Right glVertex3f( 5.0f, -5.0f, -5.0f ); glVertex3f( 5.0f, -5.0f, 5.0f ); glVertex3f( 5.0f, -5.0f, 5.0f ); glVertex3f( 5.0f, 5.0f, 5.0f ); glVertex3f( 5.0f, 5.0f, 5.0f ); glVertex3f( 5.0f, 5.0f, -5.0f ); glVertex3f( 5.0f, 5.0f, -5.0f ); glVertex3f( 5.0f, -5.0f, -5.0f ); glEnd( ); }
void large_rocky_body::draw(const simulation_context *sim_context, const drawing_context *draw_context) { lithosphere *litho = get_lithosphere(); if (litho) { vector pos_in_view = get_modelview() * vector::ZERO; gsgl::real_t radius = gsgl::max_val(get_polar_radius(), get_equatorial_radius()); gsgl::real_t dist = pos_in_view.mag(); gsgl::real_t zdist = -pos_in_view.get_z(); assert(zdist > 0); gsgl::real_t far_plane = zdist + (radius * 1.1f); gsgl::real_t near_plane = zdist - (radius * 1.1f); if (near_plane <= 0) near_plane = 1; display::scoped_perspective proj(*draw_context->screen, draw_context->cam->get_field_of_view(), draw_context->screen->get_aspect_ratio(), near_plane, far_plane); display::scoped_color cc(*draw_context->screen, color::WHITE); gsgl::real_t screen_width = utils::pixel_size(dist, radius, draw_context->cam->get_field_of_view(), draw_context->screen->get_height()); if (screen_width < MIN_PIXEL_WIDTH) { display::scoped_state state(*draw_context->screen, draw_context->display_flags(this, drawing_context::RENDER_NO_LIGHTING)); set_flags(get_draw_results(), node::NODE_DREW_POINT); draw_context->screen->draw_point(vector::ZERO, MIN_PIXEL_WIDTH); } else { display::scoped_state state(*draw_context->screen, draw_context->display_flags(this)); draw_context->screen->clear(display::CLEAR_DEPTH); display::scoped_modelview mv(*draw_context->screen, &litho->get_modelview()); litho->draw(sim_context, draw_context); } // draw name draw_name(draw_context); } else { celestial_body::draw(sim_context, draw_context); } #if 0 lithosphere *litho = get_lithosphere(); if (litho) { glPushAttrib(GL_ALL_ATTRIB_BITS); CHECK_GL_ERRORS(); glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS); CHECK_GL_ERRORS(); vector ep = utils::pos_in_eye_space(this); gsgl::real_t radius = gsgl::max_val(get_polar_radius(), get_equatorial_radius()); gsgl::real_t dist = ep.mag(); gsgl::real_t zdist = -ep.get_z(); gsgl::real_t far_plane = zdist + (radius * 1.1f); gsgl::real_t near_plane = zdist - (radius * 1.1f); if (near_plane <= 0) near_plane = 1; glMatrixMode(GL_PROJECTION); CHECK_GL_ERRORS(); glLoadIdentity(); CHECK_GL_ERRORS(); gluPerspective(draw_context->cam->get_field_of_view(), draw_context->screen->get_aspect_ratio(), near_plane, far_plane); CHECK_GL_ERRORS(); // check to see if we're out of range gsgl::real_t screen_width = utils::pixel_size(dist, radius, draw_context->cam->get_field_of_view(), draw_context->screen->get_height()); color::WHITE.bind(); if (screen_width < MIN_PIXEL_WIDTH) { get_draw_results() |= node::NODE_DREW_POINT; draw_point(MIN_PIXEL_WIDTH); } else { glClearDepth(1); CHECK_GL_ERRORS(); glClear(GL_DEPTH_BUFFER_BIT); CHECK_GL_ERRORS(); glEnable(GL_DEPTH_TEST); CHECK_GL_ERRORS(); glEnable(GL_CULL_FACE); CHECK_GL_ERRORS(); glPolygonMode(GL_FRONT_AND_BACK, (draw_context->render_flags & drawing_context::RENDER_WIREFRAME) ? GL_LINE : GL_FILL); CHECK_GL_ERRORS(); // set up lighting if (!(draw_context->render_flags & drawing_context::RENDER_NO_LIGHTING) && !(get_draw_flags() & NODE_DRAW_UNLIT)) { glEnable(GL_LIGHTING); CHECK_GL_ERRORS(); glLightModelf(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE); CHECK_GL_ERRORS(); glLightModelf(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE); CHECK_GL_ERRORS(); //glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR); glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, color::WHITE.get_val()); CHECK_GL_ERRORS(); glMaterialfv(GL_FRONT, GL_SPECULAR, color::BLACK.get_val()); CHECK_GL_ERRORS(); glMaterialfv(GL_FRONT, GL_EMISSION, color::BLACK.get_val()); CHECK_GL_ERRORS(); glMaterialf(GL_FRONT, GL_SHININESS, 8); CHECK_GL_ERRORS(); } // set up texturing if (!(draw_context->render_flags & drawing_context::RENDER_NO_TEXTURES)) { glEnable(GL_TEXTURE_2D); } // draw lithosphere glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadMatrixf(litho->get_modelview().ptr()); litho->draw(sim_context, draw_context); glMatrixMode(GL_MODELVIEW); glPopMatrix(); } glPopClientAttrib(); CHECK_GL_ERRORS(); glPopAttrib(); CHECK_GL_ERRORS(); draw_name(draw_context, 1, far_plane); } else { celestial_body::draw(sim_context, draw_context); } #endif } // large_rocky_body::draw()
static Bool clonePaintOutput(CompScreen * s, const ScreenPaintAttrib * sAttrib, const CompTransform * transform, Region region, CompOutput * outputPtr, unsigned int mask) { Bool status; int i, dst, output = 0; CLONE_SCREEN(s); dst = output = (outputPtr->id != ~0) ? outputPtr->id : 0; if (!cs->grab || cs->grabbedOutput != output) { for (i = 0; i < cs->nClone; i++) { if (cs->clone[i].dst == output) { region = cs->clone[i].region; dst = cs->clone[i].src; if (s->outputDev[dst].width != s->outputDev[output].width || s->outputDev[dst].height != s->outputDev[output].height) cs->transformed = TRUE; else cs->transformed = FALSE; break; } } } UNWRAP(cs, s, paintOutput); if (outputPtr->id != ~0) status = (*s->paintOutput) (s, sAttrib, transform, region, &s->outputDev[dst], mask); else status = (*s->paintOutput) (s, sAttrib, transform, region, outputPtr, mask); WRAP(cs, s, paintOutput, clonePaintOutput); if (cs->grab) { CompTransform sTransform = *transform; CompWindow *w; GLenum filter; float zoom1, zoom2x, zoom2y, x1, y1, x2, y2; float zoomX, zoomY; int dx, dy; zoom1 = 160.0f / s->outputDev[cs->src].height; x1 = cs->x - (s->outputDev[cs->src].region.extents.x1 * zoom1); y1 = cs->y - (s->outputDev[cs->src].region.extents.y1 * zoom1); x1 -= (s->outputDev[cs->src].width * zoom1) / 2; y1 -= (s->outputDev[cs->src].height * zoom1) / 2; if (cs->grabIndex) { x2 = s->outputDev[cs->grabbedOutput].region.extents.x1 - s->outputDev[cs->src].region.extents.x1; y2 = s->outputDev[cs->grabbedOutput].region.extents.y1 - s->outputDev[cs->src].region.extents.y1; zoom2x = (float)s->outputDev[cs->grabbedOutput].width / s->outputDev[cs->src].width; zoom2y = (float)s->outputDev[cs->grabbedOutput].height / s->outputDev[cs->src].height; } else { x2 = s->outputDev[cs->dst].region.extents.x1 - s->outputDev[cs->src].region.extents.x1; y2 = s->outputDev[cs->dst].region.extents.y1 - s->outputDev[cs->src].region.extents.y1; zoom2x = (float)s->outputDev[cs->dst].width / s->outputDev[cs->src].width; zoom2y = (float)s->outputDev[cs->dst].height / s->outputDev[cs->src].height; } /* XXX: hmm.. why do I need this.. */ if (x2 < 0.0f) x2 *= zoom2x; if (y2 < 0.0f) y2 *= zoom2y; dx = x1 * (1.0f - cs->offset) + x2 * cs->offset; dy = y1 * (1.0f - cs->offset) + y2 * cs->offset; zoomX = zoom1 * (1.0f - cs->offset) + zoom2x * cs->offset; zoomY = zoom1 * (1.0f - cs->offset) + zoom2y * cs->offset; matrixTranslate(&sTransform, -0.5f, -0.5f, -DEFAULT_Z_CAMERA); matrixScale(&sTransform, 1.0f / s->outputDev[output].width, -1.0f / s->outputDev[output].height, 1.0f); matrixTranslate(&sTransform, dx - s->outputDev[output].region.extents.x1, dy - s->outputDev[output].region.extents.y2, 0.0f); matrixScale(&sTransform, zoomX, zoomY, 1.0f); glPushMatrix(); glLoadMatrixf(sTransform.m); filter = s->display->textureFilter; if (cs->offset == 0.0f) s->display->textureFilter = GL_LINEAR_MIPMAP_LINEAR; for (w = s->windows; w; w = w->next) { if (w->destroyed) continue; if (!w->shaded) { if (w->attrib.map_state != IsViewable || !w->damaged) continue; } (*s->paintWindow) (w, &w->paint, &sTransform, &s->outputDev[cs->src].region, PAINT_WINDOW_ON_TRANSFORMED_SCREEN_MASK); } s->display->textureFilter = filter; glPopMatrix(); } return status; }
void CAdvTreeDrawer::Draw(float treeDistance,bool drawReflection) { int activeFarTex=camera->forward.z<0 ? treeGen->farTex[0] : treeGen->farTex[1]; bool drawDetailed=true; if(treeDistance<4) drawDetailed=false; if(drawReflection) drawDetailed=false; CBaseGroundDrawer *gd = readmap->GetGroundDrawer (); glEnable(GL_ALPHA_TEST); if(shadowHandler->drawShadows && !gd->DrawExtraTex()){ glBindProgramARB( GL_VERTEX_PROGRAM_ARB, treeGen->treeFarVP ); glEnable(GL_VERTEX_PROGRAM_ARB); glBindTexture(GL_TEXTURE_2D,shadowHandler->shadowTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE_ARB, GL_COMPARE_R_TO_TEXTURE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC_ARB, GL_LEQUAL); glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE_ARB, GL_ALPHA); if(shadowHandler->useFPShadows){ glBindProgramARB( GL_FRAGMENT_PROGRAM_ARB, treeGen->treeFPShadow ); glEnable( GL_FRAGMENT_PROGRAM_ARB ); glProgramEnvParameter4fARB(GL_FRAGMENT_PROGRAM_ARB,10, mapInfo->light.groundAmbientColor.x,mapInfo->light.groundAmbientColor.y,mapInfo->light.groundAmbientColor.z,1); glProgramEnvParameter4fARB(GL_FRAGMENT_PROGRAM_ARB,11, 0,0,0,1-mapInfo->light.groundShadowDensity*0.5f); glActiveTextureARB(GL_TEXTURE1_ARB); glBindTexture(GL_TEXTURE_2D, activeFarTex); } else { glEnable(GL_TEXTURE_2D); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FAIL_VALUE_ARB, 1-mapInfo->light.groundShadowDensity*0.5f); float texConstant[]={mapInfo->light.groundAmbientColor.x,mapInfo->light.groundAmbientColor.y,mapInfo->light.groundAmbientColor.z,0.0f}; glTexEnvfv(GL_TEXTURE_ENV,GL_TEXTURE_ENV_COLOR,texConstant); glTexEnvi(GL_TEXTURE_ENV,GL_SOURCE0_RGB_ARB,GL_PREVIOUS_ARB); glTexEnvi(GL_TEXTURE_ENV,GL_SOURCE1_RGB_ARB,GL_CONSTANT); glTexEnvi(GL_TEXTURE_ENV,GL_SOURCE2_RGB_ARB,GL_TEXTURE); glTexEnvi(GL_TEXTURE_ENV,GL_OPERAND2_RGB_ARB,GL_SRC_ALPHA); glTexEnvi(GL_TEXTURE_ENV,GL_COMBINE_RGB_ARB,GL_INTERPOLATE_ARB); glTexEnvi(GL_TEXTURE_ENV,GL_SOURCE0_ALPHA_ARB,GL_PREVIOUS_ARB); glTexEnvi(GL_TEXTURE_ENV,GL_SOURCE1_ALPHA_ARB,GL_CONSTANT); glTexEnvi(GL_TEXTURE_ENV,GL_COMBINE_ALPHA_ARB,GL_ADD); glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_COMBINE_ARB); glActiveTextureARB(GL_TEXTURE1_ARB); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, activeFarTex); } glActiveTextureARB(GL_TEXTURE0_ARB); glMatrixMode(GL_MATRIX0_ARB); glLoadMatrixf(shadowHandler->shadowMatrix.m); glMatrixMode(GL_MODELVIEW); } else { glBindTexture(GL_TEXTURE_2D, activeFarTex); } glEnable(GL_TEXTURE_2D); int cx=(int)(camera->pos.x/(SQUARE_SIZE*TREE_SQUARE_SIZE)); int cy=(int)(camera->pos.z/(SQUARE_SIZE*TREE_SQUARE_SIZE)); CAdvTreeSquareDrawer drawer; drawer.td = this; drawer.cx = cx; drawer.cy = cy; drawer.treeDistance = treeDistance; drawer.drawDetailed = drawDetailed; GML_STDMUTEX_LOCK(tree); // Draw // draw far away trees using the map dependent grid visibility oldTreeDistance=treeDistance; readmap->GridVisibility (camera, TREE_SQUARE_SIZE, treeDistance*2*SQUARE_SIZE*TREE_SQUARE_SIZE, &drawer); if(drawDetailed){ int xstart=std::max(0,cx-2); int xend=std::min(gs->mapx/TREE_SQUARE_SIZE-1,cx+2); int ystart=std::max(0,cy-2); int yend=std::min(gs->mapy/TREE_SQUARE_SIZE-1,cy+2); if(shadowHandler->drawShadows && !gd->DrawExtraTex()){ glBindProgramARB( GL_VERTEX_PROGRAM_ARB, treeGen->treeVP ); glActiveTextureARB(GL_TEXTURE1_ARB); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, treeGen->barkTex); glActiveTextureARB(GL_TEXTURE0_ARB); } else { glBindTexture(GL_TEXTURE_2D, treeGen->barkTex); glBindProgramARB( GL_VERTEX_PROGRAM_ARB, treeGen->treeNSVP ); glProgramEnvParameter4fARB(GL_VERTEX_PROGRAM_ARB,15, 1.0f/(gs->pwr2mapx*SQUARE_SIZE),1.0f/(gs->pwr2mapy*SQUARE_SIZE),1.0f/(gs->pwr2mapx*SQUARE_SIZE),1); } glEnable( GL_VERTEX_PROGRAM_ARB ); glProgramEnvParameter4fARB(GL_VERTEX_PROGRAM_ARB,13, camera->right.x,camera->right.y,camera->right.z,0); glProgramEnvParameter4fARB(GL_VERTEX_PROGRAM_ARB,9, camera->up.x,camera->up.y,camera->up.z,0); glProgramEnvParameter4fARB(GL_VERTEX_PROGRAM_ARB,11, mapInfo->light.groundSunColor.x,mapInfo->light.groundSunColor.y,mapInfo->light.groundSunColor.z,0.85f); glProgramEnvParameter4fARB(GL_VERTEX_PROGRAM_ARB,14, mapInfo->light.groundAmbientColor.x,mapInfo->light.groundAmbientColor.y,mapInfo->light.groundAmbientColor.z,0.85f); glProgramEnvParameter4fARB(GL_VERTEX_PROGRAM_ARB,12, 0,0,0,0.20f*(1.0f/MAX_TREE_HEIGHT)); //w=alpha/height modifier glAlphaFunc(GL_GREATER,0.5f); glDisable(GL_BLEND); glColor4f(1,1,1,1); va=GetVertexArray(); va->Initialize(); struct FadeTree{ float3 pos; float relDist; float deltaY; int type; }; static FadeTree fadeTrees[3000]; FadeTree *pFT=fadeTrees; for(TreeSquareStruct* pTSS=trees+ystart*treesX; pTSS<=trees+yend*treesX; pTSS+=treesX) { for(TreeSquareStruct* tss=pTSS+xstart; tss<=pTSS+xend; ++tss) { tss->lastSeen=gs->frameNum; va->EnlargeArrays(12*tss->trees.size(),0,VA_SIZE_T); //!alloc room for all tree vertexes for(std::map<int,TreeStruct>::iterator ti=tss->trees.begin();ti!=tss->trees.end();++ti){ TreeStruct* ts=&ti->second; float3 pos(ts->pos); int type=ts->type; float dy; unsigned int displist; if(type<8){ dy=0.5f; displist=treeGen->pineDL+type; } else { type-=8; dy=0; displist=treeGen->leafDL+type; } if(camera->InView(pos+float3(0,MAX_TREE_HEIGHT/2,0),MAX_TREE_HEIGHT/2)){ float camDist=(pos-camera->pos).SqLength(); if(camDist<SQUARE_SIZE*SQUARE_SIZE*110*110){ //draw detailed tree glProgramEnvParameter4fARB(GL_VERTEX_PROGRAM_ARB,10,pos.x,pos.y,pos.z,0); glCallList(displist); } else if(camDist<SQUARE_SIZE*SQUARE_SIZE*125*125){ //draw fading tree float relDist=(pos.distance(camera->pos)-SQUARE_SIZE*110)/(SQUARE_SIZE*15); glAlphaFunc(GL_GREATER,0.8f+relDist*0.2f); glProgramEnvParameter4fARB(GL_VERTEX_PROGRAM_ARB,10,pos.x,pos.y,pos.z,0); glCallList(displist); glAlphaFunc(GL_GREATER,0.5f); pFT->pos=pos; pFT->deltaY=dy; pFT->type=type; pFT->relDist=relDist; ++pFT; } else { //draw undetailed tree DrawTreeVertex(pos, type*0.125f, dy, false); } } } } } //draw trees that has been marked as falling glProgramEnvParameter4fARB(GL_VERTEX_PROGRAM_ARB,10,0,0,0,0); glProgramEnvParameter4fARB(GL_VERTEX_PROGRAM_ARB,13, camera->right.x,camera->right.y,camera->right.z,0); glProgramEnvParameter4fARB(GL_VERTEX_PROGRAM_ARB,9, camera->up.x,camera->up.y,camera->up.z,0); for(std::list<FallingTree>::iterator fti=fallingTrees.begin(); fti!=fallingTrees.end(); ++fti){ float3 pos=fti->pos-UpVector*(fti->fallPos*20); if(camera->InView(pos+float3(0,MAX_TREE_HEIGHT/2,0),MAX_TREE_HEIGHT/2)){ float ang=fti->fallPos*PI; float3 up(fti->dir.x*sin(ang),cos(ang),fti->dir.z*sin(ang)); float3 z(up.cross(float3(-1,0,0))); z.ANormalize(); float3 x(up.cross(z)); CMatrix44f transMatrix(pos,x,up,z); glPushMatrix(); glMultMatrixf(&transMatrix[0]); int type=fti->type; int displist; if(type<8){ displist=treeGen->pineDL+type; } else { type-=8; displist=treeGen->leafDL+type; } glCallList(displist); glPopMatrix(); } } glDisable( GL_VERTEX_PROGRAM_ARB ); if(shadowHandler->drawShadows && !gd->DrawExtraTex()){ glBindProgramARB( GL_VERTEX_PROGRAM_ARB, treeGen->treeFarVP ); glEnable(GL_VERTEX_PROGRAM_ARB); glActiveTextureARB(GL_TEXTURE1_ARB); glBindTexture(GL_TEXTURE_2D, activeFarTex); glActiveTextureARB(GL_TEXTURE0_ARB); } else { glBindTexture(GL_TEXTURE_2D, activeFarTex); } va->DrawArrayT(GL_QUADS); for(FadeTree *pFTree=fadeTrees; pFTree<pFT; ++pFTree) { //faded close trees va=GetVertexArray(); va->Initialize(); va->CheckInitSize(12*VA_SIZE_T); DrawTreeVertex(pFTree->pos, pFTree->type*0.125f, pFTree->deltaY, false); glAlphaFunc(GL_GREATER,1-pFTree->relDist*0.5f); va->DrawArrayT(GL_QUADS); } } if(shadowHandler->drawShadows && !gd->DrawExtraTex()){ glDisable( GL_VERTEX_PROGRAM_ARB ); if(shadowHandler->useFPShadows){ glDisable(GL_FRAGMENT_PROGRAM_ARB); } glActiveTextureARB(GL_TEXTURE1_ARB); glDisable(GL_TEXTURE_2D); glActiveTextureARB(GL_TEXTURE0_ARB); glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE_ARB, GL_NONE); glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE_ARB, GL_LUMINANCE); } glDisable(GL_ALPHA_TEST); //clean out squares from memory that are no longer visible int startClean=lastListClean*20%(nTrees); lastListClean=gs->frameNum; int endClean=gs->frameNum*20%(nTrees); if(startClean>endClean){ for(TreeSquareStruct *pTSS=trees+startClean; pTSS<trees+nTrees; ++pTSS) { if(pTSS->lastSeen<gs->frameNum-50 && pTSS->displist){ glDeleteLists(pTSS->displist,1); pTSS->displist=0; } if(pTSS->lastSeenFar<gs->frameNum-50 && pTSS->farDisplist){ glDeleteLists(pTSS->farDisplist,1); pTSS->farDisplist=0; } } for(TreeSquareStruct *pTSS=trees; pTSS<trees+endClean; ++pTSS) { if(pTSS->lastSeen<gs->frameNum-50 && pTSS->displist){ glDeleteLists(pTSS->displist,1); pTSS->displist=0; } if(pTSS->lastSeenFar<gs->frameNum-50 && pTSS->farDisplist){ glDeleteLists(pTSS->farDisplist,1); pTSS->farDisplist=0; } } } else { for(TreeSquareStruct *pTSS=trees+startClean; pTSS<trees+endClean; ++pTSS) { if(pTSS->lastSeen<gs->frameNum-50 && pTSS->displist){ glDeleteLists(pTSS->displist,1); pTSS->displist=0; } if(pTSS->lastSeenFar<gs->frameNum-50 && pTSS->farDisplist){ glDeleteLists(pTSS->farDisplist,1); pTSS->farDisplist=0; } } } }
int main(int argc, char *argv[]) { SDL_Surface *screen; if ( SDL_Init(SDL_INIT_VIDEO) != 0 ) { printf("Unable to initialize SDL: %s\n", SDL_GetError()); return 1; } SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); screen = SDL_SetVideoMode( 640, 480, 24, SDL_OPENGL ); if ( !screen ) { printf("Unable to set video mode: %s\n", SDL_GetError()); return 1; } glClearColor( 0, 0, 0, 0 ); glClear( GL_COLOR_BUFFER_BIT ); glGenVertexArrays_ = (PFNGLGENVERTEXARRAYSPROC) SDL_GL_GetProcAddress("glGenVertexArrays"); assert(glGenVertexArrays_); glBindVertexArray_ = (PFNGLBINDVERTEXARRAYPROC) SDL_GL_GetProcAddress("glBindVertexArray"); assert(glBindVertexArray_); glDeleteVertexArrays_ = (PFNGLDELETEVERTEXARRAYSPROC) SDL_GL_GetProcAddress("glDeleteVertexArrays"); assert(glDeleteVertexArrays_); glEnableClientState(GL_TEXTURE_COORD_ARRAY); // enabling it *before* the vao does nothing, the vao should wipe it out! // Generate a VAO GLuint vao; glGenVertexArrays_(1, &vao); glBindVertexArray_(vao); // Create a texture GLuint texture; glGenTextures( 1, &texture ); glBindTexture( GL_TEXTURE_2D, texture ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); GLubyte textureData[16*16*4]; for (int x = 0; x < 16; x++) { for (int y = 0; y < 16; y++) { *((int*)&textureData[(x*16 + y) * 4]) = x*16 + ((y*16) << 8); } } glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, 16, 16, 0, GL_RGBA, GL_UNSIGNED_BYTE, textureData ); // Create a second texture GLuint texture2; glGenTextures( 1, &texture2 ); glBindTexture( GL_TEXTURE_2D, texture2 ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); GLubyte texture2Data[] = { 0xff, 0, 0, 0xff, 0, 0xff, 0, 0xaa, 0, 0, 0xff, 0x55, 0x80, 0x90, 0x70, 0 }; glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, 2, 2, 0, GL_RGBA, GL_UNSIGNED_BYTE, texture2Data ); // BEGIN #if USE_GLEW glewInit(); #endif glMatrixMode(GL_PROJECTION); glLoadIdentity(); // original: glFrustum(-0.6435469817188064, 0.6435469817188064 ,-0.48266022190470925, 0.48266022190470925 ,0.5400000214576721, 2048); //glFrustum(-0.6435469817188064, 0.1435469817188064 ,-0.48266022190470925, 0.88266022190470925 ,0.5400000214576721, 2048); GLfloat pm[] = { 1.372136116027832, 0, 0, 0, 0, 0.7910231351852417, 0, 0, -0.6352481842041016, 0.29297152161598206, -1.0005275011062622, -1, 0, 0, -1.080284833908081, 0 }; glLoadMatrixf(pm); glMatrixMode(GL_MODELVIEW); GLfloat matrixData[] = { -1, 0, 0, 0, 0, 0,-1, 0, 0, 1, 0, 0, 0, 0, 0, 1 }; glLoadMatrixf(matrixData); //glTranslated(-512,-512,-527); // XXX this should be uncommented, but if it is then nothing is shown // glEnable(GL_CULL_FACE); // glEnable(GL_DEPTH_TEST); //glClear(GL_DEPTH_BUFFER_BIT); // glEnableClientState(GL_NORMAL_ARRAY); // glEnableClientState(GL_COLOR_ARRAY); glActiveTexture(GL_TEXTURE0); glEnableClientState(GL_VERTEX_ARRAY); GLuint arrayBuffer, elementBuffer; glGenBuffers(1, &arrayBuffer); glGenBuffers(1, &elementBuffer); GLubyte arrayData[] = { /* [0, 0, 0, 67] ==> 128 float [0, 0, 128, 67] ==> 256 float [0, 0, 0, 68] ==> 512 float [0, 0, 128, 68] ==> 1024 float [vertex x ] [vertex y ] [vertex z ] [nr] [texture u ] [texture v ] [lm u ] [lm v ] [color r,g,b,a ] */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, // 0 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 67, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, // 1 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 67, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 2 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 3 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 67, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, // 4 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 128, 67, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, // 5 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 128, 67, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 6 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 67, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 7 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 8 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 67, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 9 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 67, 0, 0, 128, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 10 0, 0, 0, 0, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 11 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 67, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 12 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 128, 67, 0, 0, 0, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 13 0, 0, 128, 68, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 128, 67, 0, 0, 128, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 14 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 67, 0, 0, 128, 67, 0, 0, 0, 0, 128, 128, 128, 128, // 15 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 128, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 128, 68, 0, 0, 128, 68, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128 }; assert(sizeof(arrayData) == 1408); glBindBuffer(GL_ARRAY_BUFFER, arrayBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(arrayData), arrayData, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); GLushort elementData[] = { 1, 2, 0, 2, 3, 0, 5, 6, 4, 6, 7, 4, 9, 10, 8, 10, 11, 8, 13, 14, 12, 14, 15, 12 }; assert(sizeof(elementData) == 48); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementBuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elementData), elementData, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, arrayBuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementBuffer); // sauer vertex data is apparently 0-12: V3F, 12: N1B, 16-24: T2F, 24-28: T2S, 28-32: C4B glVertexPointer(3, GL_FLOAT, 32, (void*)0); // all these apply to the ARRAY_BUFFER that is bound glTexCoordPointer(2, GL_FLOAT, 32, (void*)16); // glClientActiveTexture(GL_TEXTURE1); // XXX seems to be ignored in native build // glTexCoordPointer(2, GL_SHORT, 32, (void*)24); // glClientActiveTexture(GL_TEXTURE0); // likely not needed, it is a cleanup // glNormalPointer(GL_BYTE, 32, (void*)12); // glColorPointer(4, GL_UNSIGNED_BYTE, 32, (void*)28); glBindTexture(GL_TEXTURE_2D, texture); // diffuse? glActiveTexture(GL_TEXTURE0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture2); // lightmap? glActiveTexture(GL_TEXTURE0); GLint ok; const char *vertexShader = "uniform mat4 u_modelView;\n" "uniform mat4 u_projection;\n" "varying vec4 v_texCoord0;\n" "void main(void)\n" "{\n" // (gl_ProjectionMatrix * gl_ModelViewMatrix * gl_Vertex) // (u_projection * u_modelView * a_position) " gl_Position = (u_projection * u_modelView * gl_Vertex) + vec4(200, 0, 0, 0);\n" " v_texCoord0.xy = gl_MultiTexCoord0.xy/20.0;\n" // added /100 here "}\n"; const char *fragmentShader = "uniform sampler2D diffusemap;\n" "varying vec4 v_texCoord0;\n" "void main(void)\n" "{\n" " vec4 diffuse = texture2D(diffusemap, v_texCoord0.xy);\n" " gl_FragColor = diffuse;\n" "}\n"; GLuint vs = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vs, 1, &vertexShader, NULL); glCompileShader(vs); glGetShaderiv(vs, GL_COMPILE_STATUS, &ok); if (!ok) { printf("Shader compilation error with vertex\n"); GLint infoLen = 0; glGetShaderiv (vs, GL_INFO_LOG_LENGTH, &infoLen); if (infoLen > 1) { char* infoLog = (char *)malloc(sizeof(char) * infoLen+1); glGetShaderInfoLog(vs, infoLen, NULL, infoLog); printf("Error compiling shader:\n%s\n", infoLog); } } GLuint fs = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fs, 1, &fragmentShader, NULL); glCompileShader(fs); glGetShaderiv(fs, GL_COMPILE_STATUS, &ok); if (!ok) { printf("Shader compilation error with fragment\n"); GLint infoLen = 0; glGetShaderiv (vs, GL_INFO_LOG_LENGTH, &infoLen); if (infoLen > 1) { char* infoLog = (char *)malloc(sizeof(char) * infoLen+1); glGetShaderInfoLog(vs, infoLen, NULL, infoLog); printf("Error compiling shader:\n%s\n", infoLog); } } GLuint program = glCreateProgram(); glAttachShader(program, vs); glAttachShader(program, fs); glLinkProgram(program); glGetProgramiv(program, GL_LINK_STATUS, &ok); assert(ok); glUseProgram(program); //GLint lightmapLocation = glGetUniformLocation(program, "lightmap"); //assert(lightmapLocation >= 0); //glUniform1i(lightmapLocation, 1); // sampler2D? Is it the texture unit? GLint diffusemapLocation = glGetUniformLocation(program, "diffusemap"); assert(diffusemapLocation >= 0); glUniform1i(diffusemapLocation, 0); //GLint texgenscrollLocation = glGetUniformLocation(program, "texgenscroll"); //assert(texgenscrollLocation >= 0); //GLint colorparamsLocation = glGetUniformLocation(program, "colorparams"); //assert(colorparamsLocation >= 0); //GLfloat texgenscrollData[] = { 0, 0, 0, 0 }; //glUniform4fv(texgenscrollLocation, 1, texgenscrollData); //GLfloat colorparamsData[] = { 2, 2, 2, 1 }; //glUniform4fv(colorparamsLocation, 1, colorparamsData); { GLfloat data[16]; glGetFloatv(GL_MODELVIEW_MATRIX, data); printf("Modelview: "); for (int i = 0; i < 16; i++) printf("%.3f, ", data[i]); printf("\n"); //memset(data, 0, 16*4); GLint modelViewLocation = glGetUniformLocation(program, "u_modelView"); assert(modelViewLocation >= 0); glUniformMatrix4fv(modelViewLocation, 1, GL_FALSE, data); } { GLfloat data[16]; glGetFloatv(GL_PROJECTION_MATRIX, data); printf("Projection: "); for (int i = 0; i < 16; i++) printf("%.3f, ", data[i]); printf("\n"); //memset(data, 0, 16*4); GLint projectionLocation = glGetUniformLocation(program, "u_projection"); assert(projectionLocation >= 0); glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, data); } /* glBindAttribLocation(program, 0, "a_position"); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 32, (void*)0); glEnableVertexAttribArray(0); glBindAttribLocation(program, 1, "v_texCoord0"); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 32, (void*)16); glEnableVertexAttribArray(1); */ // stop recording in the VAO glBindVertexArray_(0); // unbind all the stuff the VAO would save for us, so this is a valid test glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); // draw with VAO glBindVertexArray_(vao); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)12); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*) 0); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)24); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)36); // END SDL_GL_SwapBuffers(); #if !EMSCRIPTEN SDL_Delay(1500); #endif // SDL_Quit(); return 0; }
int main( void ) { crap::audiodevice audio_device; /* openalcode */ //setup window crap::window_setup win_setup; win_setup.title = "Funny Window"; win_setup.width = 1024; win_setup.height = 768; win_setup.multisampling_count = 8; win_setup.opengl_version = 3.3f; win_setup.opengl_profile = crap::compat; //create window crap::window window( win_setup ); window.open(); //get keyboard and mouse crap::keyboard keyboard; crap::mouse mouse; // temporary crap::opengl::enable(crap::opengl::depth_test); crap::opengl::setDepthComparison(crap::opengl::less); crap::opengl::enable(crap::opengl::cull_face); //camera setup camera cam; cam.setPosition( glm::vec3( 0.0f, 0.0f, 5.0f ) ); mouse_pos = mouse.position(); //create contentmanager content_manager cm; cm.init( "spg.ini" ); //create vertex array crap::vertex_array vert_array; vert_array.bind(); //test: load vbo onto GPU vbo cube_vbo( "cube", &cm, vbo::static_draw ); vbo ape_vbo("ape", &cm, vbo::static_draw ); vbo cube_big_vbo( "cube", &cm, vbo::static_draw ); //vbo people_vbo("people", &cm, vbo::static_draw ); ////////////////////////// // Read our .obj file std::vector<glm::vec3> vertices; std::vector<glm::vec2> uvs; std::vector<glm::vec3> normals; bool res = loadOBJ("../../../data/geometry/dupercube.obj", vertices, uvs, normals); std::vector<glm::vec3> tangents; std::vector<glm::vec3> bitangents; computeTangentBasis( vertices, uvs, normals, // input tangents, bitangents // output ); std::vector<unsigned short> indices; std::vector<glm::vec3> indexed_vertices; std::vector<glm::vec2> indexed_uvs; std::vector<glm::vec3> indexed_normals; std::vector<glm::vec3> indexed_tangents; std::vector<glm::vec3> indexed_bitangents; indexVBO_TBN( vertices, uvs, normals, tangents, bitangents, indices, indexed_vertices, indexed_uvs, indexed_normals, indexed_tangents, indexed_bitangents ); GLuint vertexbuffer; glGenBuffers(1, &vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, indexed_vertices.size() * sizeof(glm::vec3), &indexed_vertices[0], GL_STATIC_DRAW); GLuint uvbuffer; glGenBuffers(1, &uvbuffer); glBindBuffer(GL_ARRAY_BUFFER, uvbuffer); glBufferData(GL_ARRAY_BUFFER, indexed_uvs.size() * sizeof(glm::vec2), &indexed_uvs[0], GL_STATIC_DRAW); GLuint normalbuffer; glGenBuffers(1, &normalbuffer); glBindBuffer(GL_ARRAY_BUFFER, normalbuffer); glBufferData(GL_ARRAY_BUFFER, indexed_normals.size() * sizeof(glm::vec3), &indexed_normals[0], GL_STATIC_DRAW); GLuint tangentbuffer; glGenBuffers(1, &tangentbuffer); glBindBuffer(GL_ARRAY_BUFFER, tangentbuffer); glBufferData(GL_ARRAY_BUFFER, indexed_tangents.size() * sizeof(glm::vec3), &indexed_tangents[0], GL_STATIC_DRAW); GLuint bitangentbuffer; glGenBuffers(1, &bitangentbuffer); glBindBuffer(GL_ARRAY_BUFFER, bitangentbuffer); glBufferData(GL_ARRAY_BUFFER, indexed_bitangents.size() * sizeof(glm::vec3), &indexed_bitangents[0], GL_STATIC_DRAW); // Generate a buffer for the indices as well GLuint elementbuffer; glGenBuffers(1, &elementbuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned short), &indices[0], GL_STATIC_DRAW); ///////////////////////// geometry_content ig; cm.create_content( "cube" , &ig, type_name::geometry ); //test: load texture onto GPU tbo diffuse_tbo( "stone_diff", &cm, tbo::tga ); tbo normal_tbo( "stone_norm", &cm, tbo::tga ); tbo height_tbo( "stone_height", &cm, tbo::tga ); //shadow stuff crap::frame_buffer frame_buffer; frame_buffer.bind(); tbo depthmap( "", &cm, tbo::depth ); frame_buffer.unbind(); //shadow stuff crap::quad_buffer quad_buffer; //test: load linked shader progam onto GPU shader_manager sm(&cm); sm.add("epr_vert", "epr_frag"); sm.add("shadow_vert", "shadow_frag"); //get stuff from shader program //shadow shader sm.set_current("shadow_vert", "shadow_frag"); crap::uniform DepthBiasMVPID = sm.current()->uniform_location("depthMVP"); //vertex shader sm.set_current("epr_vert", "epr_frag"); crap::uniform WorldMatrixID = sm.current()->uniform_location("world_matrix4x4"); crap::uniform ViewMatrixID = sm.current()->uniform_location("view_matrix4x4"); crap::uniform ModelMatrixID = sm.current()->uniform_location("model_matrix4x4"); crap::uniform ModelView3x3MatrixID = sm.current()->uniform_location("model_view_matrix3x3"); //fragment shader crap::uniform DiffuseTextureID = sm.current()->uniform_location("diffuse_texture"); crap::uniform NormalTextureID = sm.current()->uniform_location("normal_texture"); crap::uniform HeightTextureID = sm.current()->uniform_location("height_texture"); crap::uniform LightAmbientPowerID = sm.current()->uniform_location("ambient_power"); crap::uniform LightPowerArrayID = sm.current()->uniform_location("light_power"); crap::uniform LightSpecularTypeArrayID = sm.current()->uniform_location("light_specular_type"); crap::uniform LightSpecularLobeArrayID = sm.current()->uniform_location("light_specular_lobe"); crap::uniform LightColorArrayID = sm.current()->uniform_location("light_color"); crap::uniform LightSelfShadowingOnID = sm.current()->uniform_location("selfshadowing_on"); crap::uniform DisplacementOnID = sm.current()->uniform_location("displacement_on"); crap::uniform DisplacementStepsID = sm.current()->uniform_location("displacement_steps"); crap::uniform DisplacementRefinementStepsID = sm.current()->uniform_location("displacement_refinement_steps"); crap::uniform DisplacementUVFactorID = sm.current()->uniform_location("displacement_uv_factor"); //both shaders crap::uniform LightPositionArrayID = sm.current()->uniform_location("light_position"); crap::uniform LightDirectionArrayID = sm.current()->uniform_location("light_direction"); crap::uniform LightTypeArrayID = sm.current()->uniform_location("light_type"); crap::uniform LightStateArrayID = sm.current()->uniform_location("light_state"); crap::uniform LightNormalMappingOnID = sm.current()->uniform_location("normal_mapping_on"); //shadow stuff crap::uniform ShadowMapID = sm.current()->uniform_location("shadow_map"); crap::uniform ShadowMappingOnID = sm.current()->uniform_location("shadow_mapping_on"); crap::uniform ShadowDepthBiasMVPID = sm.current()->uniform_location("depth_bias_mvp"); //SHADER DATA // Projection matrix : 60° Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units float display_field_of_view = 60.f; //60° float display_ratio_horizontal = 4.f; float display_ratio_vertical = 3.f; float display_range_near = 0.1f; float display_range_far = 100.f; glm::mat4 projection_matrix = glm::perspective( display_field_of_view, display_ratio_horizontal / display_ratio_vertical, display_range_near, display_range_far); glm::mat4 model_matrix(1.0f); glm::mat4 model_view_matrix(1.0f); glm::mat4 view_matrix = cam.view(); glm::mat4 world_matrix(1.0f); glm::mat3 model_view_matrix3x3(1.0f); //light stuff float light_ambient_power = 0.5f; float light_power_array[MAX_LIGHTS] = { 1.f, 1.f, 1.f }; int light_specular_type_array[MAX_LIGHTS] = { 1, 1, 1 }; float light_specular_lobe_array[MAX_LIGHTS] = { 100.f, 100.f, 100.f }; glm::vec3 light_color_array[MAX_LIGHTS] = { glm::vec3(1.f), glm::vec3(1.f), glm::vec3(1.f) }; int light_self_shadowing_on = 1; glm::vec3 light_position_array[MAX_LIGHTS] = { glm::vec3(4,0,0), glm::vec3(0,0,-4), glm::vec3(4,4,4) }; glm::vec3 light_direction_array[MAX_LIGHTS] = { glm::vec3(-4,0,0), glm::vec3(0,0,4), glm::vec3(-4,-4,-4) }; int light_type_array[MAX_LIGHTS] = { 0, 0, 0 }; int light_state_array[MAX_LIGHTS] = { 1, 0, 0 }; int light_normal_mapping_on = 1; //shadowstuff int shadow_mapping_on = 1; //displacement stuff int displacement_on = 1; float displacement_steps = 20; float displacement_refinement_steps = 20; float displacmenet_uv_factor = 20; //GUI TwInit(TW_OPENGL, NULL); TwWindowSize(1024, 768); TwBar * GeneralGUI = TwNewBar("General settings"); TwBar * LightGUI = TwNewBar("Light Settings"); TwBar * DisplacementGUI = TwNewBar("Displacement Settings"); TwSetParam(GeneralGUI, NULL, "refresh", TW_PARAM_CSTRING, 1, "0.1"); TwSetParam(LightGUI, NULL, "refresh", TW_PARAM_CSTRING, 1, "0.1"); TwSetParam(DisplacementGUI, NULL, "refresh", TW_PARAM_CSTRING, 1, "0.1"); //general gui TwAddSeparator(GeneralGUI, "Funny seperator", NULL); TwAddVarRW(GeneralGUI, "Field of View", TW_TYPE_FLOAT , &display_field_of_view, "help='Field of View value'"); TwAddVarRW(GeneralGUI, "Ratio Horizontal", TW_TYPE_FLOAT , &display_ratio_horizontal, "help='Ratio Horizontal'"); TwAddVarRW(GeneralGUI, "Ratio Vertical", TW_TYPE_FLOAT , &display_ratio_vertical, "help='Ratio Vertical'"); TwAddVarRW(GeneralGUI, "Range Near", TW_TYPE_FLOAT , &display_range_near, "help='Range near'"); TwAddVarRW(GeneralGUI, "Range far", TW_TYPE_FLOAT , &display_range_far, "help='Range far'"); //light gui TwAddVarRW(LightGUI, "Ambient light", TW_TYPE_FLOAT , &light_ambient_power, "help='Ambient power'"); TwAddVarRW(LightGUI, "Self Shadowing", TW_TYPE_BOOL32, &light_self_shadowing_on, NULL); TwAddVarRW(LightGUI, "Normal Mapping", TW_TYPE_BOOL32, &light_normal_mapping_on, NULL); TwType gui_light_type = TwDefineEnumFromString("LightType", "Directionallight,Pointlight"); TwType gui_light_specular_type = TwDefineEnumFromString("LightSpecularType", "Blinn,Phong"); //shadow TwAddVarRW(LightGUI, "Cast Shadows", TW_TYPE_BOOL32, &shadow_mapping_on, NULL); //light1 TwAddVarRW(LightGUI, "Light 1", TW_TYPE_BOOL32, light_state_array, NULL); TwAddVarRW(LightGUI, "Light Type 1", gui_light_type, light_type_array, NULL); TwAddVarRW(LightGUI, "Light Specular Type 1", gui_light_specular_type, light_specular_type_array, NULL); TwAddVarRW(LightGUI, "Light Power 1", TW_TYPE_FLOAT , light_power_array, NULL); TwAddVarRW(LightGUI, "Light Specular Lobe 1", TW_TYPE_FLOAT , light_specular_lobe_array, NULL); TwAddVarRW(LightGUI, "Light Color 1", TW_TYPE_COLOR3F , light_color_array, NULL); TwAddVarRW(LightGUI, "Light Position 1", TW_TYPE_DIR3F , light_position_array, NULL); TwAddVarRW(LightGUI, "Light Direction 1", TW_TYPE_DIR3F , light_direction_array, NULL); //light2 TwAddVarRW(LightGUI, "Light 2", TW_TYPE_BOOL32, light_state_array+1, NULL); TwAddVarRW(LightGUI, "Light Type 2", gui_light_type, light_type_array+1, NULL); TwAddVarRW(LightGUI, "Light Specular Type 2", gui_light_specular_type, light_specular_type_array+1, NULL); TwAddVarRW(LightGUI, "Light Power 2", TW_TYPE_FLOAT , light_power_array+1, NULL); TwAddVarRW(LightGUI, "Light Specular Lobe 2", TW_TYPE_FLOAT , light_specular_lobe_array+1, NULL); TwAddVarRW(LightGUI, "Light Color 2", TW_TYPE_COLOR3F , light_color_array+1, NULL); TwAddVarRW(LightGUI, "Light Position 2", TW_TYPE_DIR3F , light_position_array+1, NULL); TwAddVarRW(LightGUI, "Light Direction 2", TW_TYPE_DIR3F , light_direction_array+1, NULL); //light3 TwAddVarRW(LightGUI, "Light 3", TW_TYPE_BOOL32, light_state_array+2, NULL); TwAddVarRW(LightGUI, "Light Type 3", gui_light_type, light_type_array+2, NULL); TwAddVarRW(LightGUI, "Light Specular Type 3", gui_light_specular_type, light_specular_type_array+2, NULL); TwAddVarRW(LightGUI, "Light Power 3", TW_TYPE_FLOAT , light_power_array+2, NULL); TwAddVarRW(LightGUI, "Light Specular Lobe 3", TW_TYPE_FLOAT , light_specular_lobe_array+2, NULL); TwAddVarRW(LightGUI, "Light Color 3", TW_TYPE_COLOR3F , light_color_array+2, NULL); TwAddVarRW(LightGUI, "Light Position 3", TW_TYPE_DIR3F , light_position_array+2, NULL); TwAddVarRW(LightGUI, "Light Direction 3", TW_TYPE_DIR3F , light_direction_array+2, NULL); //displacement gui TwAddVarRW(DisplacementGUI, "Displacement ON/OFF", TW_TYPE_BOOL32, &displacement_on, NULL); TwAddVarRW(DisplacementGUI, "Displacment steps", TW_TYPE_FLOAT , &displacement_steps, NULL); TwAddVarRW(DisplacementGUI, "Displacement refinement", TW_TYPE_FLOAT , &displacement_refinement_steps, NULL); TwAddVarRW(DisplacementGUI, "Displacement UV factor", TW_TYPE_FLOAT , &displacmenet_uv_factor, NULL); //gui mouse setup mouse.set_on_pressed_function( (crap::mouse::user_button_callback_function)gui_mouse_down ); mouse.set_on_release_function( (crap::mouse::user_button_callback_function)gui_mouse_up ); mouse.set_on_move_function( (crap::mouse::user_move_callback_function)TwEventMousePosGLFW ); mouse.set_on_wheel_function( (crap::mouse::user_wheel_callback_function)TwEventMouseWheelGLFW ); keyboard.set_on_pressed_function( (crap::keyboard::user_callback_function)TwEventKeyGLFW ); //todo set char input // temporary crap::opengl::clearColor(1.0f, 1.0f, 1.0f, 0.0f); while( !keyboard.is_pressed( crap::keyboard::key_escape ) && window.is_open() ) { // update positions handleInput(keyboard, mouse, cam); crap::opengl::clear(crap::opengl::color_depth_buffer); frame_buffer.bind(); glViewport(0,0,1024,1024); // Render on the whole framebuffer, complete from the lower left corner to the upper right sm.set_current("shadow_vert", "shadow_frag"); sm.activate(); glm::vec3 lightInvDir = light_direction_array[0]; //glm::vec3(0.5f,2,2); // Compute the MVP matrix from the light's point of view glm::mat4 depthProjectionMatrix = glm::ortho<float>(-10,10,-10,10,-10,20); glm::mat4 depthViewMatrix = glm::lookAt(lightInvDir, glm::vec3(0,0,0), glm::vec3(0,1,0)); glm::mat4 depthModelMatrix = glm::mat4(1.0); glm::mat4 depthMVP = depthProjectionMatrix * depthViewMatrix * depthModelMatrix; sm.current()->uniform_matrix4f_value( DepthBiasMVPID, 1, &depthMVP[0][0]); sm.current()->vertex_attribute_array.enable(0); cube_vbo.bind_buffer( vbo::verticies ); sm.current()->vertex_attribute_array.pointer( 0, 3, crap::gl_float, false, 0, (void*)0); cube_vbo.bind_buffer( vbo::indicies ); crap::opengl::draw_elements( crap::opengl::triangles, // mode cube_vbo.indicies_size, // count crap::opengl::unsigned_short // type ); sm.current()->vertex_attribute_array.disable(0); frame_buffer.unbind(); glViewport(0,0,1024,768); // Render on the whole framebuffer, complete from the lower left corner to the upper right crap::opengl::clear(crap::opengl::color_depth_buffer); sm.set_current("epr_vert", "epr_frag"); sm.activate(); /////////////////////////////////////// ////////////////////////////////////// projection_matrix = glm::perspective( display_field_of_view, display_ratio_horizontal / display_ratio_vertical, display_range_near, display_range_far); view_matrix = cam.view(); model_view_matrix = view_matrix * world_matrix; model_view_matrix3x3 = glm::mat3(model_view_matrix); world_matrix = projection_matrix * view_matrix * model_matrix; glm::mat4 biasMatrix( 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0 ); glm::mat4 depthBiasMVP = biasMatrix*depthMVP; sm.current()->uniform_matrix4f_value( ShadowDepthBiasMVPID, 1, &depthBiasMVP[0][0]); sm.current()->uniform_1i(ShadowMappingOnID, shadow_mapping_on); //activate shader porgram and connect data //sm.activate(); //default stuff sm.current()->uniform_matrix4f_value( WorldMatrixID, 1, &world_matrix[0][0]); sm.current()->uniform_matrix4f_value( ModelMatrixID, 1, &model_matrix[0][0]); sm.current()->uniform_matrix4f_value( ViewMatrixID, 1, &view_matrix[0][0]); sm.current()->uniform_matrix3f_value( ModelView3x3MatrixID, 1, &model_view_matrix3x3[0][0]); //light sm.activate(); sm.current()->uniform_1f(LightAmbientPowerID, light_ambient_power); sm.current()->uniform_1i(LightSelfShadowingOnID, light_self_shadowing_on); sm.current()->uniform_1i(LightNormalMappingOnID, light_normal_mapping_on); sm.current()->uniform_1f_value( LightPowerArrayID, 3, light_power_array ); sm.current()->uniform_1i_value( LightSpecularTypeArrayID, 3, light_specular_type_array ); sm.current()->uniform_1f_value( LightSpecularLobeArrayID, 3, light_specular_lobe_array ); sm.current()->uniform_3f_value( LightColorArrayID, 3, (f32*)light_color_array ); sm.current()->uniform_3f_value( LightPositionArrayID, 3, (f32*)light_position_array ); sm.current()->uniform_3f_value( LightDirectionArrayID, 3, (f32*)light_direction_array ); sm.current()->uniform_1i_value( LightTypeArrayID, 3, light_type_array ); sm.current()->uniform_1i_value( LightStateArrayID, 3, light_state_array ); //displacement sm.current()->uniform_1i( DisplacementOnID, displacement_on ); sm.current()->uniform_1f( DisplacementStepsID, displacement_steps); sm.current()->uniform_1f( DisplacementRefinementStepsID, displacement_refinement_steps); sm.current()->uniform_1f( DisplacementUVFactorID, displacmenet_uv_factor); //activate texture buffer and connect data diffuse_tbo.activate(); diffuse_tbo.bind_buffer(); sm.current()->uniform_1i( DiffuseTextureID, 0); normal_tbo.activate(); normal_tbo.bind_buffer(); sm.current()->uniform_1i( NormalTextureID, 1); height_tbo.activate(); height_tbo.bind_buffer(); sm.current()->uniform_1i( HeightTextureID, 2 ); depthmap.activate(); depthmap.bind_buffer(); sm.current()->uniform_1i( ShadowMapID, 4); //define data of buffers sm.current()->vertex_attribute_array.enable(0); //cube_vbo.bind_buffer( vbo::verticies ); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); sm.current()->vertex_attribute_array.pointer( 0, 3, crap::gl_float, false, 0, (void*)0); sm.current()->vertex_attribute_array.enable(1); glBindBuffer(GL_ARRAY_BUFFER, uvbuffer); //cube_vbo.bind_buffer( vbo::uvs ); sm.current()->vertex_attribute_array.pointer( 1, 2, crap::gl_float, false, 0, (void*)0); sm.current()->vertex_attribute_array.enable(2); glBindBuffer(GL_ARRAY_BUFFER, normalbuffer); //cube_vbo.bind_buffer( vbo::normals ); sm.current()->vertex_attribute_array.pointer( 2, 3, crap::gl_float, false, 0, (void*)0); sm.current()->vertex_attribute_array.enable(3); glBindBuffer(GL_ARRAY_BUFFER, tangentbuffer); //cube_vbo.bind_buffer( vbo::tangents ); sm.current()->vertex_attribute_array.pointer( 3, 3, crap::gl_float, false, 0, (void*)0); sm.current()->vertex_attribute_array.enable(4); glBindBuffer(GL_ARRAY_BUFFER, bitangentbuffer); //cube_vbo.bind_buffer( vbo::binormals ); sm.current()->vertex_attribute_array.pointer( 4, 3, crap::gl_float, false, 0, (void*)0); ////draw the f**k cube_vbo.bind_buffer( vbo::indicies ); crap::opengl::draw_elements( crap::opengl::triangles, // mode cube_vbo.indicies_size, // count crap::opengl::unsigned_short // type ); sm.current()->vertex_attribute_array.disable(0); sm.current()->vertex_attribute_array.disable(1); sm.current()->vertex_attribute_array.disable(2); sm.current()->vertex_attribute_array.disable(3); sm.current()->vertex_attribute_array.disable(4); //next object glm::mat4 model_matrix_2 = model_matrix * glm::translate(3.f,0.f,0.f); model_view_matrix = view_matrix * model_matrix_2; model_view_matrix3x3 = glm::mat3(model_view_matrix); world_matrix = projection_matrix * view_matrix * model_matrix_2; //activate shader porgram and connect data //sm.activate(); sm.current()->uniform_matrix4f_value( WorldMatrixID, 1, &world_matrix[0][0]); sm.current()->uniform_matrix4f_value( ModelMatrixID, 1, &model_matrix_2[0][0]); sm.current()->uniform_matrix3f_value( ModelView3x3MatrixID, 1, &model_view_matrix3x3[0][0]); //attempt //define data of buffers sm.current()->vertex_attribute_array.enable(0); ape_vbo.bind_buffer( vbo::verticies ); sm.current()->vertex_attribute_array.pointer( 0, 3, crap::gl_float, false, 0, (void*)0); sm.current()->vertex_attribute_array.enable(1); ape_vbo.bind_buffer( vbo::uvs ); sm.current()->vertex_attribute_array.pointer( 1, 2, crap::gl_float, false, 0, (void*)0); sm.current()->vertex_attribute_array.enable(2); ape_vbo.bind_buffer( vbo::normals ); sm.current()->vertex_attribute_array.pointer( 2, 3, crap::gl_float, false, 0, (void*)0); sm.current()->vertex_attribute_array.enable(3); ape_vbo.bind_buffer( vbo::tangents ); sm.current()->vertex_attribute_array.pointer(3, 3, crap::gl_float, false, 0, (void*)0); sm.current()->vertex_attribute_array.enable(4); ape_vbo.bind_buffer( vbo::binormals ); sm.current()->vertex_attribute_array.pointer( 4, 3, crap::gl_float, false, 0, (void*)0); //draw the f**k ape_vbo.bind_buffer( vbo::indicies ); crap::opengl::draw_elements( crap::opengl::triangles, // mode ape_vbo.indicies_size, // count crap::opengl::unsigned_short // type ); //disable data define stuff sm.current()->vertex_attribute_array.disable(0); sm.current()->vertex_attribute_array.disable(1); sm.current()->vertex_attribute_array.disable(2); sm.current()->vertex_attribute_array.disable(3); sm.current()->vertex_attribute_array.disable(4); //next object glm::mat4 model_matrix_3 = model_matrix * glm::translate(0.f,-2.f,0.f); model_view_matrix = view_matrix * model_matrix_2; model_view_matrix3x3 = glm::mat3(model_view_matrix); world_matrix = projection_matrix * view_matrix * model_matrix_3; //activate shader porgram and connect data //sm.activate(); sm.current()->uniform_matrix4f_value( WorldMatrixID, 1, &world_matrix[0][0]); sm.current()->uniform_matrix4f_value( ModelMatrixID, 1, &model_matrix_3[0][0]); sm.current()->uniform_matrix3f_value( ModelView3x3MatrixID, 1, &model_view_matrix3x3[0][0]); //attempt //define data of buffers sm.current()->vertex_attribute_array.enable(0); cube_big_vbo.bind_buffer( vbo::verticies ); sm.current()->vertex_attribute_array.pointer( 0, 3, crap::gl_float, false, 0, (void*)0); sm.current()->vertex_attribute_array.enable(1); cube_big_vbo.bind_buffer( vbo::uvs ); sm.current()->vertex_attribute_array.pointer( 1, 2, crap::gl_float, false, 0, (void*)0); sm.current()->vertex_attribute_array.enable(2); cube_big_vbo.bind_buffer( vbo::normals ); sm.current()->vertex_attribute_array.pointer( 2, 3, crap::gl_float, false, 0, (void*)0); sm.current()->vertex_attribute_array.enable(3); cube_big_vbo.bind_buffer( vbo::tangents ); sm.current()->vertex_attribute_array.pointer(3, 3, crap::gl_float, false, 0, (void*)0); sm.current()->vertex_attribute_array.enable(4); cube_big_vbo.bind_buffer( vbo::binormals ); sm.current()->vertex_attribute_array.pointer( 4, 3, crap::gl_float, false, 0, (void*)0); //draw the f**k cube_big_vbo.bind_buffer( vbo::indicies ); crap::opengl::draw_elements( crap::opengl::triangles, // mode cube_big_vbo.indicies_size, // count crap::opengl::unsigned_short // type ); //disable data define stuff sm.current()->vertex_attribute_array.disable(0); sm.current()->vertex_attribute_array.disable(1); sm.current()->vertex_attribute_array.disable(2); sm.current()->vertex_attribute_array.disable(3); sm.current()->vertex_attribute_array.disable(4); glMatrixMode(GL_PROJECTION); glLoadMatrixf((const GLfloat*)&projection_matrix[0]); glMatrixMode(GL_MODELVIEW); glm::mat4 MV = view_matrix * model_matrix; glLoadMatrixf((const GLfloat*)&MV[0]); sm.activate(); // normals glColor3f(0,0,1); glBegin(GL_LINES); for (unsigned int i=0; i<ig.indices_size; i++){ glm::vec3 p = glm::vec3(ig.positions[ig.indices[i]].x, ig.positions[ig.indices[i]].y, ig.positions[ig.indices[i]].z ); glVertex3fv(&p.x); glm::vec3 o = glm::normalize( glm::vec3(ig.normals[ig.indices[i]].x, ig.normals[ig.indices[i]].y, ig.normals[ig.indices[i]].z) ); p+=o*0.1f; glVertex3fv(&p.x); } glEnd(); // tangents glColor3f(1,0,0); glBegin(GL_LINES); for (unsigned int i=0; i<ig.indices_size; i++){ glm::vec3 p = glm::vec3(ig.positions[ig.indices[i]].x, ig.positions[ig.indices[i]].y, ig.positions[ig.indices[i]].z ); glVertex3fv(&p.x); glm::vec3 o = glm::normalize( glm::vec3(ig.tangents[ig.indices[i]].x, ig.tangents[ig.indices[i]].y, ig.tangents[ig.indices[i]].z) ); p+=o*0.1f; glVertex3fv(&p.x); } glEnd(); // bitangents glColor3f(0,1,0); glBegin(GL_LINES); for (unsigned int i=0; i<ig.indices_size; i++){ glm::vec3 p = glm::vec3(ig.positions[ig.indices[i]].x, ig.positions[ig.indices[i]].y, ig.positions[ig.indices[i]].z ); glVertex3fv(&p.x); glm::vec3 o = glm::normalize( glm::vec3(ig.binormals[ig.indices[i]].x, ig.binormals[ig.indices[i]].y, ig.binormals[ig.indices[i]].z) ); p+=o*0.1f; glVertex3fv(&p.x); } glEnd(); glm::vec3 debug_light; // light pos 1 glColor3f(1,1,1); glBegin(GL_LINES); debug_light = light_position_array[0]; glVertex3fv(&debug_light.x); debug_light+=glm::vec3(1,0,0)*0.1f; glVertex3fv(&debug_light.x); debug_light-=glm::vec3(1,0,0)*0.1f; glVertex3fv(&debug_light.x); debug_light+=glm::vec3(0,1,0)*0.1f; glVertex3fv(&debug_light.x); glEnd(); // light pos 2 glColor3f(1,1,1); glBegin(GL_LINES); debug_light = light_position_array[1]; glVertex3fv(&debug_light.x); debug_light+=glm::vec3(1,0,0)*0.1f; glVertex3fv(&debug_light.x); debug_light-=glm::vec3(1,0,0)*0.1f; glVertex3fv(&debug_light.x); debug_light+=glm::vec3(0,1,0)*0.1f; glVertex3fv(&debug_light.x); glEnd(); // light pos3 glColor3f(1,1,1); glBegin(GL_LINES); debug_light = light_position_array[2]; glVertex3fv(&debug_light.x); debug_light+=glm::vec3(1,0,0)*0.1f; glVertex3fv(&debug_light.x); debug_light-=glm::vec3(1,0,0)*0.1f; glVertex3fv(&debug_light.x); debug_light+=glm::vec3(0,1,0)*0.1f; glVertex3fv(&debug_light.x); glEnd(); // Draw GUI TwDraw(); //poll and swap window.swap(); window.poll_events(); } TwTerminate(); //geometry_content ig; //cm.create_content( "ape" , &ig, type_name::geometry ); //texture_content tc; //cm.create_content( "color", &tc, type_name::texture ); //shader_content sc; //cm.create_content( "fragment_texture_only", &sc, type_name::shader ); //cm.save_content( "fragment_texture_only", &sc, type_name::shader ); return 0; }
int ProgressLoop (SDL_Window *pWindow, Progress *pProgress, bool &error) { /* Since this function runs in a separate thread, we need to use a different rendering context. Attach it to the same window: */ SDL_GLContext glContext = SDL_GL_CreateContext (pWindow); /* rect order: x1, y1, x2, y2 rect 1 is most outside, rect 3 is most inside */ float rects [3][4], f, x1, x2; for (int i = 0; i < 3; i++) { f = 2 - i; rects [i][0] = -(f * LOAD_BAR_EDGE + LOAD_BAR_WIDTH / 2); rects [i][1] = -(f * LOAD_BAR_EDGE + LOAD_BAR_HEIGHT / 2); rects [i][2] = f * LOAD_BAR_EDGE + LOAD_BAR_WIDTH / 2; rects [i][3] = f * LOAD_BAR_EDGE + LOAD_BAR_HEIGHT / 2; } std::size_t total, passed; do { total = pProgress->GetTotal (); passed = pProgress->GetPassed (); int w, h; SDL_GL_GetDrawableSize (pWindow, &w, &h); glViewport (0, 0, w, h); glMatrixMode (GL_PROJECTION); matrix4 matScreen = matOrtho (-float (w) / 2, float (w) / 2, -float (h) / 2, float (h) / 2, -1.0f, 1.0f); glLoadMatrixf (matScreen.m); glMatrixMode (GL_MODELVIEW); glLoadIdentity (); glClearColor (0,0,0,1); glClear (GL_COLOR_BUFFER_BIT); glColor4f (1,1,1,1); glDisable (GL_CULL_FACE); glDisable (GL_LIGHTING); // Outer line: glBegin (GL_QUAD_STRIP); glVertex2f (rects [0][0], rects [0][1]); glVertex2f (rects [1][0], rects [1][1]); glVertex2f (rects [0][2], rects [0][1]); glVertex2f (rects [1][2], rects [1][1]); glVertex2f (rects [0][2], rects [0][3]); glVertex2f (rects [1][2], rects [1][3]); glVertex2f (rects [0][0], rects [0][3]); glVertex2f (rects [1][0], rects [1][3]); glVertex2f (rects [0][0], rects [0][1]); glVertex2f (rects [1][0], rects [1][1]); glEnd (); // progress bar if (total > 0 && passed <= total) f = float (passed) / total; else f = 0; x1 = rects [2][0]; x2 = x1 + f * (rects [2][2] - rects [2][0]); glBegin (GL_QUADS); glVertex2f (x1, rects [2][1]); glVertex2f (x2, rects [2][1]); glVertex2f (x2, rects [2][3]); glVertex2f (x1, rects [2][3]); glEnd (); SDL_GL_SwapWindow (pWindow); } while (!error && passed < total); // keep rendering as long as the other thread loads SDL_GL_DeleteContext (glContext); return 0; }
void Render() { PROFILE3("render"); g_SoundManager->IdleTask(); ogl_WarnIfError(); g_Profiler2.RecordGPUFrameStart(); ogl_WarnIfError(); CStr skystring = "255 0 255"; CFG_GET_USER_VAL("skycolor", String, skystring); CColor skycol; GUI<CColor>::ParseString(skystring.FromUTF8(), skycol); g_Renderer.SetClearColor(skycol.AsSColor4ub()); // prepare before starting the renderer frame if (g_Game && g_Game->IsGameStarted()) g_Game->GetView()->BeginFrame(); // start new frame g_Renderer.BeginFrame(); ogl_WarnIfError(); if (g_Game && g_Game->IsGameStarted()) g_Game->GetView()->Render(); ogl_WarnIfError(); g_Renderer.RenderTextOverlays(); if (g_DoRenderGui) g_GUI->Draw(); ogl_WarnIfError(); // If we're in Atlas game view, render special overlays (e.g. editor bandbox) if (g_AtlasGameLoop && g_AtlasGameLoop->view) { g_AtlasGameLoop->view->DrawOverlays(); ogl_WarnIfError(); } // Text: glDisable(GL_DEPTH_TEST); g_Console->Render(); ogl_WarnIfError(); if (g_DoRenderLogger) g_Logger->Render(); ogl_WarnIfError(); // Profile information g_ProfileViewer.RenderProfile(); ogl_WarnIfError(); // Draw the cursor (or set the Windows cursor, on Windows) if (g_DoRenderCursor) { PROFILE3_GPU("cursor"); CStrW cursorName = g_CursorName; if (cursorName.empty()) { cursor_draw(g_VFS, NULL, g_mouse_x, g_yres-g_mouse_y, false); } else { bool forceGL = false; CFG_GET_USER_VAL("nohwcursor", Bool, forceGL); #if CONFIG2_GLES #warning TODO: implement cursors for GLES #else // set up transform for GL cursor glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); CMatrix3D transform; transform.SetOrtho(0.f, (float)g_xres, 0.f, (float)g_yres, -1.f, 1000.f); glLoadMatrixf(&transform._11); #endif if (cursor_draw(g_VFS, cursorName.c_str(), g_mouse_x, g_yres-g_mouse_y, forceGL) < 0) LOGWARNING(L"Failed to draw cursor '%ls'", cursorName.c_str()); #if CONFIG2_GLES #warning TODO: implement cursors for GLES #else // restore transform glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); #endif } } glEnable(GL_DEPTH_TEST); g_Renderer.EndFrame(); PROFILE2_ATTR("draw calls: %d", (int)g_Renderer.GetStats().m_DrawCalls); PROFILE2_ATTR("terrain tris: %d", (int)g_Renderer.GetStats().m_TerrainTris); PROFILE2_ATTR("water tris: %d", (int)g_Renderer.GetStats().m_WaterTris); PROFILE2_ATTR("model tris: %d", (int)g_Renderer.GetStats().m_ModelTris); PROFILE2_ATTR("overlay tris: %d", (int)g_Renderer.GetStats().m_OverlayTris); PROFILE2_ATTR("blend splats: %d", (int)g_Renderer.GetStats().m_BlendSplats); PROFILE2_ATTR("particles: %d", (int)g_Renderer.GetStats().m_Particles); ogl_WarnIfError(); g_Profiler2.RecordGPUFrameEnd(); ogl_WarnIfError(); }
// The face knows where it needs to rotate to. // Pass the current perspective to the face and load the returned perspective rotation. void rotateToFace(int faceNum) { GLfloat matrix[16]; glGetFloatv(GL_MODELVIEW_MATRIX, matrix); face[faceNum]->rotateToSelf(matrix); glLoadMatrixf(matrix); }
/* ============= R_Mirror ============= */ void R_Mirror (void) { float d; msurface_t *s; entity_t *ent; if (!mirror) return; memcpy (r_base_world_matrix, r_world_matrix, sizeof(r_base_world_matrix)); d = DotProduct (r_refdef.vieworg, mirror_plane->normal) - mirror_plane->dist; VectorMA (r_refdef.vieworg, -2*d, mirror_plane->normal, r_refdef.vieworg); d = DotProduct (vpn, mirror_plane->normal); VectorMA (vpn, -2*d, mirror_plane->normal, vpn); r_refdef.viewangles[0] = -asin (vpn[2])/M_PI*180; r_refdef.viewangles[1] = atan2 (vpn[1], vpn[0])/M_PI*180; r_refdef.viewangles[2] = -r_refdef.viewangles[2]; ent = &cl_entities[cl.viewentity]; if (cl_numvisedicts < MAX_VISEDICTS) { cl_visedicts[cl_numvisedicts] = ent; cl_numvisedicts++; } gldepthmin = 0.5; gldepthmax = 1; #ifdef USE_OPENGLES glDepthRangef (gldepthmin, gldepthmax); #else glDepthRange (gldepthmin, gldepthmax); #endif glDepthFunc (GL_LEQUAL); R_RenderScene (); R_DrawWaterSurfaces (); gldepthmin = 0; gldepthmax = 0.5; #ifdef USE_OPENGLES glDepthRangef (gldepthmin, gldepthmax); #else glDepthRange (gldepthmin, gldepthmax); #endif glDepthFunc (GL_LEQUAL); // blend on top glEnable (GL_BLEND); glMatrixMode(GL_PROJECTION); if (mirror_plane->normal[2]) glScalef (1,-1,1); else glScalef (-1,1,1); glCullFace(GL_FRONT); glMatrixMode(GL_MODELVIEW); glLoadMatrixf (r_base_world_matrix); glColor4f (1,1,1,r_mirroralpha.value); s = cl.worldmodel->textures[mirrortexturenum]->texturechain; for ( ; s ; s=s->texturechain) R_RenderBrushPoly (s); cl.worldmodel->textures[mirrortexturenum]->texturechain = NULL; glDisable (GL_BLEND); glColor4f (1,1,1,1); }
// Paint the display! void display(BOOL rebuild, F32 zoom_factor, int subfield, BOOL for_snapshot) { LLFastTimer t(LLFastTimer::FTM_RENDER); if (LLPipeline::sRenderFrameTest) { send_agent_pause(); } gSnapshot = for_snapshot; LLGLSDefault gls_default; LLGLDepthTest gls_depth(GL_TRUE, GL_TRUE, GL_LEQUAL); LLVertexBuffer::unbind(); LLGLState::checkStates(); LLGLState::checkTextureChannels(); gPipeline.disableLights(); // Don't draw if the window is hidden or minimized. // In fact, must explicitly check the minimized state before drawing. // Attempting to draw into a minimized window causes a GL error. JC if ( !gViewerWindow->getActive() || !gViewerWindow->mWindow->getVisible() || gViewerWindow->mWindow->getMinimized() ) { // Clean up memory the pools may have allocated if (rebuild) { gFrameStats.start(LLFrameStats::REBUILD); gPipeline.rebuildPools(); } gViewerWindow->returnEmptyPicks(); return; } gViewerWindow->checkSettings(); { LLFastTimer ftm(LLFastTimer::FTM_PICK); LLAppViewer::instance()->pingMainloopTimeout("Display:Pick"); gViewerWindow->performPick(); } LLAppViewer::instance()->pingMainloopTimeout("Display:CheckStates"); LLGLState::checkStates(); LLGLState::checkTextureChannels(); ////////////////////////////////////////////////////////// // // Logic for forcing window updates if we're in drone mode. // if (gNoRender) { #if LL_WINDOWS static F32 last_update_time = 0.f; if ((gFrameTimeSeconds - last_update_time) > 1.f) { InvalidateRect((HWND)gViewerWindow->getPlatformWindow(), NULL, FALSE); last_update_time = gFrameTimeSeconds; } #elif LL_DARWIN // MBW -- Do something clever here. #endif // Not actually rendering, don't bother. return; } // // Bail out if we're in the startup state and don't want to try to // render the world. // if (LLStartUp::getStartupState() < STATE_STARTED) { LLAppViewer::instance()->pingMainloopTimeout("Display:Startup"); display_startup(); return; } //LLGLState::verify(FALSE); ///////////////////////////////////////////////// // // Update GL Texture statistics (used for discard logic?) // LLAppViewer::instance()->pingMainloopTimeout("Display:TextureStats"); gFrameStats.start(LLFrameStats::UPDATE_TEX_STATS); stop_glerror(); LLImageGL::updateStats(gFrameTimeSeconds); LLVOAvatar::sRenderName = gSavedSettings.getS32("RenderName"); LLVOAvatar::sRenderGroupTitles = !gSavedSettings.getBOOL("RenderHideGroupTitleAll"); gPipeline.mBackfaceCull = TRUE; gFrameCount++; gRecentFrameCount++; if (gFocusMgr.getAppHasFocus()) { gForegroundFrameCount++; } ////////////////////////////////////////////////////////// // // Display start screen if we're teleporting, and skip render // if (gTeleportDisplay) { LLAppViewer::instance()->pingMainloopTimeout("Display:Teleport"); const F32 TELEPORT_ARRIVAL_DELAY = 2.f; // Time to preload the world before raising the curtain after we've actually already arrived. S32 attach_count = 0; if (gAgent.getAvatarObject()) { attach_count = gAgent.getAvatarObject()->getAttachmentCount(); } F32 teleport_save_time = TELEPORT_EXPIRY + TELEPORT_EXPIRY_PER_ATTACHMENT * attach_count; F32 teleport_elapsed = gTeleportDisplayTimer.getElapsedTimeF32(); F32 teleport_percent = teleport_elapsed * (100.f / teleport_save_time); if( (gAgent.getTeleportState() != LLAgent::TELEPORT_START) && (teleport_percent > 100.f) ) { // Give up. Don't keep the UI locked forever. gAgent.setTeleportState( LLAgent::TELEPORT_NONE ); gAgent.setTeleportMessage(std::string()); } const std::string& message = gAgent.getTeleportMessage(); switch( gAgent.getTeleportState() ) { case LLAgent::TELEPORT_START: // Transition to REQUESTED. Viewer has sent some kind // of TeleportRequest to the source simulator gTeleportDisplayTimer.reset(); if(!gSavedSettings.getBOOL("AscentDisableTeleportScreens"))gViewerWindow->setShowProgress(TRUE); gViewerWindow->setProgressPercent(0); gAgent.setTeleportState( LLAgent::TELEPORT_REQUESTED ); gAgent.setTeleportMessage( LLAgent::sTeleportProgressMessages["requesting"]); break; case LLAgent::TELEPORT_REQUESTED: // Waiting for source simulator to respond gViewerWindow->setProgressPercent( llmin(teleport_percent, 37.5f) ); gViewerWindow->setProgressString(message); break; case LLAgent::TELEPORT_MOVING: // Viewer has received destination location from source simulator gViewerWindow->setProgressPercent( llmin(teleport_percent, 75.f) ); gViewerWindow->setProgressString(message); break; case LLAgent::TELEPORT_START_ARRIVAL: // Transition to ARRIVING. Viewer has received avatar update, etc., from destination simulator gTeleportArrivalTimer.reset(); gViewerWindow->setProgressCancelButtonVisible(FALSE, std::string("Cancel")); //TODO: Translate gViewerWindow->setProgressPercent(75.f); gAgent.setTeleportState( LLAgent::TELEPORT_ARRIVING ); gAgent.setTeleportMessage( LLAgent::sTeleportProgressMessages["arriving"]); gImageList.mForceResetTextureStats = TRUE; if(!gSavedSettings.getBOOL("AscentDisableTeleportScreens"))gAgent.resetView(TRUE, TRUE); break; case LLAgent::TELEPORT_ARRIVING: // Make the user wait while content "pre-caches" { F32 arrival_fraction = (gTeleportArrivalTimer.getElapsedTimeF32() / TELEPORT_ARRIVAL_DELAY); if( arrival_fraction > 1.f || gSavedSettings.getBOOL("AscentDisableTeleportScreens")) { arrival_fraction = 1.f; LLFirstUse::useTeleport(); gAgent.setTeleportState( LLAgent::TELEPORT_NONE ); } gViewerWindow->setProgressCancelButtonVisible(FALSE, std::string("Cancel")); //TODO: Translate gViewerWindow->setProgressPercent( arrival_fraction * 25.f + 75.f); gViewerWindow->setProgressString(message); } break; case LLAgent::TELEPORT_LOCAL: // Short delay when teleporting in the same sim (progress screen active but not shown - did not // fall-through from TELEPORT_START) { // <edit> // is this really needed.... I say no. //if( gTeleportDisplayTimer.getElapsedTimeF32() > TELEPORT_LOCAL_DELAY ) // </edit> { LLFirstUse::useTeleport(); gAgent.setTeleportState( LLAgent::TELEPORT_NONE ); } } break; case LLAgent::TELEPORT_NONE: // No teleport in progress gViewerWindow->setShowProgress(FALSE); gTeleportDisplay = FALSE; gTeleportArrivalTimer.reset(); break; default: break; } } else if(LLAppViewer::instance()->logoutRequestSent()) { LLAppViewer::instance()->pingMainloopTimeout("Display:Logout"); F32 percent_done = gLogoutTimer.getElapsedTimeF32() * 100.f / gLogoutMaxTime; if (percent_done > 100.f) { percent_done = 100.f; } if( LLApp::isExiting() ) { percent_done = 100.f; } gViewerWindow->setProgressPercent( percent_done ); } else if (gRestoreGL) { LLAppViewer::instance()->pingMainloopTimeout("Display:RestoreGL"); F32 percent_done = gRestoreGLTimer.getElapsedTimeF32() * 100.f / RESTORE_GL_TIME; if( percent_done > 100.f ) { gViewerWindow->setShowProgress(FALSE); gRestoreGL = FALSE; } else { if( LLApp::isExiting() ) { percent_done = 100.f; } gViewerWindow->setProgressPercent( percent_done ); } } // Progressively increase draw distance after TP when required. if (gSavedDrawDistance > 0.0f && gAgent.getTeleportState() == LLAgent::TELEPORT_NONE) { if (gTeleportArrivalTimer.getElapsedTimeF32() >= (F32)gSavedSettings.getU32("SpeedRezInterval")) { gTeleportArrivalTimer.reset(); F32 current = gSavedSettings.getF32("RenderFarClip"); if (gSavedDrawDistance > current) { current *= 2.0; if (current > gSavedDrawDistance) { current = gSavedDrawDistance; } gSavedSettings.setF32("RenderFarClip", current); } if (current >= gSavedDrawDistance) { gSavedDrawDistance = 0.0f; gSavedSettings.setF32("SavedRenderFarClip", 0.0f); } } } ////////////////////////// // // Prepare for the next frame // ///////////////////////////// // // Update the camera // // LLAppViewer::instance()->pingMainloopTimeout("Display:Camera"); LLViewerCamera::getInstance()->setZoomParameters(zoom_factor, subfield); LLViewerCamera::getInstance()->setNear(MIN_NEAR_PLANE); ////////////////////////// // // clear the next buffer // (must follow dynamic texture writing since that uses the frame buffer) // if (gDisconnected) { LLAppViewer::instance()->pingMainloopTimeout("Display:Disconnected"); render_ui(); render_disconnected_background(); } ////////////////////////// // // Set rendering options // // LLAppViewer::instance()->pingMainloopTimeout("Display:RenderSetup"); stop_glerror(); /////////////////////////////////////// // // Slam lighting parameters back to our defaults. // Note that these are not the same as GL defaults... stop_glerror(); F32 one[4] = {1.f, 1.f, 1.f, 1.f}; glLightModelfv (GL_LIGHT_MODEL_AMBIENT,one); stop_glerror(); ///////////////////////////////////// // // Render // // Actually push all of our triangles to the screen. // // do render-to-texture stuff here if (gPipeline.hasRenderDebugFeatureMask(LLPipeline::RENDER_DEBUG_FEATURE_DYNAMIC_TEXTURES)) { LLAppViewer::instance()->pingMainloopTimeout("Display:DynamicTextures"); LLFastTimer t(LLFastTimer::FTM_UPDATE_TEXTURES); if (LLDynamicTexture::updateAllInstances()) { gGL.setColorMask(true, true); glClear(GL_DEPTH_BUFFER_BIT); } } gViewerWindow->setupViewport(); gPipeline.resetFrameStats(); // Reset per-frame statistics. if (!gDisconnected) { LLAppViewer::instance()->pingMainloopTimeout("Display:Update"); if (gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_HUD)) { //don't draw hud objects in this frame gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_HUD); } if (gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_HUD_PARTICLES)) { //don't draw hud particles in this frame gPipeline.toggleRenderType(LLPipeline::RENDER_TYPE_HUD_PARTICLES); } //upkeep gl name pools LLGLNamePool::upkeepPools(); stop_glerror(); display_update_camera(); stop_glerror(); // *TODO: merge these two methods LLHUDManager::getInstance()->updateEffects(); LLHUDObject::updateAll(); stop_glerror(); gFrameStats.start(LLFrameStats::UPDATE_GEOM); const F32 max_geom_update_time = 0.005f*10.f*gFrameIntervalSeconds; // 50 ms/second update time gPipeline.createObjects(max_geom_update_time); gPipeline.updateGeom(max_geom_update_time); stop_glerror(); gFrameStats.start(LLFrameStats::UPDATE_CULL); S32 water_clip = 0; if ((LLViewerShaderMgr::instance()->getVertexShaderLevel(LLViewerShaderMgr::SHADER_ENVIRONMENT) > 1) && (gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_WATER) || gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_VOIDWATER))) { if (LLViewerCamera::getInstance()->cameraUnderWater()) { water_clip = -1; } else { water_clip = 1; } } LLAppViewer::instance()->pingMainloopTimeout("Display:Cull"); //Increment drawable frame counter LLDrawable::incrementVisible(); LLSpatialGroup::sNoDelete = TRUE; LLPipeline::sUseOcclusion = (!gUseWireframe && LLFeatureManager::getInstance()->isFeatureAvailable("UseOcclusion") && gSavedSettings.getBOOL("UseOcclusion") && gGLManager.mHasOcclusionQuery) ? 2 : 0; if (LLPipeline::sUseOcclusion && LLPipeline::sRenderDeferred) { //force occlusion on for all render types if doing deferred render LLPipeline::sUseOcclusion = 3; } LLPipeline::sFastAlpha = gSavedSettings.getBOOL("RenderFastAlpha"); LLPipeline::sUseFarClip = gSavedSettings.getBOOL("RenderUseFarClip"); LLVOAvatar::sMaxVisible = gSavedSettings.getS32("RenderAvatarMaxVisible"); LLPipeline::sDelayVBUpdate = gSavedSettings.getBOOL("RenderDelayVBUpdate"); S32 occlusion = LLPipeline::sUseOcclusion; if (gDepthDirty) { //depth buffer is invalid, don't overwrite occlusion state LLPipeline::sUseOcclusion = llmin(occlusion, 1); } gDepthDirty = FALSE; LLGLState::checkStates(); LLGLState::checkTextureChannels(); LLGLState::checkClientArrays(); static LLCullResult result; gPipeline.updateCull(*LLViewerCamera::getInstance(), result, water_clip); stop_glerror(); LLGLState::checkStates(); LLGLState::checkTextureChannels(); LLGLState::checkClientArrays(); BOOL to_texture = !for_snapshot && gPipeline.canUseVertexShaders() && LLPipeline::sRenderGlow; LLAppViewer::instance()->pingMainloopTimeout("Display:Swap"); { { LLFastTimer ftm(LLFastTimer::FTM_CLIENT_COPY); LLVertexBuffer::clientCopy(0.016); } if (gResizeScreenTexture) { gResizeScreenTexture = FALSE; gPipeline.resizeScreenTexture(); } gGL.setColorMask(true, true); glClearColor(0,0,0,0); LLGLState::checkStates(); LLGLState::checkTextureChannels(); LLGLState::checkClientArrays(); if (!for_snapshot) { if (gFrameCount > 1) { //for some reason, ATI 4800 series will error out if you //try to generate a shadow before the first frame is through gPipeline.generateSunShadow(*LLViewerCamera::getInstance()); } LLGLState::checkStates(); LLGLState::checkTextureChannels(); LLGLState::checkClientArrays(); glh::matrix4f proj = glh_get_current_projection(); glh::matrix4f mod = glh_get_current_modelview(); glViewport(0,0,512,512); LLVOAvatar::updateFreezeCounter() ; LLVOAvatar::updateImpostors(); glh_set_current_projection(proj); glh_set_current_modelview(mod); glMatrixMode(GL_PROJECTION); glLoadMatrixf(proj.m); glMatrixMode(GL_MODELVIEW); glLoadMatrixf(mod.m); gViewerWindow->setupViewport(); LLGLState::checkStates(); LLGLState::checkTextureChannels(); LLGLState::checkClientArrays(); } glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); } if (!for_snapshot) { LLAppViewer::instance()->pingMainloopTimeout("Display:Imagery"); gPipeline.generateWaterReflection(*LLViewerCamera::getInstance()); } ////////////////////////////////////// // // Update images, using the image stats generated during object update/culling // // Can put objects onto the retextured list. // // Doing this here gives hardware occlusion queries extra time to complete LLAppViewer::instance()->pingMainloopTimeout("Display:UpdateImages"); LLError::LLCallStacks::clear() ; llpushcallstacks ; gFrameStats.start(LLFrameStats::IMAGE_UPDATE); { LLFastTimer t(LLFastTimer::FTM_IMAGE_UPDATE); LLViewerImage::updateClass(LLViewerCamera::getInstance()->getVelocityStat()->getMean(), LLViewerCamera::getInstance()->getAngularVelocityStat()->getMean()); gBumpImageList.updateImages(); // must be called before gImageList version so that it's textures are thrown out first. F32 max_image_decode_time = 0.050f*gFrameIntervalSeconds; // 50 ms/second decode time max_image_decode_time = llclamp(max_image_decode_time, 0.001f, 0.005f ); // min 1ms/frame, max 5ms/frame) gImageList.updateImages(max_image_decode_time); stop_glerror(); } llpushcallstacks ; /////////////////////////////////// // // StateSort // // Responsible for taking visible objects, and adding them to the appropriate draw orders. // In the case of alpha objects, z-sorts them first. // Also creates special lists for outlines and selected face rendering. // LLAppViewer::instance()->pingMainloopTimeout("Display:StateSort"); { gFrameStats.start(LLFrameStats::STATE_SORT); gPipeline.stateSort(*LLViewerCamera::getInstance(), result); stop_glerror(); if (rebuild) { ////////////////////////////////////// // // rebuildPools // // gFrameStats.start(LLFrameStats::REBUILD); gPipeline.rebuildPools(); stop_glerror(); } } LLPipeline::sUseOcclusion = occlusion; { LLAppViewer::instance()->pingMainloopTimeout("Display:Sky"); LLFastTimer t(LLFastTimer::FTM_UPDATE_SKY); gSky.updateSky(); } if(gUseWireframe) { glClearColor(0.5f, 0.5f, 0.5f, 0.f); glClear(GL_COLOR_BUFFER_BIT); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); } LLAppViewer::instance()->pingMainloopTimeout("Display:RenderStart"); //// render frontmost floater opaque for occlusion culling purposes //LLFloater* frontmost_floaterp = gFloaterView->getFrontmost(); //// assumes frontmost floater with focus is opaque //if (frontmost_floaterp && gFocusMgr.childHasKeyboardFocus(frontmost_floaterp)) //{ // glMatrixMode(GL_MODELVIEW); // glPushMatrix(); // { // gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE); // glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_TRUE); // glLoadIdentity(); // LLRect floater_rect = frontmost_floaterp->getScreenRect(); // // deflate by one pixel so rounding errors don't occlude outside of floater extents // floater_rect.stretch(-1); // LLRectf floater_3d_rect((F32)floater_rect.mLeft / (F32)gViewerWindow->getWindowWidth(), // (F32)floater_rect.mTop / (F32)gViewerWindow->getWindowHeight(), // (F32)floater_rect.mRight / (F32)gViewerWindow->getWindowWidth(), // (F32)floater_rect.mBottom / (F32)gViewerWindow->getWindowHeight()); // floater_3d_rect.translate(-0.5f, -0.5f); // glTranslatef(0.f, 0.f, -LLViewerCamera::getInstance()->getNear()); // glScalef(LLViewerCamera::getInstance()->getNear() * LLViewerCamera::getInstance()->getAspect() / sinf(LLViewerCamera::getInstance()->getView()), LLViewerCamera::getInstance()->getNear() / sinf(LLViewerCamera::getInstance()->getView()), 1.f); // gGL.color4fv(LLColor4::white.mV); // gGL.begin(LLVertexBuffer::QUADS); // { // gGL.vertex3f(floater_3d_rect.mLeft, floater_3d_rect.mBottom, 0.f); // gGL.vertex3f(floater_3d_rect.mLeft, floater_3d_rect.mTop, 0.f); // gGL.vertex3f(floater_3d_rect.mRight, floater_3d_rect.mTop, 0.f); // gGL.vertex3f(floater_3d_rect.mRight, floater_3d_rect.mBottom, 0.f); // } // gGL.end(); // glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); // } // glPopMatrix(); //} LLPipeline::sUnderWaterRender = LLViewerCamera::getInstance()->cameraUnderWater() ? TRUE : FALSE; LLPipeline::updateRenderDeferred(); stop_glerror(); if (to_texture) { gGL.setColorMask(true, true); if (LLPipeline::sRenderDeferred && !LLPipeline::sUnderWaterRender) { gPipeline.mDeferredScreen.bindTarget(); gPipeline.mDeferredScreen.clear(); } else { gPipeline.mScreen.bindTarget(); gPipeline.mScreen.clear(); } gGL.setColorMask(true, false); } LLAppViewer::instance()->pingMainloopTimeout("Display:RenderGeom"); if (!(LLAppViewer::instance()->logoutRequestSent() && LLAppViewer::instance()->hasSavedFinalSnapshot()) && !gRestoreGL) { gGL.setColorMask(true, false); if (LLPipeline::sRenderDeferred && !LLPipeline::sUnderWaterRender) { gPipeline.renderGeomDeferred(*LLViewerCamera::getInstance()); } else { gPipeline.renderGeom(*LLViewerCamera::getInstance(), TRUE); } gGL.setColorMask(true, true); //store this frame's modelview matrix for use //when rendering next frame's occlusion queries for (U32 i = 0; i < 16; i++) { gGLLastModelView[i] = gGLModelView[i]; } stop_glerror(); } LLAppViewer::instance()->pingMainloopTimeout("Display:RenderFlush"); if (to_texture) { if (LLPipeline::sRenderDeferred && !LLPipeline::sUnderWaterRender) { gPipeline.mDeferredScreen.flush(); } else { gPipeline.mScreen.flush(); } } /// We copy the frame buffer straight into a texture here, /// and then display it again with compositor effects. /// Using render to texture would be faster/better, but I don't have a /// grasp of their full display stack just yet. // gPostProcess->apply(gViewerWindow->getWindowDisplayWidth(), gViewerWindow->getWindowDisplayHeight()); if (LLPipeline::sRenderDeferred && !LLPipeline::sUnderWaterRender) { gPipeline.renderDeferredLighting(); } LLPipeline::sUnderWaterRender = FALSE; LLAppViewer::instance()->pingMainloopTimeout("Display:RenderUI"); if (!for_snapshot) { gFrameStats.start(LLFrameStats::RENDER_UI); render_ui(); } LLSpatialGroup::sNoDelete = FALSE; } LLAppViewer::instance()->pingMainloopTimeout("Display:FrameStats"); gFrameStats.start(LLFrameStats::MISC_END); stop_glerror(); if (LLPipeline::sRenderFrameTest) { send_agent_resume(); LLPipeline::sRenderFrameTest = FALSE; } display_stats(); LLAppViewer::instance()->pingMainloopTimeout("Display:Done"); }
void LLDrawPoolWater::render(S32 pass) { LLFastTimer ftm(LLFastTimer::FTM_RENDER_WATER); if (mDrawFace.empty() || LLDrawable::getCurrentFrame() <= 1) { return; } //do a quick 'n dirty depth sort for (std::vector<LLFace*>::iterator iter = mDrawFace.begin(); iter != mDrawFace.end(); iter++) { LLFace* facep = *iter; facep->mDistance = -facep->mCenterLocal.mV[2]; } std::sort(mDrawFace.begin(), mDrawFace.end(), LLFace::CompareDistanceGreater()); LLGLEnable blend(GL_BLEND); if ((mVertexShaderLevel > 0) && !sSkipScreenCopy) { shade(); return; } LLVOSky *voskyp = gSky.mVOSkyp; stop_glerror(); if (!gGLManager.mHasMultitexture) { // Ack! No multitexture! Bail! return; } LLFace* refl_face = voskyp->getReflFace(); gPipeline.disableLights(); LLGLDepthTest gls_depth(GL_TRUE, GL_FALSE); LLGLDisable cullFace(GL_CULL_FACE); // Set up second pass first mWaterImagep->addTextureStats(1024.f*1024.f); gGL.getTexUnit(1)->activate(); gGL.getTexUnit(1)->enable(LLTexUnit::TT_TEXTURE); gGL.getTexUnit(1)->bind(mWaterImagep.get()); LLVector3 camera_up = LLViewerCamera::getInstance()->getUpAxis(); F32 up_dot = camera_up * LLVector3::z_axis; LLColor4 water_color; if (LLViewerCamera::getInstance()->cameraUnderWater()) { water_color.setVec(1.f, 1.f, 1.f, 0.4f); } else { water_color.setVec(1.f, 1.f, 1.f, 0.5f*(1.f + up_dot)); } glColor4fv(water_color.mV); // Automatically generate texture coords for detail map glEnable(GL_TEXTURE_GEN_S); //texture unit 1 glEnable(GL_TEXTURE_GEN_T); //texture unit 1 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); // Slowly move over time. F32 offset = fmod(gFrameTimeSeconds*2.f, 100.f); F32 tp0[4] = {16.f/256.f, 0.0f, 0.0f, offset*0.01f}; F32 tp1[4] = {0.0f, 16.f/256.f, 0.0f, offset*0.01f}; glTexGenfv(GL_S, GL_OBJECT_PLANE, tp0); glTexGenfv(GL_T, GL_OBJECT_PLANE, tp1); gGL.getTexUnit(1)->setTextureColorBlend(LLTexUnit::TBO_MULT, LLTexUnit::TBS_TEX_COLOR, LLTexUnit::TBS_PREV_COLOR); gGL.getTexUnit(1)->setTextureAlphaBlend(LLTexUnit::TBO_REPLACE, LLTexUnit::TBS_PREV_ALPHA); gGL.getTexUnit(0)->activate(); glClearStencil(1); glClear(GL_STENCIL_BUFFER_BIT); LLGLEnable gls_stencil(GL_STENCIL_TEST); glStencilOp(GL_KEEP, GL_REPLACE, GL_KEEP); glStencilFunc(GL_ALWAYS, 0, 0xFFFFFFFF); for (std::vector<LLFace*>::iterator iter = mDrawFace.begin(); iter != mDrawFace.end(); iter++) { LLFace *face = *iter; if (voskyp->isReflFace(face)) { continue; } gGL.getTexUnit(0)->bind(face->getTexture()); face->renderIndexed(); } // Now, disable texture coord generation on texture state 1 gGL.getTexUnit(1)->activate(); gGL.getTexUnit(1)->unbind(LLTexUnit::TT_TEXTURE); gGL.getTexUnit(1)->disable(); glDisable(GL_TEXTURE_GEN_S); //texture unit 1 glDisable(GL_TEXTURE_GEN_T); //texture unit 1 // Disable texture coordinate and color arrays gGL.getTexUnit(0)->activate(); gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE); stop_glerror(); if (gSky.mVOSkyp->getCubeMap()) { gSky.mVOSkyp->getCubeMap()->enable(0); gSky.mVOSkyp->getCubeMap()->bind(); glMatrixMode(GL_TEXTURE); glLoadIdentity(); LLMatrix4 camera_mat = LLViewerCamera::getInstance()->getModelview(); LLMatrix4 camera_rot(camera_mat.getMat3()); camera_rot.invert(); glLoadMatrixf((F32 *)camera_rot.mMatrix); glMatrixMode(GL_MODELVIEW); LLOverrideFaceColor overrid(this, 1.f, 1.f, 1.f, 0.5f*up_dot); gGL.getTexUnit(0)->setTextureBlendType(LLTexUnit::TB_MULT); for (std::vector<LLFace*>::iterator iter = mDrawFace.begin(); iter != mDrawFace.end(); iter++) { LLFace *face = *iter; if (voskyp->isReflFace(face)) { //refl_face = face; continue; } if (face->getGeomCount() > 0) { face->renderIndexed(); } } gGL.getTexUnit(0)->setTextureBlendType(LLTexUnit::TB_MULT); gSky.mVOSkyp->getCubeMap()->disable(); gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE); gGL.getTexUnit(0)->enable(LLTexUnit::TT_TEXTURE); glMatrixMode(GL_TEXTURE); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); } glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); if (refl_face) { glStencilFunc(GL_NOTEQUAL, 0, 0xFFFFFFFF); renderReflection(refl_face); } gGL.getTexUnit(0)->setTextureBlendType(LLTexUnit::TB_MULT); }
// Rendu de la surface de l'eau void SceneTerrain::RenderWaterSurface() { VarManager& var = VarManager::getInstance(); float h = var.getf("water_height"); glPushAttrib(GL_ENABLE_BIT); glDisable(GL_CULL_FACE); glEnable(GL_BLEND); glMatrixMode(GL_TEXTURE); glActiveTexture(GL_TEXTURE0); glLoadMatrixf( m_matSunModelviewProj ); glMatrixMode(GL_MODELVIEW); m_pShaderWater->Activate(); { m_fboWaterReflection.Bind(0); m_pShaderWater->UniformTexture("texWaterReflection", 0); m_pTexWaterNoiseNM->Bind(1); m_pShaderWater->UniformTexture("texWaterNoiseNM", 1); m_pShaderWater->Uniform("win_width", var.geti("win_width")); m_pShaderWater->Uniform("win_height", var.geti("win_height")); m_pShaderWater->Uniform("noise_tile", 10.0f); m_pShaderWater->Uniform("noise_factor", 0.1f); m_pShaderWater->Uniform("time", Timer::getInstance().getCurrentTime()); m_pShaderWater->Uniform("water_shininess", 50.0f); for(GLuint i=0; i<TERRAIN_SHADOWMAPS_COUNT; i++) m_fboDepthMapFromLight[i].Bind(2 + i); m_pShaderWater->UniformTexture("texDepthMapFromLight0", 2); m_pShaderWater->UniformTexture("texDepthMapFromLight1", 3); m_pShaderWater->Uniform("depth_map_size", 512); vec3 e = Camera::getInstance().getEye(); float d = 2.0f * var.getf("cam_zfar"); glBegin(GL_QUADS); glVertex3f(e.x - d, h, e.z - d); glVertex3f(e.x - d, h, e.z + d); glVertex3f(e.x + d, h, e.z + d); glVertex3f(e.x + d, h, e.z - d); glEnd(); for(GLint i=TERRAIN_SHADOWMAPS_COUNT-1; i>=0; i--) m_fboDepthMapFromLight[i].Unbind(2 + i); m_pTexWaterNoiseNM->Unbind(1); m_fboWaterReflection.Unbind(0); } m_pShaderWater->Deactivate(); glMatrixMode(GL_TEXTURE); glActiveTexture(GL_TEXTURE0); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glPopAttrib(); }