//-------------------------------------------------------------- // initialize application void DontHitMe::appInit() { // get the important directories mgString shaderDir; m_options.getFileName("shaderDir", m_options.m_sourceFileName, "docs/shaders", shaderDir); mgString uiDir; m_options.getFileName("uiDir", m_options.m_sourceFileName, "docs/ui", uiDir); mgString fontDir; m_options.getFileName("fontDir", m_options.m_sourceFileName, "docs/fonts", fontDir); mgInitDisplayServices(shaderDir, fontDir); mgDisplay->setFOV(m_options.getDouble("FOV", 60.0)); mgDisplay->setDPI(m_options.getInteger("DPI", 0)); // load cursor pattern loadCursor(); setDeskMode(true); initMovement(); // load the shaders we might use mgVertex::loadShader("litTexture"); mgVertex::loadShader("unlitTexture"); mgVertex::loadShader("litTextureCube"); mgVertex::loadShader("unlitTextureCube"); mgVertexTA::loadShader("litTextureArray"); mgVertexTA::loadShader("unlitTextureArray"); m_sky = new StarrySky(m_options); m_sky->enableSkyBox(true); m_sky->enableStars(true); m_sky->enableSun(true); mgPoint3 lightDir(0, 1, 1); lightDir.normalize(); m_sky->setSunDir(lightDir); mgDisplay->setLightDir(lightDir); m_saucer = new Saucer(m_options); m_planet = new Planet(m_options); m_wreck = new Wreck(m_options); m_tower1 = new Tower(m_options, false); m_tower2 = new Tower(m_options, false); mgString fileName; m_options.getFileName("tube", m_options.m_sourceFileName, "tube.jpg", fileName); m_tubeTexture = mgDisplay->loadTexture(fileName); initTrack(); initBall(); updateBallPt(); m_intro = new Intro(m_options, m_ballOrigin); m_showingIntro = false; m_lastAnimate = mgOSGetTime(); // now! }
TheaSDK::Normal3D TheaRenderer::getSunDirection() { MFnDependencyNode depFn(getRenderGlobalsNode()); std::shared_ptr<RenderGlobals> renderGlobals = MayaTo::getWorldPtr()->worldRenderGlobalsPtr; std::shared_ptr<TheaRenderer> renderer = std::static_pointer_cast<TheaRenderer>(MayaTo::getWorldPtr()->worldRendererPtr); TheaSDK::Normal3D sunDir; MObjectArray nodeList; getConnectedInNodes(MString("sunLightConnection"), getRenderGlobalsNode(), nodeList); if( nodeList.length() > 0) { MVector lightDir(0,0,1); MFnDagNode sunDagNode(nodeList[0]); //lightDir *= this->mtth_renderGlobals->globalConversionMatrix.inverse(); lightDir *= sunDagNode.transformationMatrix(); lightDir *= renderGlobals->globalConversionMatrix; lightDir.normalize(); return TheaSDK::Normal3D(lightDir.x,lightDir.y,lightDir.z); } float sunDirX = 0.0f, sunDirY = 0.0f, sunDirZ = 1.0f; MPlug sunDirPlug = depFn.findPlug("sunDirection"); if (!sunDirPlug.isNull()) { sunDirX = sunDirPlug.child(0).asFloat(); sunDirY = sunDirPlug.child(1).asFloat(); sunDirZ = sunDirPlug.child(2).asFloat(); } return TheaSDK::Normal3D(sunDirX, sunDirY, sunDirZ); }
// Initialize the engine void Demo::Initialize(HINSTANCE hInstance, int nCmdShow) { // Grab instance Demo* pDemo = Demo::privGetInstance(); // Create window pDemo->window = pDemo->privCreateGraphicsWindow(hInstance, nCmdShow, "Bricks Demo", GAME_WIDTH, GAME_HEIGHT); // Initialize Direct3D pDemo->privInitDevice(); pDemo->privCreateShader(); pDemo->privCreateBuffers(); // initialize motion blur pDemo->motionBlur.initialize(200); pDemo->motionBlur.setBlurTime(0.5f); // Set up camera pDemo->cam.setViewport(0, 0, GAME_WIDTH, GAME_HEIGHT); pDemo->cam.setPerspective(35.0f, float(GAME_WIDTH) / float(GAME_HEIGHT), 1.0f, 4500.0f); pDemo->cam.setOrientAndPosition(Vect(0.0f, 1.0f, 0.0f), Vect(0.0f, 50.0f, -10.0f), Vect(0.0f, 50.0f, 0.0f)); pDemo->cam.updateCamera(); pDemo->projection = pDemo->cam.getProjMatrix(); pDemo->projection.T(); pDemo->deviceCon->UpdateSubresource(pDemo->projectionBuffer, 0, nullptr, &pDemo->projection, 0, 0); // Set up Lighting Vect lightDir(20.0f, 100.0f, 100.0f); lightDir.norm(); Vect lightColor(1.0f, 1.0f, 1.0f, 1.0f); pDemo->lightInfo.color = lightColor; pDemo->lightInfo.direction = lightDir; pDemo->globalLightDir = lightDir; pDemo->deviceCon->UpdateSubresource(pDemo->lightBuffer, 0, nullptr, &pDemo->lightInfo, 0, 0); };
Material* RendererD3D::SetMaterial(Material* material, const Matrix4x4& ltw) { Material* old = mCurrentMaterial; mCurrentMaterial = material; if( material ) { VertexShaderD3D9* vs = (VertexShaderD3D9*)material->GetVertexShader(); mDevice->SetVertexShader(vs ? vs->GetShader() : 0); Matrix4x4 wvp = ltw * mViewProjectionMatrix; mDevice->SetVertexShaderConstantF(0, wvp, 4); mDevice->SetVertexShaderConstantF(4, ltw, 4); PixelShaderD3D9* ps = (PixelShaderD3D9*)material->GetPixelShader(); mDevice->SetPixelShader(ps ? ps->GetShader() : 0); Vector4 lightDir(1, 1, 0); Vector3* ld = (Vector3*)&lightDir; ld->Normalize(); mDevice->SetPixelShaderConstantF(0, &lightDir.mX, 1); } return old; }
void SceneBase::RenderLight(void) { const int NUM_LIGHT_PARAMS = U_LIGHT0_EXPONENT - U_NUMLIGHTS; for (size_t i = 0; i < m_NUM_LIGHTS; ++i) { if (lights[i].enabled == false) { continue; } if (lights[i].type == Light::LIGHT_DIRECTIONAL) { Vector3 lightDir(lights[i].position.x, lights[i].position.y, lights[i].position.z); Vector3 lightDirection_cameraspace = viewStack.Top() * lightDir; glUniform3fv(m_parameters[U_LIGHT0_POSITION + i * NUM_LIGHT_PARAMS], 1, &lightDirection_cameraspace.x); } else if (lights[i].type == Light::LIGHT_SPOT) { Position lightPosition_cameraspace = viewStack.Top() * lights[i].position; glUniform3fv(m_parameters[U_LIGHT0_POSITION + i * NUM_LIGHT_PARAMS], 1, &lightPosition_cameraspace.x); Vector3 spotDirection_cameraspace = viewStack.Top() * lights[i].spotDirection; glUniform3fv(m_parameters[U_LIGHT0_SPOTDIRECTION + i * NUM_LIGHT_PARAMS], 1, &spotDirection_cameraspace.x); } else { Position lightPosition_cameraspace = viewStack.Top() * lights[i].position; glUniform3fv(m_parameters[U_LIGHT0_POSITION + i * NUM_LIGHT_PARAMS], 1, &lightPosition_cameraspace.x); } } }
void Bonsai::renderAll() { Luddite::TextureDB &texDB = Luddite::TextureDB::singleton(); GLuint texId = texDB.getTextureId( m_treeLand->m_htexTerrainColor ); GLuint texIdNorm = texDB.getTextureId( m_treeLand->m_htexTerrainNorm ); glActiveTexture( GL_TEXTURE0 ); glEnable( GL_TEXTURE_2D ); glBindTexture( GL_TEXTURE_2D, texId ); glActiveTexture( GL_TEXTURE1 ); glEnable( GL_TEXTURE_2D ); glBindTexture( GL_TEXTURE_2D, texIdNorm ); glUseProgram( m_progTreeland ); glUniform1i( m_paramTreeland_samplerDif0, 0 ); glUniform1i( m_paramTreeland_samplerNrm0, 1 ); PVRTVec3 lightDir( 1, 0, 0 ); lightDir.normalize(); glUniform3f( m_paramTreeland_lightDir, 1.0, 0.0, 0.0 ); //glUniform3f( m_paramTreeland_lightDir, lightDir.x, lightDir.y, lightDir.z ); m_treeLand->renderAll(); glUseProgram( 0 ); }
void OpeningCutScene2::Render() { // Render VBO here glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //Set view matrix using camera settings viewStack.LoadIdentity(); viewStack.Rotate(MoveCamera1, 0, 1, 0); viewStack.Rotate(RotateCamera, 1, 0, 0); viewStack.LookAt( camera.position.x, camera.position.y, camera.position.z, camera.target.x, camera.target.y, camera.target.z, camera.up.x, camera.up.y, camera.up.z ); modelStack.LoadIdentity(); RenderSceneStart(); RenderTextWord(); // Light Source 1 if (light[0].type == Light::LIGHT_DIRECTIONAL) { Vector3 lightDir(light[0].position.x, light[0].position.y, light[0].position.z); Vector3 lightDirection_cameraspace = viewStack.Top() * lightDir; glUniform3fv(m_parameters[U_LIGHT0_POSITION], 1, &lightDirection_cameraspace.x); } else if (light[0].type == Light::LIGHT_SPOT) { Position lightPosition_cameraspace = viewStack.Top() * light[0].position; glUniform3fv(m_parameters[U_LIGHT0_POSITION], 1, &lightPosition_cameraspace.x); Vector3 spotDirection_cameraspace = viewStack.Top() * light[0].spotDirection; glUniform3fv(m_parameters[U_LIGHT0_SPOTDIRECTION], 1, &spotDirection_cameraspace.x); } else { Position lightPosition_cameraspace = viewStack.Top() * light[0].position; glUniform3fv(m_parameters[U_LIGHT0_POSITION], 1, &lightPosition_cameraspace.x); } //basic renders modelStack.PushMatrix(); RenderModelOnScreen(meshList[GEO_QUAD], 80, 60, 5, 90, 1, 0, 0, 0.5f, 1+eyeOpening, 1, false); modelStack.PopMatrix(); modelStack.PushMatrix(); RenderModelOnScreen(meshList[GEO_QUAD], 80, 60, 5, 90, 1, 0, 0, 0.5f, -eyeOpening, 1, false); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(0, 0, 53); modelStack.Rotate(180, 0, 1, 0); modelStack.Scale(15, 15, 15); RenderMesh(meshList[GEO_DEADBODY], true); modelStack.PopMatrix(); }
void Scene::createVertexNode() { _vgeode = new osg::Geode; _vgeode->setDataVariance(osg::Object::DYNAMIC); osg::Vec3f lightDir(1.0f, 1.0f, 1.0f); lightDir.normalize(); auto offsets = new osg::Uniform(osg::Uniform::FLOAT_VEC3, "offsets", Scene::VertexInstances); offsets->setDataVariance(osg::Object::DYNAMIC); auto stateSet = _vgeode->getOrCreateStateSet(); stateSet->setAttributeAndModes(_instancedProgram, osg::StateAttribute::ON); stateSet->addUniform(new osg::Uniform("ecLightDirection", lightDir)); stateSet->addUniform(new osg::Uniform("lightColor", osg::Vec3(1.0f, 1.0f, 1.0f))); stateSet->addUniform(offsets); osg::Vec3 scale(1.0f, 1.0f, 1.0f); osg::Vec4 color(0.25f, 0.25f, 0.25f, 1.0f); auto vertexMatrix = osg::Matrixf::scale(scale * 0.125f * 0.25f); auto normalMatrix = inverseTranspose(vertexMatrix); _vgeometry = new osgKaleido::PolyhedronGeometry("#27"); _vgeometry->setUseDisplayList(false); _vgeometry->setUseVertexBufferObjects(true); _vgeometry->update(nullptr); // Force geometry generation auto vertices = dynamic_cast<osg::Vec3Array*>(_vgeometry->getVertexArray()); if (vertices != nullptr) { transform(*vertices, vertexMatrix); } auto normals = dynamic_cast<osg::Vec3Array*>(_vgeometry->getNormalArray()); if (normals != nullptr) { transform(*normals, normalMatrix); } auto colors = dynamic_cast<osg::Vec4Array*>(_vgeometry->getColorArray()); if (colors != nullptr) { fill(*colors, color); } makeInstanced(_vgeometry, Scene::VertexInstances); auto size = 1.0f; osg::BoundingBox bb(-size, -size, -size, +size, +size, +size); _vgeometry->setInitialBound(bb); _vgeode->addDrawable(_vgeometry); addChild(_vgeode); }
//-------------------------------------------------------------------------------------- // Render the scene using the D3D10 device //-------------------------------------------------------------------------------------- void CALLBACK OnD3D10FrameRender( ID3D10Device* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext ) { // Clear the render target float ClearColor[4] = { 0.9569f, 0.9569f, 1.0f, 0.0f }; ID3D10RenderTargetView* pRTV = DXUTGetD3D10RenderTargetView(); pd3dDevice->ClearRenderTargetView( pRTV, ClearColor ); ID3D10DepthStencilView* pDSV = DXUTGetD3D10DepthStencilView(); pd3dDevice->ClearDepthStencilView( pDSV, D3D10_CLEAR_DEPTH, 1.0, 0 ); // Render the result D3DXMATRIX mWorld; D3DXMATRIX mView; D3DXMATRIX mProj; D3DXMATRIX mWorldView; D3DXMATRIX mWorldViewProj; mWorld = *g_Camera.GetWorldMatrix(); mProj = *g_Camera.GetProjMatrix(); mView = *g_Camera.GetViewMatrix(); mWorldView = mWorld * mView; mWorldViewProj = mWorldView * mProj; // Set variables g_pmWorldViewProj->SetMatrix( ( float* )&mWorldViewProj ); g_pmWorldView->SetMatrix( ( float* )&mWorldView ); g_pmWorld->SetMatrix( ( float* )&mWorld ); g_pmView->SetMatrix( ( float* )&mView ); g_pmProj->SetMatrix( ( float* )&mProj ); g_pDiffuseTex->SetResource( g_pMeshTexRV ); D3DXVECTOR3 lightDir( -1,1,-1 ); D3DXVECTOR3 viewLightDir; D3DXVec3TransformNormal( &viewLightDir, &lightDir, &mView ); D3DXVec3Normalize( &viewLightDir, &viewLightDir ); g_pViewSpaceLightDir->SetFloatVector( ( float* )&viewLightDir ); // Set Input Assembler params UINT stride = g_VertStride; UINT offset = 0; pd3dDevice->IASetInputLayout( g_pVertexLayout ); pd3dDevice->IASetPrimitiveTopology( D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST ); pd3dDevice->IASetIndexBuffer( g_pIB, DXGI_FORMAT_R32_UINT, 0 ); pd3dDevice->IASetVertexBuffers( 0, 1, &g_pVB, &stride, &offset ); // Render using the technique g_pRenderTextured D3D10_TECHNIQUE_DESC techDesc; g_pRenderTextured->GetDesc( &techDesc ); for( UINT p = 0; p < techDesc.Passes; p++ ) { g_pRenderTextured->GetPassByIndex( p )->Apply( 0 ); pd3dDevice->DrawIndexed( g_NumIndices, 0, 0 ); } }
void display() { // WCS-to-VCS mat4 WCS_to_VCS = lookat( eyePosition, worldCentre, vec3(0,1,0) ); // WCS-to-CCS float n = (eyePosition - worldCentre).length() - worldRadius; float f = (eyePosition - worldCentre).length() + worldRadius; mat4 WCS_to_CCS = perspective( fovy, windowWidth / (float) windowHeight, n, f ) * WCS_to_VCS; // Light direction is in the WCS, but rotates vec3 lightDir(1,1.5,1); lightDir = lightDir.normalize(); vec4 rotatedLightDir = rotate( theta, vec3(0,1,0) ) * vec4( lightDir, 0 ); vec3 rotatedLightDir3 = vec3( rotatedLightDir.x, rotatedLightDir.y, rotatedLightDir.z ); // Draw the objects renderer->render( objs, WCS_to_VCS, WCS_to_CCS, rotatedLightDir3, eyePosition ); // Draw the world axes if (showAxes && !renderer->debugOn()) { mat4 axesTransform = WCS_to_CCS * scale( 10, 10, 10 ); axes->draw( axesTransform, rotatedLightDir3 ); } // Output status message char buffer[1000]; renderer->makeStatusMessage( buffer ); glColor3f(0.3,0.3,1.0); printString( buffer, 10, 10, windowWidth, windowHeight ); // Done glutSwapBuffers(); }
void configureShaders(osg::StateSet *stateSet) { const std::string vertexSource = "#version 140 \n" " \n" "uniform mat4 osg_ModelViewProjectionMatrix; \n" "uniform mat3 osg_NormalMatrix; \n" "uniform vec3 ecLightDir; \n" " \n" "in vec4 osg_Vertex; \n" "in vec3 osg_Normal; \n" "out vec4 color; \n" " \n" "void main() \n" "{ \n" " vec3 ecNormal = normalize( osg_NormalMatrix * osg_Normal ); \n" " float diffuse = max( dot( ecLightDir, ecNormal ), 0. ); \n" " color = vec4( vec3( diffuse ), 1. ); \n" " \n" " gl_Position = osg_ModelViewProjectionMatrix * osg_Vertex; \n" "} \n"; osg::Shader *vShader = new osg::Shader(osg::Shader::VERTEX, vertexSource); const std::string fragmentSource = "#version 140 \n" " \n" "in vec4 color; \n" "out vec4 fragData; \n" " \n" "void main() \n" "{ \n" " fragData = color; \n" "} \n"; osg::Shader *fShader = new osg::Shader(osg::Shader::FRAGMENT, fragmentSource); osg::Program *program = new osg::Program; program->addShader(vShader); program->addShader(fShader); stateSet->setAttribute(program); osg::Vec3f lightDir(0., 0.5, 1.); lightDir.normalize(); stateSet->addUniform(new osg::Uniform("ecLightDir", lightDir)); }
void PLANET3::Render() { // Render VBO here glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //These will be replaced by matrix stack soon Mtx44 model; Mtx44 view; Mtx44 projection; model.SetToIdentity(); //Set view matrix using camera settings view.SetToLookAt( camera.position.x, camera.position.y, camera.position.z, camera.target.x, camera.target.y, camera.target.z, camera.up.x, camera.up.y, camera.up.z ); //Set projection matrix to perspective mode projection.SetToPerspective(45.0f, 4.0f / 3.0f, 0.1f, 1000.0f); //FOV, Aspect Ratio, Near plane, Far plane viewStack.LoadIdentity(); viewStack.LookAt(camera.position.x, camera.position.y, camera.position.z, camera.target.x, camera.target.y, camera.target.z, camera.up.x, camera.up.y, camera.up.z); modelStack.LoadIdentity(); Position lightPosition_cameraspace = viewStack.Top() * light[0].position; glUniform3fv(m_parameters[U_LIGHT0_POSITION], 1, &lightPosition_cameraspace.x); Vector3 lightDir(light[1].position.x, light[1].position.y, light[1].position.z); Vector3 lightDirection_cameraspace2 = viewStack.Top() * lightDir; glUniform3fv(m_parameters[U_LIGHT1_POSITION], 1, &lightDirection_cameraspace2.x); RenderMesh(meshList[GEO_AXES], false); modelStack.PushMatrix(); modelStack.Translate(light[0].position.x, light[0].position.y, light[0].position.z); RenderMesh(meshList[GEO_LIGHTBALL], false); modelStack.PopMatrix(); RenderSkyBox(); }
void Scene::setup(Sim* sim) { mSim = sim; mSim->scene = this; // Lighting and sky mSceneMgr->setAmbientLight(Ogre::ColourValue(0.4, 0.4, 0.4)); Ogre::Vector3 lightDir(0.55, -0.3f, 0.75); lightDir.normalise(); sun = mSceneMgr->createLight("SunLight"); sun->setType(Ogre::Light::LT_DIRECTIONAL); sun->setDirection(lightDir); sun->setDiffuseColour(Ogre::ColourValue::White); sun->setSpecularColour(Ogre::ColourValue(0.4, 0.4, 0.4)); mSceneMgr->setSkyDome(true, "CloudySky"); // Terrain mTerrainGlobals = OGRE_NEW Ogre::TerrainGlobalOptions(); mTerrainGroup = OGRE_NEW Ogre::TerrainGroup(mSceneMgr, Ogre::Terrain::ALIGN_X_Z, terrSize, worldSize); configureTerrainDefaults(); defineTerrain(); mTerrainGroup->loadAllTerrains(true); Ogre::TerrainGroup::TerrainIterator ti = mTerrainGroup->getTerrainIterator(); while (ti.hasMoreElements()) { Ogre::Terrain* t = ti.getNext()->instance; t->setVisibilityFlags(RV_Terrain); } mTerrainGroup->freeTemporaryResources(); createBulletTerrain(); // Road // setupRoad(); // Objects setupObjects(); }
Vector SpotLight::calcIntensity( Raytracer* rt, HitProperties const& hp ) const { // calc light vec Vector lightVec( getLightVector( hp ) ); // intensity is normal dot light vector double intensity = hp.normal.dot( lightVec ); if( intensity < 0.0 ) return Vector( 0.0, 0.0, 0.0 ); // get light direction Vector lightDir( getMatrix().getForward() ); // calc angle between lightVec and lightDir // multiplied by 2 because we only calculate half angle but need the total angle double angle = abs( acos( lightVec.dot( lightDir.negated() ) ) * RAD2DEG * 2.0 ); // inside spot area? if( angle < outerAngle ) { // inside fall off area? if( angle > innerAngle ) { // calc linear fall off angle = ( angle - innerAngle ) / ( outerAngle - innerAngle ); intensity *= ( 1.0 - angle ); } } else return Vector( 0.0, 0.0, 0.0 ); // construct ray double dist; Ray r( hp.point, getMatrix().getTranslation(), &dist ); if( getShadowing() && rt->getScene()->intersect( r, dist ) ) return Vector( 0.0, 0.0, 0.0 ); // depends on light dir return color * intensity; }
void Scene::createPolyhedronNode() { _pgeode = new osg::Geode; _pgeode->setDataVariance(osg::Object::DYNAMIC); osg::Vec3f lightDir(0.0f, 0.0f, 1.0f); lightDir.normalize(); auto stateSet = _pgeode->getOrCreateStateSet(); stateSet->setAttributeAndModes(_twoSidedProgram, osg::StateAttribute::ON); stateSet->addUniform(new osg::Uniform("ecLightDirection", lightDir)); stateSet->addUniform(new osg::Uniform("lightColor", osg::Vec3(1.0f, 1.0f, 1.0f))); _pgeometry = new osgKaleido::PolyhedronGeometry("#27"); _pgeometry->setUseDisplayList(false); _pgeometry->setUseVertexBufferObjects(true); _pgeode->addDrawable(_pgeometry); addChild(_pgeode); }
void SceneLight2::lighting() { if (light[0].type == Light::LIGHT_DIRECTIONAL) { Vector3 lightDir(light[0].position.x, light[0].position.y, light[0].position.z); Vector3 lightDirection_cameraspace = viewStack.Top() * lightDir; glUniform3fv(m_parameters[U_LIGHT0_POSITION], 1, &lightDirection_cameraspace.x); } else if (light[0].type == Light::LIGHT_SPOT) { Position lightPosition_cameraspace = viewStack.Top()* light[0].position; glUniform3fv(m_parameters[U_LIGHT0_POSITION], 1, &lightPosition_cameraspace.x); Vector3 spotDirection_cameraspace = viewStack.Top() *light[0].spotDirection; glUniform3fv(m_parameters[U_LIGHT0_SPOTDIRECTION], 1, &spotDirection_cameraspace.x); } else if (light[0].type == Light::LIGHT_POINT) { Position lightPosition_cameraspace = viewStack.Top() * light[0].position; glUniform3fv(m_parameters[U_LIGHT0_POSITION], 1, &lightPosition_cameraspace.x); } }
void intro_do( IDirect3DDevice9 *d3dDevice, float time) { d3dDevice->SetRenderTarget(0, rtScene); d3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0,0,0), 1.0f, 0); d3dDevice->BeginScene(); d3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); d3dDevice->SetRenderState(D3DRS_ZENABLE, FALSE); camera->SetupRenderParameters(d3dDevice); D3DSURFACE_DESC surfDesc; texture->GetLevelDesc(0, &surfDesc); lightTheta += time * LIGHT_SPEED; const float twoPi = 2.0*D3DX_PI; if(lightTheta >= twoPi) lightTheta -= twoPi; D3DXVECTOR3 lightDir(cos(LIGHT_PHI)*cos(lightTheta), sin(LIGHT_PHI), cos(LIGHT_PHI)*sin(lightTheta)); D3DXVECTOR2 texRes(1.0f/(float)surfDesc.Width, 1.0f/(float)surfDesc.Height); D3DXVECTOR2 chamberRes(1.0f/(float)CHAMBER_SIZE, 1.0f/(float)CHAMBER_SIZE); d3dDevice->SetPixelShaderConstantF(6, texRes, 1); d3dDevice->SetPixelShaderConstantF(7, lightDir, 1); d3dDevice->SetVertexShader(gShader->GetVertexShader()); d3dDevice->SetPixelShader(gShader->GetPixelShader()); d3dDevice->SetTexture(0, texture); d3dDevice->SetFVF( D3DFVF_XYZ|D3DFVF_TEX1 ); d3dDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP,2,quadVerts,5*sizeof(float)); d3dDevice->SetRenderTarget(0, backBuffer); d3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0,0,0), 1.0f, 0); sceneTexture->GetLevelDesc(0, &surfDesc); D3DXVECTOR2 invRes(1.0f/(float)surfDesc.Width, 1.0f/(float)surfDesc.Height); d3dDevice->SetPixelShaderConstantF(0, invRes, 1); d3dDevice->SetVertexShader(basic2DShader->GetVertexShader()); d3dDevice->SetPixelShader(basic2DShader->GetPixelShader()); d3dDevice->SetTexture(0, sceneTexture); d3dDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP,2,quadVerts,5*sizeof(float)); d3dDevice->EndScene(); d3dDevice->Present( NULL, NULL, NULL, NULL ); }
void VolRenRaycastCuda::updateCUDALights(const QMatrix4x4& matView) { CudaLight cudaLights[10]; for (unsigned int i = 0; i < lights.size(); ++i) { QVector3D lightDir(matView.inverted() * QVector4D(lights[i].direction, 0.f)); lightDir.normalize(); cudaLights[i].direction.x = lightDir.x(); cudaLights[i].direction.y = lightDir.y(); cudaLights[i].direction.z = lightDir.z(); cudaLights[i].ambient.x = lights[i].color.x() * lights[i].ambient; cudaLights[i].ambient.y = lights[i].color.y() * lights[i].ambient; cudaLights[i].ambient.z = lights[i].color.z() * lights[i].ambient; cudaLights[i].diffuse.x = lights[i].color.x() * lights[i].diffuse; cudaLights[i].diffuse.y = lights[i].color.y() * lights[i].diffuse; cudaLights[i].diffuse.z = lights[i].color.z() * lights[i].diffuse; cudaLights[i].specular.x = lights[i].color.x() * lights[i].specular; cudaLights[i].specular.y = lights[i].color.y() * lights[i].specular; cudaLights[i].specular.z = lights[i].color.z() * lights[i].specular; cudaLights[i].shininess = lights[i].shininess; } cudaSetLights(lights.size(), cudaLights); }
void Credits::Render() { // Render VBO here glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //Set view matrix using camera settings viewStack.LoadIdentity(); viewStack.LookAt( camera.position.x, camera.position.y, camera.position.z, camera.target.x, camera.target.y, camera.target.z, camera.up.x, camera.up.y, camera.up.z ); modelStack.LoadIdentity(); // Light Source 1 if (light[0].type == Light::LIGHT_DIRECTIONAL) { Vector3 lightDir(light[0].position.x, light[0].position.y, light[0].position.z); Vector3 lightDirection_cameraspace = viewStack.Top() * lightDir; glUniform3fv(m_parameters[U_LIGHT0_POSITION], 1, &lightDirection_cameraspace.x); } else if (light[0].type == Light::LIGHT_SPOT) { Position lightPosition_cameraspace = viewStack.Top() * light[0].position; glUniform3fv(m_parameters[U_LIGHT0_POSITION], 1, &lightPosition_cameraspace.x); Vector3 spotDirection_cameraspace = viewStack.Top() * light[0].spotDirection; glUniform3fv(m_parameters[U_LIGHT0_SPOTDIRECTION], 1, &spotDirection_cameraspace.x); } else { Position lightPosition_cameraspace = viewStack.Top() * light[0].position; glUniform3fv(m_parameters[U_LIGHT0_POSITION], 1, &lightPosition_cameraspace.x); } RenderCredits(); }
void SceneText::Render() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); Mtx44 perspective; perspective.SetToPerspective(45.0f, 4.0f / 3.0f, 0.1f, 10000.0f); //perspective.SetToOrtho(-80, 80, -60, 60, -1000, 1000); projectionStack.LoadMatrix(perspective); // Camera matrix viewStack.LoadIdentity(); viewStack.LookAt( camera.position.x, camera.position.y, camera.position.z, camera.target.x, camera.target.y, camera.target.z, camera.up.x, camera.up.y, camera.up.z ); // Model matrix : an identity matrix (model will be at the origin) modelStack.LoadIdentity(); if(lights[0].type == Light::LIGHT_DIRECTIONAL) { Vector3 lightDir(lights[0].position.x, lights[0].position.y, lights[0].position.z); Vector3 lightDirection_cameraspace = viewStack.Top() * lightDir; glUniform3fv(m_parameters[U_LIGHT0_POSITION], 1, &lightDirection_cameraspace.x); } else if(lights[0].type == Light::LIGHT_SPOT) { Position lightPosition_cameraspace = viewStack.Top() * lights[0].position; glUniform3fv(m_parameters[U_LIGHT0_POSITION], 1, &lightPosition_cameraspace.x); Vector3 spotDirection_cameraspace = viewStack.Top() * lights[0].spotDirection; glUniform3fv(m_parameters[U_LIGHT0_SPOTDIRECTION], 1, &spotDirection_cameraspace.x); } else { Position lightPosition_cameraspace = viewStack.Top() * lights[0].position; glUniform3fv(m_parameters[U_LIGHT0_POSITION], 1, &lightPosition_cameraspace.x); } if(lights[1].type == Light::LIGHT_DIRECTIONAL) { Vector3 lightDir(lights[1].position.x, lights[1].position.y, lights[1].position.z); Vector3 lightDirection_cameraspace = viewStack.Top() * lightDir; glUniform3fv(m_parameters[U_LIGHT1_POSITION], 1, &lightDirection_cameraspace.x); } else if(lights[1].type == Light::LIGHT_SPOT) { Position lightPosition_cameraspace = viewStack.Top() * lights[1].position; glUniform3fv(m_parameters[U_LIGHT1_POSITION], 1, &lightPosition_cameraspace.x); Vector3 spotDirection_cameraspace = viewStack.Top() * lights[1].spotDirection; glUniform3fv(m_parameters[U_LIGHT1_SPOTDIRECTION], 1, &spotDirection_cameraspace.x); } else { Position lightPosition_cameraspace = viewStack.Top() * lights[1].position; glUniform3fv(m_parameters[U_LIGHT1_POSITION], 1, &lightPosition_cameraspace.x); } RenderMesh(meshList[GEO_AXES], false); modelStack.PushMatrix(); modelStack.Translate(lights[0].position.x, lights[0].position.y, lights[0].position.z); RenderMesh(meshList[GEO_LIGHTBALL], false); modelStack.PopMatrix(); RenderSkybox(); // perspective; ////perspective.SetToPerspective(45.0f, 4.0f / 3.0f, 0.1f, 10000.0f); //perspective.SetToOrtho(-80, 80, -60, 60, -1000, 1000); //projectionStack.LoadMatrix(perspective); //viewStack.LoadIdentity(); // //modelStack.PushMatrix(); ////modelStack.Translate(20, 0, -20); ////modelStack.Scale(0.1f, 0.1f, 0.1f); //modelStack.Scale(50, 50, 50); ////RenderMesh(meshList[GEO_QUAD], false); //RenderText(meshList[GEO_TEXT], "HelloWorld", Color(0, 1, 0)); //modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(-20, 0, -20); RenderMesh(meshList[GEO_OBJECT], false); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(20, 0, -20); RenderMesh(meshList[GEO_OBJECT], true); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Scale(10, 10, 10); //RenderText(meshList[GEO_TEXT], "Hello World", Color(0, 1, 0)); RenderText(meshList[GEO_TEXT], "Hello World", Color(0, 1, 0)); modelStack.PopMatrix(); //On screen text std::ostringstream ss; ss.precision(5); ss << "FPS: " << fps; RenderTextOnScreen(meshList[GEO_TEXT], ss.str(), Color(0, 1, 0), 3, 0, 6); std::ostringstream ss1; ss1.precision(4); ss1 << "Light(" << lights[0].position.x << ", " << lights[0].position.y << ", " << lights[0].position.z << ")"; RenderTextOnScreen(meshList[GEO_TEXT], ss1.str(), Color(0, 1, 0), 3, 0, 3); RenderTextOnScreen(meshList[GEO_TEXT], "Hello Screen", Color(0, 1, 0), 3, 0, 0); RenderMeshIn2D(meshList[GEO_CROSSHAIR], false,1,1,1); }
void PLANET5::Render() { // Render VBO here glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //These will be replaced by matrix stack soon Mtx44 model; Mtx44 view; Mtx44 projection; model.SetToIdentity(); //Set view matrix using camera settings view.SetToLookAt( camera.position.x, camera.position.y, camera.position.z, camera.target.x, camera.target.y, camera.target.z, camera.up.x, camera.up.y, camera.up.z ); //Set projection matrix to perspective mode projection.SetToPerspective(45.0f, 4.0f / 3.0f, 0.1f, 1000.0f); //FOV, Aspect Ratio, Near plane, Far plane viewStack.LoadIdentity(); viewStack.LookAt(camera.position.x, camera.position.y, camera.position.z, camera.target.x, camera.target.y, camera.target.z, camera.up.x, camera.up.y, camera.up.z); modelStack.LoadIdentity(); Position lightPosition_cameraspace = viewStack.Top() * light[0].position; glUniform3fv(m_parameters[U_LIGHT0_POSITION], 1, &lightPosition_cameraspace.x); Vector3 lightDir(light[1].position.x, light[1].position.y, light[1].position.z); Vector3 lightDirection_cameraspace2 = viewStack.Top() * lightDir; glUniform3fv(m_parameters[U_LIGHT1_POSITION], 1, &lightDirection_cameraspace2.x); RenderMesh(meshList[GEO_AXES], false); /*modelStack.PushMatrix(); modelStack.Translate(light[0].position.x, light[0].position.y, light[0].position.z); RenderMesh(meshList[GEO_LIGHTBALL], false); modelStack.PopMatrix(); /* modelStack.PushMatrix(); modelStack.Translate(0.f, 0.f, 0.f); RenderMesh(meshList[ASTEROID], false); modelStack.PopMatrix();*/ std::ostringstream fps; fps << camera.position.x << " " << camera.position.y << " " << camera.position.z; std::ostringstream fpss; fpss << camera.target.x << " " << camera.target.y << " " << camera.target.z; RenderSkyBox(); modelStack.PushMatrix(); modelStack.Translate(0.0f, -35.0f, 0.f); modelStack.Rotate(rotatespin - 45, 0, 1, 0); modelStack.Scale(22.0f, 24.0f, 22.0f); RenderMesh(meshList[SPIN], false); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(0.0f, 8.0f, 0.f); modelStack.Scale(10.0f, 10.f, 10.f); RenderMesh(meshList[SPINCAP], false); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(5.0f, translateButton - 6.f, 43.5f); modelStack.Rotate(25.0f, 1, 0, 0); modelStack.Scale(2.f, 3.0f, 2.f); RenderMesh(meshList[BUTTON], false); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(5.0f, -6.0f, 45.0f); modelStack.Rotate(-90.0f, 0, 1, 0); modelStack.Scale(2.0f, 2.0f, 2.0f); RenderMesh(meshList[BUTTONSTAND], false); modelStack.PopMatrix(); //////////////////////GEMS ARE OUTRAGREOUS////////////////////////// modelStack.PushMatrix(); modelStack.Translate(-50.0f, translategem1 - 5.7f, -81.5f); modelStack.Rotate(22.0f, 1, 0, 0); modelStack.Scale(2.f, 3.0f, 2.f); RenderMesh(meshList[BUTTON], false); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(-50.0f, -6.0f, -80.0f); modelStack.Rotate(-90.0f, 0, 1, 0); modelStack.Scale(2.0f, 2.0f, 2.0f); RenderMesh(meshList[BUTTONSTAND], false); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(-50.0f, flygem1, -90.0f); modelStack.Rotate(rotategem1, 0, 1, 0); modelStack.Scale(2.f, 3.0f, 2.f); RenderMesh(meshList[GEM], true); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(-50.0f, -5.0f, -90.0f); modelStack.Scale(2.f, 2.0f, 2.f); RenderMesh(meshList[GEMCASE], true); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(-25.0f, translategem2 - 5.7f, -81.5f); modelStack.Rotate(22.0f, 1, 0, 0); modelStack.Scale(2.f, 3.0f, 2.f); RenderMesh(meshList[BUTTON], false); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(-25.0f, -6.0f, -80.0f); modelStack.Rotate(-90.0f, 0, 1, 0); modelStack.Scale(2.0f, 2.0f, 2.0f); RenderMesh(meshList[BUTTONSTAND], false); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(-25.0f, flygem2, -90.0f); modelStack.Rotate(rotategem2, 0, 1, 0); modelStack.Scale(2.f, 3.0f, 2.f); RenderMesh(meshList[GEM2], true); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(-25.0f, -5.0f, -90.0f); modelStack.Scale(2.f, 2.0f, 2.f); RenderMesh(meshList[GEMCASE], true); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(0.0f, translategem3 - 5.7f, -81.5f); modelStack.Rotate(22.0f, 1, 0, 0); modelStack.Scale(2.f, 3.0f, 2.f); RenderMesh(meshList[BUTTON], false); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(0.0f, -6.0f, -80.0f); modelStack.Rotate(-90.0f, 0, 1, 0); modelStack.Scale(2.0f, 2.0f, 2.0f); RenderMesh(meshList[BUTTONSTAND], false); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(0.0f, flygem3, -90.0f); modelStack.Rotate(rotategem3, 0, 1, 0); modelStack.Scale(2.f, 3.0f, 2.f); RenderMesh(meshList[GEM3], true); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(0.0f, -5.0f, -90.0f); modelStack.Scale(2.f, 2.0f, 2.f); RenderMesh(meshList[GEMCASE], true); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(25.0f, translategem4 - 5.7f, -81.5f); modelStack.Rotate(22.0f, 1, 0, 0); modelStack.Scale(2.f, 3.0f, 2.f); RenderMesh(meshList[BUTTON], false); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(25.0f, -6.0f, -80.0f); modelStack.Rotate(-90.0f, 0, 1, 0); modelStack.Scale(2.0f, 2.0f, 2.0f); RenderMesh(meshList[BUTTONSTAND], false); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(25.0f, flygem4, -90.0f); modelStack.Rotate(rotategem4, 0, 2, 0); modelStack.Scale(2.f, 3.0f, 2.f); RenderMesh(meshList[GEM4], true); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(25.0f, -5.0f, -90.0f); modelStack.Scale(2.f, 2.0f, 2.f); RenderMesh(meshList[GEMCASE], true); modelStack.PopMatrix(); //////////////////////THEY ARE TRULY, TRULY, TRULY OUTRAGREOUS////////////////////////// modelStack.PushMatrix(); modelStack.Translate(-10.0f, translateEND, -123.0f); modelStack.Scale(scaleFinish, scaleFinish, scaleFinish); RenderMesh(meshList[END], true); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(124.0f, 12.0f, -40.f); modelStack.Rotate(-90.0f, 0, 1, 0); modelStack.Scale(10.0f, 10.0f, 3.0f); RenderMesh(meshList[PICFRAME], false); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(124.0f, 12.0f, 40.f); modelStack.Rotate(-90.0f, 0, 1, 0); modelStack.Scale(10.0f, 10.0f, 3.0f); RenderMesh(meshList[PICFRAME], false); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(-124.0f, 12.0f, -40.f); modelStack.Rotate(90.0f, 0, 1, 0); modelStack.Scale(10.0f, 10.0f, 3.0f); RenderMesh(meshList[PICFRAME], false); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(-124.0f, 12.0f, 40.f); modelStack.Rotate(90.0f, 0, 1, 0); modelStack.Scale(10.0f, 10.0f, 3.0f); RenderMesh(meshList[PICFRAME], false); modelStack.PopMatrix(); RenderHandOnScreen(); RenderTextOnScreen(meshList[POSITION], fps.str(), Color(0, 1, 1), 3, 10, 10); RenderTextOnScreen(meshList[POSITION], fpss.str(), Color(0, 1, 1), 3, 10, 7); }
int main(int argc, char** argv) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc, argv); // set up the usage document, in case we need to print out how to use this program. arguments.getApplicationUsage()->setDescription(arguments.getApplicationName() + " is the example which demonstrates using of GL_ARB_shadow extension implemented in osg::Texture class"); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()); arguments.getApplicationUsage()->addCommandLineOption("-h or --help", "Display this information"); arguments.getApplicationUsage()->addCommandLineOption("--positionalLight", "Use a positional light."); arguments.getApplicationUsage()->addCommandLineOption("--directionalLight", "Use a direction light."); arguments.getApplicationUsage()->addCommandLineOption("--noUpdate", "Disable the updating the of light source."); arguments.getApplicationUsage()->addCommandLineOption("--castsShadowMask", "Override default castsShadowMask (default - 0x2)"); arguments.getApplicationUsage()->addCommandLineOption("--receivesShadowMask", "Override default receivesShadowMask (default - 0x1)"); arguments.getApplicationUsage()->addCommandLineOption("--base", "Add a base geometry to test shadows."); arguments.getApplicationUsage()->addCommandLineOption("--sv", "Select ShadowVolume implementation."); arguments.getApplicationUsage()->addCommandLineOption("--ssm", "Select SoftShadowMap implementation."); arguments.getApplicationUsage()->addCommandLineOption("--sm", "Select ShadowMap implementation."); arguments.getApplicationUsage()->addCommandLineOption("--pssm", "Select ParallelSplitShadowMap implementation.");//ADEGLI arguments.getApplicationUsage()->addCommandLineOption("--mapcount", "ParallelSplitShadowMap texture count.");//ADEGLI arguments.getApplicationUsage()->addCommandLineOption("--mapres", "ParallelSplitShadowMap texture resolution.");//ADEGLI arguments.getApplicationUsage()->addCommandLineOption("--debug-color", "ParallelSplitShadowMap display debugging color (only the first 3 maps are color r=0,g=1,b=2.");//ADEGLI arguments.getApplicationUsage()->addCommandLineOption("--minNearSplit", "ParallelSplitShadowMap shadow map near offset.");//ADEGLI arguments.getApplicationUsage()->addCommandLineOption("--maxFarDist", "ParallelSplitShadowMap max far distance to shadow.");//ADEGLI arguments.getApplicationUsage()->addCommandLineOption("--moveVCamFactor", "ParallelSplitShadowMap move the virtual frustum behind the real camera, (also back ground object can cast shadow).");//ADEGLI arguments.getApplicationUsage()->addCommandLineOption("--PolyOffset-Factor", "ParallelSplitShadowMap set PolygonOffset factor.");//ADEGLI arguments.getApplicationUsage()->addCommandLineOption("--PolyOffset-Unit", "ParallelSplitShadowMap set PolygonOffset unit.");//ADEGLI arguments.getApplicationUsage()->addCommandLineOption("--lispsm", "Select LightSpacePerspectiveShadowMap implementation."); arguments.getApplicationUsage()->addCommandLineOption("--msm", "Select MinimalShadowMap implementation."); arguments.getApplicationUsage()->addCommandLineOption("--ViewBounds", "MSM, LiSPSM optimize shadow for view frustum (weakest option)"); arguments.getApplicationUsage()->addCommandLineOption("--CullBounds", "MSM, LiSPSM optimize shadow for bounds of culled objects in view frustum (better option)."); arguments.getApplicationUsage()->addCommandLineOption("--DrawBounds", "MSM, LiSPSM optimize shadow for bounds of predrawn pixels in view frustum (best & default)."); arguments.getApplicationUsage()->addCommandLineOption("--mapres", "MSM, LiSPSM & texture resolution."); arguments.getApplicationUsage()->addCommandLineOption("--maxFarDist", "MSM, LiSPSM max far distance to shadow."); arguments.getApplicationUsage()->addCommandLineOption("--moveVCamFactor", "MSM, LiSPSM move the virtual frustum behind the real camera, (also back ground object can cast shadow)."); arguments.getApplicationUsage()->addCommandLineOption("--minLightMargin", "MSM, LiSPSM the same as --moveVCamFactor."); arguments.getApplicationUsage()->addCommandLineOption("-1", "Use test model one."); arguments.getApplicationUsage()->addCommandLineOption("-2", "Use test model two."); arguments.getApplicationUsage()->addCommandLineOption("-3", "Use test model three (default)."); arguments.getApplicationUsage()->addCommandLineOption("-4", "Use test model four - island scene."); arguments.getApplicationUsage()->addCommandLineOption("--two-sided", "Use two-sided stencil extension for shadow volumes."); arguments.getApplicationUsage()->addCommandLineOption("--two-pass", "Use two-pass stencil for shadow volumes."); arguments.getApplicationUsage()->addCommandLineOption("--near-far-mode","COMPUTE_NEAR_USING_PRIMITIVES, COMPUTE_NEAR_FAR_USING_PRIMITIVES, COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES, DO_NOT_COMPUTE_NEAR_FAR"); arguments.getApplicationUsage()->addCommandLineOption("--max-shadow-distance","<float> Maximum distance that the shadow map should extend from the eye point."); // construct the viewer. osgViewer::Viewer viewer(arguments); // if user request help write it out to cout. if (arguments.read("-h") || arguments.read("--help")) { arguments.getApplicationUsage()->write(std::cout); return 1; } double zNear=1.0, zMid=10.0, zFar=1000.0; if (arguments.read("--depth-partition",zNear, zMid, zFar)) { // set up depth partitioning osg::ref_ptr<osgViewer::DepthPartitionSettings> dps = new osgViewer::DepthPartitionSettings; dps->_mode = osgViewer::DepthPartitionSettings::FIXED_RANGE; dps->_zNear = zNear; dps->_zMid = zMid; dps->_zFar = zFar; viewer.setUpDepthPartition(dps.get()); } if (arguments.read("--dp")) { // set up depth partitioning viewer.setUpDepthPartition(); } float fov = 0.0; while (arguments.read("--fov",fov)) {} osg::Vec4 lightpos(0.0,0.0,1,0.0); bool spotlight = false; while (arguments.read("--positionalLight")) { lightpos.set(0.5,0.5,1.5,1.0); } while (arguments.read("--directionalLight")) { lightpos.set(0.0,0.0,1,0.0); } while (arguments.read("--spotLight")) { lightpos.set(0.5,0.5,1.5,1.0); spotlight = true; } bool keepLightPos = false; osg::Vec3 spotLookat(0.0,0.0,0.0); while ( arguments.read("--light-pos", lightpos.x(), lightpos.y(), lightpos.z(), lightpos.w())) { keepLightPos = true; } while ( arguments.read("--light-pos", lightpos.x(), lightpos.y(), lightpos.z())) { lightpos.w()=1.0; keepLightPos = true; } while ( arguments.read("--light-dir", lightpos.x(), lightpos.y(), lightpos.z())) { lightpos.w()=0.0; keepLightPos = true; } while ( arguments.read("--spot-lookat", spotLookat.x(), spotLookat.y(), spotLookat.z())) { } while (arguments.read("--castsShadowMask", CastsShadowTraversalMask )); while (arguments.read("--receivesShadowMask", ReceivesShadowTraversalMask )); bool updateLightPosition = true; while (arguments.read("--noUpdate")) updateLightPosition = false; // set up the camera manipulators. { osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator; keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() ); keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() ); keyswitchManipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() ); keyswitchManipulator->addMatrixManipulator( '4', "Terrain", new osgGA::TerrainManipulator() ); std::string pathfile; char keyForAnimationPath = '5'; while (arguments.read("-p",pathfile)) { osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile); if (apm || !apm->valid()) { unsigned int num = keyswitchManipulator->getNumMatrixManipulators(); keyswitchManipulator->addMatrixManipulator( keyForAnimationPath, "Path", apm ); keyswitchManipulator->selectMatrixManipulator(num); ++keyForAnimationPath; } } viewer.setCameraManipulator( keyswitchManipulator.get() ); } // add the state manipulator viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) ); // add stats viewer.addEventHandler( new osgViewer::StatsHandler() ); // add the record camera path handler viewer.addEventHandler(new osgViewer::RecordCameraPathHandler); // add the window size toggle handler viewer.addEventHandler(new osgViewer::WindowSizeHandler); // add the threading handler viewer.addEventHandler( new osgViewer::ThreadingHandler() ); osg::ref_ptr<osgShadow::ShadowedScene> shadowedScene = new osgShadow::ShadowedScene; osgShadow::ShadowSettings* settings = shadowedScene->getShadowSettings(); settings->setReceivesShadowTraversalMask(ReceivesShadowTraversalMask); settings->setCastsShadowTraversalMask(CastsShadowTraversalMask); std::string nearFarMode(""); if (arguments.read("--near-far-mode",nearFarMode)) { if (nearFarMode=="COMPUTE_NEAR_USING_PRIMITIVES") settings->setComputeNearFarModeOverride(osg::CullSettings::COMPUTE_NEAR_USING_PRIMITIVES); else if (nearFarMode=="COMPUTE_NEAR_FAR_USING_PRIMITIVES") settings->setComputeNearFarModeOverride(osg::CullSettings::COMPUTE_NEAR_FAR_USING_PRIMITIVES); else if (nearFarMode=="DO_NOT_COMPUTE_NEAR_FAR") settings->setComputeNearFarModeOverride(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR); else if (nearFarMode=="COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES") settings->setComputeNearFarModeOverride(osg::CullSettings::COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES); OSG_NOTICE<<"ComputeNearFarModeOverride set to "; switch(settings->getComputeNearFarModeOverride()) { case(osg::CullSettings::COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES): OSG_NOTICE<<"COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES"; break; case(osg::CullSettings::COMPUTE_NEAR_USING_PRIMITIVES): OSG_NOTICE<<"COMPUTE_NEAR_USING_PRIMITIVES"; break; case(osg::CullSettings::COMPUTE_NEAR_FAR_USING_PRIMITIVES): OSG_NOTICE<<"COMPUTE_NEAR_FAR_USING_PRIMITIVES"; break; case(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR): OSG_NOTICE<<"DO_NOT_COMPUTE_NEAR_FAR"; break; } OSG_NOTICE<<std::endl; } double distance; if (arguments.read("--max-shadow-distance",distance)) { settings->setMaximumShadowMapDistance(distance); OSG_NOTICE<<"MaximumShadowMapDistance set to "<<settings->getMaximumShadowMapDistance()<<std::endl; } osg::ref_ptr<osgShadow::MinimalShadowMap> msm = NULL; if (arguments.read("--no-shadows")) { OSG_NOTICE<<"Not using a ShadowTechnique"<<std::endl; shadowedScene->setShadowTechnique(0); } else if (arguments.read("--sv")) { // hint to tell viewer to request stencil buffer when setting up windows osg::DisplaySettings::instance()->setMinimumNumStencilBits(8); osg::ref_ptr<osgShadow::ShadowVolume> sv = new osgShadow::ShadowVolume; sv->setDynamicShadowVolumes(updateLightPosition); while (arguments.read("--two-sided")) sv->setDrawMode(osgShadow::ShadowVolumeGeometry::STENCIL_TWO_SIDED); while (arguments.read("--two-pass")) sv->setDrawMode(osgShadow::ShadowVolumeGeometry::STENCIL_TWO_PASS); shadowedScene->setShadowTechnique(sv.get()); } else if (arguments.read("--st")) { osg::ref_ptr<osgShadow::ShadowTexture> st = new osgShadow::ShadowTexture; shadowedScene->setShadowTechnique(st.get()); } else if (arguments.read("--stsm")) { osg::ref_ptr<osgShadow::StandardShadowMap> st = new osgShadow::StandardShadowMap; shadowedScene->setShadowTechnique(st.get()); } else if (arguments.read("--pssm")) { int mapcount = 3; while (arguments.read("--mapcount", mapcount)); osg::ref_ptr<osgShadow::ParallelSplitShadowMap> pssm = new osgShadow::ParallelSplitShadowMap(NULL,mapcount); int mapres = 1024; while (arguments.read("--mapres", mapres)) pssm->setTextureResolution(mapres); while (arguments.read("--debug-color")) { pssm->setDebugColorOn(); } int minNearSplit=0; while (arguments.read("--minNearSplit", minNearSplit)) if ( minNearSplit > 0 ) { pssm->setMinNearDistanceForSplits(minNearSplit); std::cout << "ParallelSplitShadowMap : setMinNearDistanceForSplits(" << minNearSplit <<")" << std::endl; } int maxfardist = 0; while (arguments.read("--maxFarDist", maxfardist)) if ( maxfardist > 0 ) { pssm->setMaxFarDistance(maxfardist); std::cout << "ParallelSplitShadowMap : setMaxFarDistance(" << maxfardist<<")" << std::endl; } int moveVCamFactor = 0; while (arguments.read("--moveVCamFactor", moveVCamFactor)) if ( maxfardist > 0 ) { pssm->setMoveVCamBehindRCamFactor(moveVCamFactor); std::cout << "ParallelSplitShadowMap : setMoveVCamBehindRCamFactor(" << moveVCamFactor<<")" << std::endl; } double polyoffsetfactor = pssm->getPolygonOffset().x(); double polyoffsetunit = pssm->getPolygonOffset().y(); while (arguments.read("--PolyOffset-Factor", polyoffsetfactor)); while (arguments.read("--PolyOffset-Unit", polyoffsetunit)); pssm->setPolygonOffset(osg::Vec2(polyoffsetfactor,polyoffsetunit)); shadowedScene->setShadowTechnique(pssm.get()); } else if (arguments.read("--ssm")) { osg::ref_ptr<osgShadow::SoftShadowMap> sm = new osgShadow::SoftShadowMap; shadowedScene->setShadowTechnique(sm.get()); } else if( arguments.read("--vdsm") ) { while( arguments.read("--debugHUD") ) settings->setDebugDraw( true ); if (arguments.read("--persp")) settings->setShadowMapProjectionHint(osgShadow::ShadowSettings::PERSPECTIVE_SHADOW_MAP); if (arguments.read("--ortho")) settings->setShadowMapProjectionHint(osgShadow::ShadowSettings::ORTHOGRAPHIC_SHADOW_MAP); unsigned int unit=1; if (arguments.read("--unit",unit)) settings->setBaseShadowTextureUnit(unit); double n=0.0; if (arguments.read("-n",n)) settings->setMinimumShadowMapNearFarRatio(n); unsigned int numShadowMaps; if (arguments.read("--num-sm",numShadowMaps)) settings->setNumShadowMapsPerLight(numShadowMaps); if (arguments.read("--parallel-split") || arguments.read("--ps") ) settings->setMultipleShadowMapHint(osgShadow::ShadowSettings::PARALLEL_SPLIT); if (arguments.read("--cascaded")) settings->setMultipleShadowMapHint(osgShadow::ShadowSettings::CASCADED); int mapres = 1024; while (arguments.read("--mapres", mapres)) settings->setTextureSize(osg::Vec2s(mapres,mapres)); osg::ref_ptr<osgShadow::ViewDependentShadowMap> vdsm = new osgShadow::ViewDependentShadowMap; shadowedScene->setShadowTechnique(vdsm.get()); } else if ( arguments.read("--lispsm") ) { if( arguments.read( "--ViewBounds" ) ) msm = new osgShadow::LightSpacePerspectiveShadowMapVB; else if( arguments.read( "--CullBounds" ) ) msm = new osgShadow::LightSpacePerspectiveShadowMapCB; else // if( arguments.read( "--DrawBounds" ) ) // default msm = new osgShadow::LightSpacePerspectiveShadowMapDB; } else if( arguments.read("--msm") ) { if( arguments.read( "--ViewBounds" ) ) msm = new osgShadow::MinimalShadowMap; else if( arguments.read( "--CullBounds" ) ) msm = new osgShadow::MinimalCullBoundsShadowMap; else // if( arguments.read( "--DrawBounds" ) ) // default msm = new osgShadow::MinimalDrawBoundsShadowMap; } else /* if (arguments.read("--sm")) */ { osg::ref_ptr<osgShadow::ShadowMap> sm = new osgShadow::ShadowMap; shadowedScene->setShadowTechnique(sm.get()); int mapres = 1024; while (arguments.read("--mapres", mapres)) sm->setTextureSize(osg::Vec2s(mapres,mapres)); } if( msm )// Set common MSM & LISPSM arguments { shadowedScene->setShadowTechnique( msm.get() ); while( arguments.read("--debugHUD") ) msm->setDebugDraw( true ); float minLightMargin = 10.f; float maxFarPlane = 0; unsigned int texSize = 1024; unsigned int baseTexUnit = 0; unsigned int shadowTexUnit = 1; while ( arguments.read("--moveVCamFactor", minLightMargin ) ); while ( arguments.read("--minLightMargin", minLightMargin ) ); while ( arguments.read("--maxFarDist", maxFarPlane ) ); while ( arguments.read("--mapres", texSize )); while ( arguments.read("--baseTextureUnit", baseTexUnit) ); while ( arguments.read("--shadowTextureUnit", shadowTexUnit) ); msm->setMinLightMargin( minLightMargin ); msm->setMaxFarPlane( maxFarPlane ); msm->setTextureSize( osg::Vec2s( texSize, texSize ) ); msm->setShadowTextureCoordIndex( shadowTexUnit ); msm->setShadowTextureUnit( shadowTexUnit ); msm->setBaseTextureCoordIndex( baseTexUnit ); msm->setBaseTextureUnit( baseTexUnit ); } OSG_INFO<<"shadowedScene->getShadowTechnique()="<<shadowedScene->getShadowTechnique()<<std::endl; osg::ref_ptr<osg::Node> model = osgDB::readNodeFiles(arguments); if (model.valid()) { model->setNodeMask(CastsShadowTraversalMask | ReceivesShadowTraversalMask); } else { model = createTestModel(arguments); } // get the bounds of the model. osg::ComputeBoundsVisitor cbbv; model->accept(cbbv); osg::BoundingBox bb = cbbv.getBoundingBox(); if (lightpos.w()==1.0 && !keepLightPos) { lightpos.x() = bb.xMin()+(bb.xMax()-bb.xMin())*lightpos.x(); lightpos.y() = bb.yMin()+(bb.yMax()-bb.yMin())*lightpos.y(); lightpos.z() = bb.zMin()+(bb.zMax()-bb.zMin())*lightpos.z(); } if ( arguments.read("--base")) { osg::Geode* geode = new osg::Geode; osg::Vec3 widthVec(bb.radius(), 0.0f, 0.0f); osg::Vec3 depthVec(0.0f, bb.radius(), 0.0f); osg::Vec3 centerBase( (bb.xMin()+bb.xMax())*0.5f, (bb.yMin()+bb.yMax())*0.5f, bb.zMin()-bb.radius()*0.1f ); geode->addDrawable( osg::createTexturedQuadGeometry( centerBase-widthVec*1.5f-depthVec*1.5f, widthVec*3.0f, depthVec*3.0f) ); geode->setNodeMask(shadowedScene->getReceivesShadowTraversalMask()); geode->getOrCreateStateSet()->setTextureAttributeAndModes(0, new osg::Texture2D(osgDB::readImageFile("Images/lz.rgb"))); shadowedScene->addChild(geode); } osg::ref_ptr<osg::LightSource> ls = new osg::LightSource; ls->getLight()->setPosition(lightpos); if (spotlight) { osg::Vec3 center = spotLookat; osg::Vec3 lightdir = center - osg::Vec3(lightpos.x(), lightpos.y(), lightpos.z()); lightdir.normalize(); ls->getLight()->setDirection(lightdir); ls->getLight()->setSpotCutoff(25.0f); //set the LightSource, only for checking, there is only 1 light in the scene osgShadow::ShadowMap* shadowMap = dynamic_cast<osgShadow::ShadowMap*>(shadowedScene->getShadowTechnique()); if( shadowMap ) shadowMap->setLight(ls.get()); } if ( arguments.read("--coloured-light")) { ls->getLight()->setAmbient(osg::Vec4(1.0,0.0,0.0,1.0)); ls->getLight()->setDiffuse(osg::Vec4(0.0,1.0,0.0,1.0)); } else { ls->getLight()->setAmbient(osg::Vec4(0.2,0.2,0.2,1.0)); ls->getLight()->setDiffuse(osg::Vec4(0.8,0.8,0.8,1.0)); } shadowedScene->addChild(model.get()); shadowedScene->addChild(ls.get()); viewer.setSceneData(shadowedScene.get()); osg::ref_ptr< DumpShadowVolumesHandler > dumpShadowVolumes = new DumpShadowVolumesHandler; viewer.addEventHandler(new ChangeFOVHandler(viewer.getCamera())); viewer.addEventHandler( dumpShadowVolumes.get() ); // create the windows and run the threads. viewer.realize(); if (fov!=0.0) { double fovy, aspectRatio, zNear, zFar; viewer.getCamera()->getProjectionMatrix().getPerspective(fovy, aspectRatio, zNear, zFar); std::cout << "Setting FOV to " << fov << std::endl; viewer.getCamera()->getProjectionMatrix().makePerspective(fov, aspectRatio, zNear, zFar); } // it is done after viewer.realize() so that the windows are already initialized if ( arguments.read("--debugHUD")) { osgViewer::Viewer::Windows windows; viewer.getWindows(windows); if (windows.empty()) return 1; osgShadow::ShadowMap* sm = dynamic_cast<osgShadow::ShadowMap*>(shadowedScene->getShadowTechnique()); if( sm ) { osg::ref_ptr<osg::Camera> hudCamera = sm->makeDebugHUD(); // set up cameras to rendering on the first window available. hudCamera->setGraphicsContext(windows[0]); hudCamera->setViewport(0,0,windows[0]->getTraits()->width, windows[0]->getTraits()->height); viewer.addSlave(hudCamera.get(), false); } } osg::ref_ptr<LightAnimationHandler> lightAnimationHandler = updateLightPosition ? new LightAnimationHandler : 0; if (lightAnimationHandler) viewer.addEventHandler(lightAnimationHandler.get()); // osgDB::writeNodeFile(*group,"test.osgt"); while (!viewer.done()) { { osgShadow::MinimalShadowMap * msm = dynamic_cast<osgShadow::MinimalShadowMap*>( shadowedScene->getShadowTechnique() ); if( msm ) { // If scene decorated by CoordinateSystemNode try to find localToWorld // and set modellingSpaceToWorld matrix to optimize scene bounds computation osg::NodePath np = viewer.getCoordinateSystemNodePath(); if( !np.empty() ) { osg::CoordinateSystemNode * csn = dynamic_cast<osg::CoordinateSystemNode *>( np.back() ); if( csn ) { osg::Vec3d pos = viewer.getCameraManipulator()->getMatrix().getTrans(); msm->setModellingSpaceToWorldTransform ( csn->computeLocalCoordinateFrame( pos ) ); } } } } if (lightAnimationHandler.valid() && lightAnimationHandler ->getAnimating()) { float t = viewer.getFrameStamp()->getSimulationTime(); if (lightpos.w()==1.0) { lightpos.set(bb.center().x()+sinf(t)*bb.radius(), bb.center().y() + cosf(t)*bb.radius(), bb.zMax() + bb.radius()*3.0f ,1.0f); } else { lightpos.set(sinf(t),cosf(t),1.0f,0.0f); } ls->getLight()->setPosition(lightpos); osg::Vec3f lightDir(-lightpos.x(),-lightpos.y(),-lightpos.z()); if(spotlight) lightDir = osg::Vec3(bb.center().x()+sinf(t)*bb.radius()/2.0, bb.center().y() + cosf(t)*bb.radius()/2.0, bb.center().z()) - osg::Vec3(lightpos.x(), lightpos.y(), lightpos.z()) ; lightDir.normalize(); ls->getLight()->setDirection(lightDir); } if( dumpShadowVolumes->get() ) { dumpShadowVolumes->set( false ); static int dumpFileNo = 0; dumpFileNo ++; char filename[256]; std::sprintf( filename, "shadowDump%d.osgt", dumpFileNo ); osgShadow::MinimalShadowMap * msm = dynamic_cast<osgShadow::MinimalShadowMap*>( shadowedScene->getShadowTechnique() ); if( msm ) msm->setDebugDump( filename ); } viewer.frame(); } return 0; }
void SceneTexture::Render() { // Render VBO here glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //Set view matrix using camera settings viewStack.LoadIdentity(); viewStack.LookAt( camera.position.x, camera.position.y, camera.position.z, camera.target.x, camera.target.y, camera.target.z, camera.up.x, camera.up.y, camera.up.z ); modelStack.LoadIdentity(); //new code if (light[0].type == Light::LIGHT_DIRECTIONAL) { Vector3 lightDir(light[0].position.x, light[0].position.y, light[0].position.z); Vector3 lightDirection_cameraspace = viewStack.Top() * lightDir; glUniform3fv(m_parameters[U_LIGHT0_POSITION], 1, &lightDirection_cameraspace.x); } else if (light[0].type == Light::LIGHT_SPOT) { Position lightPosition_cameraspace = viewStack.Top() * light[0].position; glUniform3fv(m_parameters[U_LIGHT0_POSITION], 1, &lightPosition_cameraspace.x); Vector3 spotDirection_cameraspace = viewStack.Top() * light[0].spotDirection; glUniform3fv(m_parameters[U_LIGHT0_SPOTDIRECTION], 1, &spotDirection_cameraspace.x); } else { Position lightPosition_cameraspace = viewStack.Top() * light[0].position; glUniform3fv(m_parameters[U_LIGHT0_POSITION], 1, &lightPosition_cameraspace.x); } if (light[1].type == Light::LIGHT_DIRECTIONAL) { Vector3 lightDir(light[1].position.x, light[1].position.y, light[1].position.z); Vector3 lightDirection_cameraspace = viewStack.Top() * lightDir; glUniform3fv(m_parameters[U_LIGHT1_POSITION], 1, &lightDirection_cameraspace.x); } else if (light[1].type == Light::LIGHT_SPOT) { Position lightPosition_cameraspace = viewStack.Top() * light[1].position; glUniform3fv(m_parameters[U_LIGHT1_POSITION], 1, &lightPosition_cameraspace.x); Vector3 spotDirection_cameraspace = viewStack.Top() * light[1].spotDirection; glUniform3fv(m_parameters[U_LIGHT1_SPOTDIRECTION], 1, &spotDirection_cameraspace.x); } else { Position lightPosition_cameraspace = viewStack.Top() * light[1].position; glUniform3fv(m_parameters[U_LIGHT1_POSITION], 1, &lightPosition_cameraspace.x); } RenderMesh(meshList[GEO_REF_AXES], false); modelStack.PushMatrix(); modelStack.Translate(light[0].position.x, light[0].position.y, light[0].position.z); RenderMesh(meshList[GEO_LIGHTBALL], false); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(light[1].position.x, light[1].position.y, light[1].position.z); RenderMesh(meshList[GEO_LIGHTBALL], false); modelStack.PopMatrix(); modelStack.PushMatrix(); //to do: transformation code here modelStack.Scale(100, 100, 100); modelStack.Translate(0, -0.1f, 0); modelStack.Rotate(50, 1, 0, 0); RenderMesh(meshList[GEO_QUAD], true); modelStack.PopMatrix(); //modelStack.PushMatrix(); ////to do: transformation code here //modelStack.Scale(10, 10, 10); //RenderMesh(meshList[GEO_REF_SPHERE], true); //modelStack.PopMatrix(); //modelStack.PushMatrix(); ////to do: transformation code here //modelStack.Scale(10, 10, 10); //modelStack.Translate(-2, 0, 2); //RenderMesh(meshList[GEO_REF_SPHERE1], true); //modelStack.PopMatrix(); //modelStack.PushMatrix(); ////to do: transformation code here //modelStack.Scale(10, 10, 10); //modelStack.Translate(2, 0, -2); //RenderMesh(meshList[GEO_REF_SPHERE2], true); //modelStack.PopMatrix(); //modelStack.PushMatrix(); ////to do: transformation code here //modelStack.Scale(10, 10, 10); //modelStack.Translate(0, 0, 2); //RenderMesh(meshList[GEO_REF_SPHERE3], true); //modelStack.PopMatrix(); //modelStack.PushMatrix(); ////to do: transformation code here //modelStack.Scale(10, 10, 10); //modelStack.Translate(2, 0, 0); //RenderMesh(meshList[GEO_REF_SPHERE4], true); //modelStack.PopMatrix(); //modelStack.PushMatrix(); ////to do: transformation code here //modelStack.Scale(10, 10, 10); //modelStack.Translate(2, 0, 2); //RenderMesh(meshList[GEO_REF_SPHERE5], true); //modelStack.PopMatrix(); //modelStack.PushMatrix(); ////to do: transformation code here //modelStack.Scale(10, 10, 10); //modelStack.Translate(-2, 0, 0); //RenderMesh(meshList[GEO_REF_SPHERE6], true); //modelStack.PopMatrix(); //modelStack.PushMatrix(); ////to do: transformation code here //modelStack.Scale(10, 10, 10); //modelStack.Translate(-2, 0, -2); //RenderMesh(meshList[GEO_REF_CONE], true); //modelStack.PopMatrix(); //modelStack.PushMatrix(); ////to do: transformation code here //modelStack.Scale(10, 10, 10); //modelStack.Translate(0, 0, -2); //RenderMesh(meshList[GEO_REF_SPHERE8], true); //modelStack.PopMatrix(); //modelStack.PushMatrix(); ////to do: transformation code here //modelStack.Scale(10, 10, 10); //modelStack.Translate(0, 3, 0); //RenderMesh(meshList[GEO_REF_CONE], true); //modelStack.PopMatrix(); }
// // Framework Functions // bool Setup() { // // Make walls have low specular reflectance - 20%. // WallMtrl.Specular = d3d::WHITE * 0.2f; // // Create the teapot. // D3DXCreateTeapot(Device, &Teapot, 0); // // Create and specify geometry. For this sample we draw a floor // and a wall with a mirror on it. We put the floor, wall, and // mirror geometry in one vertex buffer. // // |----|----|----| // |Wall|Mirr|Wall| // | | or | | // /--------------/ // / Floor / // /--------------/ // Device->CreateVertexBuffer( 24 * sizeof(Vertex), 0, // usage Vertex::FVF, D3DPOOL_MANAGED, &VB, 0); Vertex* v = 0; VB->Lock(0, 0, (void**)&v, 0); // floor v[0] = Vertex(-7.5f, 0.0f, -10.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f); v[1] = Vertex(-7.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f); v[2] = Vertex( 7.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f); v[3] = Vertex(-7.5f, 0.0f, -10.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f); v[4] = Vertex( 7.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f); v[5] = Vertex( 7.5f, 0.0f, -10.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f); // wall v[6] = Vertex(-7.5f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f); v[7] = Vertex(-7.5f, 5.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f); v[8] = Vertex(-2.5f, 5.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f); v[9] = Vertex(-7.5f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f); v[10] = Vertex(-2.5f, 5.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f); v[11] = Vertex(-2.5f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f); // Note: We leave gap in middle of walls for mirror v[12] = Vertex(2.5f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f); v[13] = Vertex(2.5f, 5.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f); v[14] = Vertex(7.5f, 5.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f); v[15] = Vertex(2.5f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f); v[16] = Vertex(7.5f, 5.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f); v[17] = Vertex(7.5f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f); // mirror v[18] = Vertex(-2.5f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f); v[19] = Vertex(-2.5f, 5.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f); v[20] = Vertex( 2.5f, 5.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f); v[21] = Vertex(-2.5f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f); v[22] = Vertex( 2.5f, 5.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f); v[23] = Vertex( 2.5f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f); VB->Unlock(); // // Load Textures, set filters. // D3DXCreateTextureFromFile(Device, "checker.jpg", &FloorTex); D3DXCreateTextureFromFile(Device, "brick0.jpg", &WallTex); D3DXCreateTextureFromFile(Device, "ice.bmp", &MirrorTex); Device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); Device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); Device->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR); // // Lights. // D3DXVECTOR3 lightDir(0.707f, -0.707f, 0.707f); D3DXCOLOR color(1.0f, 1.0f, 1.0f, 1.0f); D3DLIGHT9 light = d3d::InitDirectionalLight(&lightDir, &color); Device->SetLight(0, &light); Device->LightEnable(0, true); Device->SetRenderState(D3DRS_NORMALIZENORMALS, true); Device->SetRenderState(D3DRS_SPECULARENABLE, true); // // Set Camera. // D3DXVECTOR3 pos(-10.0f, 3.0f, -15.0f); D3DXVECTOR3 target(0.0, 0.0f, 0.0f); D3DXVECTOR3 up(0.0f, 1.0f, 0.0f); D3DXMATRIX V; D3DXMatrixLookAtLH(&V, &pos, &target, &up); Device->SetTransform(D3DTS_VIEW, &V); // // Set projection matrix. // D3DXMATRIX proj; D3DXMatrixPerspectiveFovLH( &proj, D3DX_PI / 4.0f, // 45 - degree (float)Width / (float)Height, 1.0f, 1000.0f); Device->SetTransform(D3DTS_PROJECTION, &proj); return true; }
//-------------------------------------------------------------------------------------- // Render the scene using the D3D10 device //-------------------------------------------------------------------------------------- void CALLBACK OnD3D10FrameRender( ID3D10Device* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext ) { // Clear the render target float ClearColor[4] = { 0.9569f, 0.9569f, 1.0f, 0.0f }; ID3D10RenderTargetView* pRTV = DXUTGetD3D10RenderTargetView(); pd3dDevice->ClearRenderTargetView( pRTV, ClearColor ); ID3D10DepthStencilView* pDSV = DXUTGetD3D10DepthStencilView(); pd3dDevice->ClearDepthStencilView( pDSV, D3D10_CLEAR_DEPTH, 1.0, 0 ); // Make sure we only grow the tree the first time we go to render. // If we recreated the same tree every frame, we would definitely waste time. static bool bFirst = true; if( bFirst ) { //----------------------------------------------------------------------------------------- // o/__ <-- BreakdancinBob NOTE: Give the grow algorithm access to the random buffer // | (\ //----------------------------------------------------------------------------------------- g_pRandomBuf->SetResource( g_pRandomBufferRV ); // Grow the branches one step at a time for( UINT i = 0; i < g_NumGrowthSpurts; i++ ) { GrowBranches( pd3dDevice ); } bFirst = false; } // Render the result D3DXMATRIX mWorld; D3DXMATRIX mView; D3DXMATRIX mProj; D3DXMATRIX mWorldViewProj; D3DXMATRIX mWorldView; mWorld = *g_Camera.GetWorldMatrix(); mProj = *g_Camera.GetProjMatrix(); mView = *g_Camera.GetViewMatrix(); mWorldView = mWorld * mView; mWorldViewProj = mWorldView * mProj; // Set variables g_pmWorldViewProj->SetMatrix( ( float* )&mWorldViewProj ); g_pmWorld->SetMatrix( ( float* )&mWorld ); g_pmWorldView->SetMatrix( ( float* )&mWorldView ); g_pDiffuseTex->SetResource( g_pMeshTexRV ); D3DXVECTOR3 lightDir( -1,1,-1 ); D3DXVECTOR3 viewLightDir; D3DXVec3TransformNormal( &viewLightDir, &lightDir, &mView ); D3DXVec3Normalize( &viewLightDir, &viewLightDir ); g_pViewSpaceLightDir->SetFloatVector( ( float* )&viewLightDir ); // Set Input Assembler params ID3D10Buffer* pBuffers[1]; pBuffers[0] = g_pDrawFrom; UINT stride = g_VertStride; UINT offset = 0; pd3dDevice->IASetPrimitiveTopology( D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST ); pd3dDevice->IASetVertexBuffers( 0, 1, pBuffers, &stride, &offset ); // Render using the technique g_pRenderTextured D3D10_TECHNIQUE_DESC techDesc; g_pRenderTextured->GetDesc( &techDesc ); for( UINT p = 0; p < techDesc.Passes; p++ ) { g_pRenderTextured->GetPassByIndex( p )->Apply( 0 ); pd3dDevice->DrawAuto(); } }
//-------------------------------------------------------------------------------------- // Render the scene using the D3D10 device //-------------------------------------------------------------------------------------- void CALLBACK OnD3D10FrameRender( ID3D10Device* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext ) { // Clear the render target float ClearColor[4] = { 0.9569f, 0.9569f, 1.0f, 0.0f }; ID3D10RenderTargetView* pRTV = DXUTGetD3D10RenderTargetView(); pd3dDevice->ClearRenderTargetView( pRTV, ClearColor ); ID3D10DepthStencilView* pDSV = DXUTGetD3D10DepthStencilView(); pd3dDevice->ClearDepthStencilView( pDSV, D3D10_CLEAR_DEPTH, 1.0, 0 ); D3DXMATRIX mWorld; D3DXMATRIX mView; D3DXMATRIX mProj; D3DXMATRIX mWorldView; D3DXMATRIX mWorldViewProj; mWorld = *g_Camera.GetWorldMatrix(); mProj = *g_Camera.GetProjMatrix(); mView = *g_Camera.GetViewMatrix(); mWorldView = mWorld * mView; mWorldViewProj = mWorldView * mProj; // Set variables g_pmWorldViewProj->SetMatrix( ( float* )&mWorldViewProj ); g_pmWorldView->SetMatrix( ( float* )&mWorldView ); g_pmWorld->SetMatrix( ( float* )&mWorld ); g_pmProj->SetMatrix( ( float* )&mProj ); g_pDiffuseTex->SetResource( g_pMeshTexRV ); D3DXVECTOR3 lightDir( -1,1,-1 ); D3DXVECTOR3 viewLightDir; D3DXVec3TransformNormal( &viewLightDir, &lightDir, &mView ); D3DXVec3Normalize( &viewLightDir, &viewLightDir ); g_pViewSpaceLightDir->SetFloatVector( ( float* )&viewLightDir ); // Get VB and IB UINT offset = 0; UINT stride = g_Mesh.GetVertexStride( 0, 0 ); ID3D10Buffer* pVB = g_Mesh.GetVB10( 0, 0 ); ID3D10Buffer* pIB = g_Mesh.GetAdjIB10( 0 ); // Set Input Assembler params pd3dDevice->IASetInputLayout( g_pVertexLayout ); pd3dDevice->IASetIndexBuffer( pIB, g_Mesh.GetIBFormat10( 0 ), 0 ); pd3dDevice->IASetVertexBuffers( 0, 1, &pVB, &stride, &offset ); pd3dDevice->IASetPrimitiveTopology( D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ ); // Render using the technique g_pRenderTextured SDKMESH_SUBSET* pSubset = NULL; D3D10_TECHNIQUE_DESC techDesc; g_pRenderTextured->GetDesc( &techDesc ); for( UINT p = 0; p < techDesc.Passes; p++ ) { g_pRenderTextured->GetPassByIndex( p )->Apply( 0 ); for( UINT subset = 0; subset < g_Mesh.GetNumSubsets( 0 ); subset++ ) { pSubset = g_Mesh.GetSubset( 0, subset ); pd3dDevice->DrawIndexed( ( UINT )pSubset->IndexCount * 2, ( UINT )pSubset->IndexStart, ( UINT )pSubset->VertexStart ); } } // Render the chess piece just for show // Render using the technique g_pRenderPiece g_pRenderPiece->GetDesc( &techDesc ); for( UINT p = 0; p < techDesc.Passes; p++ ) { g_pRenderPiece->GetPassByIndex( p )->Apply( 0 ); for( UINT subset = 0; subset < g_Mesh.GetNumSubsets( 0 ); subset++ ) { pSubset = g_Mesh.GetSubset( 0, subset ); pd3dDevice->DrawIndexed( ( UINT )pSubset->IndexCount * 2, ( UINT )pSubset->IndexStart, ( UINT )pSubset->VertexStart ); } } }
void GLView::paintEvent( QPaintEvent * event ) { makeCurrent(); QPainter painter; painter.begin( this ); painter.setRenderHint( QPainter::TextAntialiasing ); #else void GLView::paintGL() { #endif // Save GL state glPushAttrib( GL_ALL_ATTRIB_BITS ); glMatrixMode( GL_PROJECTION ); glPushMatrix(); glMatrixMode( GL_MODELVIEW ); glPushMatrix(); // Clear Viewport if ( scene->visMode & Scene::VisSilhouette ) { qglClearColor( QColor( 255, 255, 255, 255 ) ); } //glViewport( 0, 0, width(), height() ); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT ); // Compile the model if ( doCompile ) { textures->setNifFolder( model->getFolder() ); scene->make( model ); scene->transform( Transform(), scene->timeMin() ); axis = (scene->bounds().radius <= 0) ? 1024.0 : scene->bounds().radius; if ( scene->timeMin() != scene->timeMax() ) { if ( time < scene->timeMin() || time > scene->timeMax() ) time = scene->timeMin(); emit sequencesUpdated(); } else if ( scene->timeMax() == 0 ) { // No Animations in this NIF emit sequencesDisabled( true ); } emit sceneTimeChanged( time, scene->timeMin(), scene->timeMax() ); doCompile = false; } // Center the model if ( doCenter ) { setCenter(); doCenter = false; } // Transform the scene Matrix ap; // TODO: Redo for new Settings class //if ( Options::upAxis() == Options::YAxis ) { // ap( 0, 0 ) = 0; ap( 0, 1 ) = 0; ap( 0, 2 ) = 1; // ap( 1, 0 ) = 1; ap( 1, 1 ) = 0; ap( 1, 2 ) = 0; // ap( 2, 0 ) = 0; ap( 2, 1 ) = 1; ap( 2, 2 ) = 0; //} else if ( Options::upAxis() == Options::XAxis ) { // ap( 0, 0 ) = 0; ap( 0, 1 ) = 1; ap( 0, 2 ) = 0; // ap( 1, 0 ) = 0; ap( 1, 1 ) = 0; ap( 1, 2 ) = 1; // ap( 2, 0 ) = 1; ap( 2, 1 ) = 0; ap( 2, 2 ) = 0; //} Transform viewTrans; viewTrans.rotation.fromEuler( Rot[0] / 180.0 * PI, Rot[1] / 180.0 * PI, Rot[2] / 180.0 * PI ); viewTrans.rotation = viewTrans.rotation * ap; viewTrans.translation = viewTrans.rotation * Pos; if ( view != ViewWalk ) viewTrans.translation[2] -= Dist * 2; scene->transform( viewTrans, time ); // Setup projection mode glProjection(); glLoadIdentity(); // Draw the grid if ( scene->options & Scene::ShowAxes ) { glDisable( GL_ALPHA_TEST ); glDisable( GL_BLEND ); glDisable( GL_LIGHTING ); glDisable( GL_COLOR_MATERIAL ); glEnable( GL_DEPTH_TEST ); glDepthMask( GL_TRUE ); glDepthFunc( GL_LESS ); glDisable( GL_TEXTURE_2D ); glDisable( GL_NORMALIZE ); glLineWidth( 2.0f ); glPushMatrix(); glLoadMatrix( viewTrans ); // TODO: Configurable grid in Settings // 1024 game units, major lines every 128, minor lines every 64 drawGrid( 1024, 128, 2 ); glPopMatrix(); } #ifndef QT_NO_DEBUG // Debug scene bounds glEnable( GL_DEPTH_TEST ); glDepthMask( GL_TRUE ); glDepthFunc( GL_LESS ); glPushMatrix(); glLoadMatrix( viewTrans ); if ( debugMode == DbgBounds ) { BoundSphere bs = scene->bounds(); bs |= BoundSphere( Vector3(), axis ); drawSphere( bs.center, bs.radius ); } glPopMatrix(); #endif GLfloat mat_spec[] = { 0.0f, 0.0f, 0.0f, 1.0f }; if ( scene->options & Scene::DoLighting ) { // Setup light Vector4 lightDir( 0.0, 0.0, 1.0, 0.0 ); if ( !frontalLight ) { float decl = declination / 180.0 * PI; Vector3 v( sin( decl ), 0, cos( decl ) ); Matrix m; m.fromEuler( 0, 0, planarAngle / 180.0 * PI ); v = m * v; lightDir = Vector4( viewTrans.rotation * v, 0.0 ); if ( scene->visMode & Scene::VisLightPos ) { glEnable( GL_BLEND ); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); glEnable( GL_DEPTH_TEST ); glDepthMask( GL_TRUE ); glDepthFunc( GL_LESS ); glPushMatrix(); glLoadMatrix( viewTrans ); glLineWidth( 2.0f ); glColor4f( 1.0f, 1.0f, 1.0f, 0.5f ); // Scale the distance a bit float l = axis + 64.0; l = (l < 128) ? axis * 1.5 : l; l = (l > 2048) ? axis * 0.66 : l; l = (l > 1024) ? axis * 0.75 : l; drawDashLine( Vector3( 0, 0, 0 ), v * l, 30 ); drawSphere( v * l, axis / 10 ); glPopMatrix(); glDisable( GL_BLEND ); } } float amb = ambient; if ( (scene->visMode & Scene::VisNormalsOnly) && (scene->options & Scene::DoTexturing) && !(scene->options & Scene::DisableShaders) ) { amb = 0.1f; } GLfloat mat_amb[] = { amb, amb, amb, 1.0f }; GLfloat mat_diff[] = { brightness, brightness, brightness, 1.0f }; glShadeModel( GL_SMOOTH ); glEnable( GL_LIGHTING ); glEnable( GL_LIGHT0 ); glLightfv( GL_LIGHT0, GL_AMBIENT, mat_amb ); glLightfv( GL_LIGHT0, GL_DIFFUSE, mat_diff ); glLightfv( GL_LIGHT0, GL_SPECULAR, mat_diff ); glLightfv( GL_LIGHT0, GL_POSITION, lightDir.data() ); // Necessary? glLightModeli( GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE ); } else { float amb = 0.5f; if ( scene->options & Scene::DisableShaders ) { amb = 0.0f; } GLfloat mat_amb[] = { amb, amb, amb, 1.0f }; GLfloat mat_diff[] = { 1.0f, 1.0f, 1.0f, 1.0f }; glShadeModel( GL_SMOOTH ); glEnable( GL_LIGHTING ); glEnable( GL_LIGHT0 ); glLightfv( GL_LIGHT0, GL_AMBIENT, mat_amb ); glLightfv( GL_LIGHT0, GL_DIFFUSE, mat_diff ); glLightfv( GL_LIGHT0, GL_SPECULAR, mat_spec ); } if ( scene->visMode & Scene::VisSilhouette ) { GLfloat mat_diff[] = { 0.0f, 0.0f, 0.0f, 1.0f }; GLfloat mat_amb[] = { 0.0f, 0.0f, 0.0f, 1.0f }; glShadeModel( GL_FLAT ); glEnable( GL_LIGHTING ); glEnable( GL_LIGHT0 ); glLightModelfv( GL_LIGHT_MODEL_AMBIENT, mat_diff ); glMaterialfv( GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, mat_diff ); glLightfv( GL_LIGHT0, GL_AMBIENT, mat_amb ); glLightfv( GL_LIGHT0, GL_DIFFUSE, mat_diff ); glLightfv( GL_LIGHT0, GL_SPECULAR, mat_spec ); } if ( scene->options & Scene::DoMultisampling ) glEnable( GL_MULTISAMPLE_ARB ); #ifndef QT_NO_DEBUG // Color Key debug if ( debugMode == DbgColorPicker ) { glDisable( GL_MULTISAMPLE ); glDisable( GL_LINE_SMOOTH ); glDisable( GL_TEXTURE_2D ); glDisable( GL_BLEND ); glDisable( GL_DITHER ); glDisable( GL_LIGHTING ); glShadeModel( GL_FLAT ); glDisable( GL_FOG ); glDisable( GL_MULTISAMPLE_ARB ); glEnable( GL_DEPTH_TEST ); glDepthFunc( GL_LEQUAL ); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); Node::SELECTING = 1; } else { Node::SELECTING = 0; } #endif // Draw the model scene->draw(); if ( scene->options & Scene::ShowAxes ) { // Resize viewport to small corner of screen int axesSize = std::min( width() / 10, 125 ); glViewport( 0, 0, axesSize, axesSize ); // Reset matrices glMatrixMode( GL_PROJECTION ); glLoadIdentity(); // Square frustum auto nr = 1.0; auto fr = 250.0; GLdouble h2 = tan( FOV / 360 * M_PI ) * nr; GLdouble w2 = h2; glFrustum( -w2, +w2, -h2, +h2, nr, fr ); // Reset matrices glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); glPushMatrix(); // Store and reset viewTrans translation auto viewTransOrig = viewTrans.translation; // Zoom out slightly viewTrans.translation = { 0, 0, -150.0 }; // Load modified viewTrans glLoadMatrix( viewTrans ); // Restore original viewTrans translation viewTrans.translation = viewTransOrig; // Find direction of axes auto vtr = viewTrans.rotation; QVector<float> axesDots = { vtr( 2, 0 ), vtr( 2, 1 ), vtr( 2, 2 ) }; drawAxesOverlay( { 0, 0, 0 }, 50.0, sortAxes( axesDots ) ); glPopMatrix(); // Restore viewport size glViewport( 0, 0, width(), height() ); // Restore matrices glProjection(); } // Restore GL state glPopAttrib(); glMatrixMode( GL_MODELVIEW ); glPopMatrix(); glMatrixMode( GL_PROJECTION ); glPopMatrix(); // Check for errors GLenum err; while ( ( err = glGetError() ) != GL_NO_ERROR ) qDebug() << tr( "glview.cpp - GL ERROR (paint): " ) << (const char *)gluErrorString( err ); emit paintUpdate(); // Manually handle the buffer swap swapBuffers(); #ifdef USE_GL_QPAINTER painter.end(); #endif }
void Lighter::Light(float colorOut0[4], float colorOut1[4], const float colorIn[4], Vec3f pos, Vec3f norm) { Color4 in(colorIn); const Color4 *ambient; if (materialUpdate_ & 1) ambient = ∈ else ambient = &materialAmbient; const Color4 *diffuse; if (materialUpdate_ & 2) diffuse = ∈ else diffuse = &materialDiffuse; const Color4 *specular; if (materialUpdate_ & 4) specular = ∈ else specular = &materialSpecular; Color4 lightSum0 = globalAmbient * *ambient + materialEmissive; Color4 lightSum1(0, 0, 0, 0); for (int l = 0; l < 4; l++) { // can we skip this light? if (!gstate.isLightChanEnabled(l)) continue; GELightType type = gstate.getLightType(l); Vec3f toLight(0,0,0); Vec3f lightDir(0,0,0); if (type == GE_LIGHTTYPE_DIRECTIONAL) toLight = Vec3f(gstate_c.lightpos[l]); // lightdir is for spotlights else toLight = Vec3f(gstate_c.lightpos[l]) - pos; bool doSpecular = gstate.isUsingSpecularLight(l); bool poweredDiffuse = gstate.isUsingPoweredDiffuseLight(l); float distanceToLight = toLight.Length(); float dot = 0.0f; float angle = 0.0f; float lightScale = 0.0f; if (distanceToLight > 0.0f) { toLight /= distanceToLight; dot = Dot(toLight, norm); } // Clamp dot to zero. if (dot < 0.0f) dot = 0.0f; if (poweredDiffuse) dot = powf(dot, specCoef_); // Attenuation switch (type) { case GE_LIGHTTYPE_DIRECTIONAL: lightScale = 1.0f; break; case GE_LIGHTTYPE_POINT: lightScale = clamp(1.0f / (gstate_c.lightatt[l][0] + gstate_c.lightatt[l][1]*distanceToLight + gstate_c.lightatt[l][2]*distanceToLight*distanceToLight), 0.0f, 1.0f); break; case GE_LIGHTTYPE_SPOT: case GE_LIGHTTYPE_UNKNOWN: lightDir = gstate_c.lightdir[l]; angle = Dot(toLight.Normalized(), lightDir.Normalized()); if (angle >= gstate_c.lightangle[l]) lightScale = clamp(1.0f / (gstate_c.lightatt[l][0] + gstate_c.lightatt[l][1]*distanceToLight + gstate_c.lightatt[l][2]*distanceToLight*distanceToLight), 0.0f, 1.0f) * powf(angle, gstate_c.lightspotCoef[l]); break; default: // ILLEGAL break; } Color4 lightDiff(gstate_c.lightColor[1][l], 0.0f); Color4 diff = (lightDiff * *diffuse) * dot; // Real PSP specular Vec3f toViewer(0,0,1); // Better specular // Vec3f toViewer = (viewer - pos).Normalized(); if (doSpecular) { Vec3f halfVec = (toLight + toViewer); halfVec.Normalize(); dot = Dot(halfVec, norm); if (dot > 0.0f) { Color4 lightSpec(gstate_c.lightColor[2][l], 0.0f); lightSum1 += (lightSpec * *specular * (powf(dot, specCoef_) * lightScale)); } } if (gstate.isLightChanEnabled(l)) { Color4 lightAmbient(gstate_c.lightColor[0][l], 0.0f); lightSum0 += (lightAmbient * *ambient + diff) * lightScale; } } // 4? for (int i = 0; i < 4; i++) { colorOut0[i] = lightSum0[i] > 1.0f ? 1.0f : lightSum0[i]; colorOut1[i] = lightSum1[i] > 1.0f ? 1.0f : lightSum1[i]; } }
bool Setup() { D3DXVECTOR3 lightDirection(0.0f, 1.0f, 0.0f); TheTerrain = new Terrain(Device, "Faces.raw", 734,1024,20,1.0f); TheTerrain->genTexture(&lightDirection); TheTerrain->loadTexture("Faces.jpg"); D3DXCreateFont(Device, 20, 0, FW_BOLD, 0, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, TEXT("Arial"), &m_font ); // // Lights. // Barrels.init(Device, "barells/barrels.x"); Dalek.init(Device, "dalek/dalek.x"); tank.init(Device, "Oiltank/tank.x"); Table.init(Device, "table/table.x"); Ton.init(Device, "ton/ton3.x"); Tree.init(Device, "trees/palm_tree_3.x"); numbertrees = rand() % 100 - 1; for(int i = 0; i < 10; i++) BoolTrash[i] = true; D3DXCreateSprite(Device, &spriteMap); D3DXCreateSprite(Device, &spritePlayer); for(int i = 0; i < 10; i++) { D3DXCreateSprite(Device, &spriteTrash[i]); } D3DXCreateTextureFromFile(Device, "Map.png", &texMap); srand(GetTickCount()); TrashPositions[0].x = rand() % 360 - 180; TrashPositions[0].z = rand() % 360 - 180; float height = TheTerrain->getHeight(TrashPositions[0].x, TrashPositions[0].z); TrashPositions[0].y = height; TrashPositions[1].x = rand() % 360 - 180; TrashPositions[1].z = rand() % 360 - 180; height = TheTerrain->getHeight(TrashPositions[1].x, TrashPositions[1].z); TrashPositions[1].y = height; TrashPositions[2].x = rand() % 360 - 180; TrashPositions[2].z = rand() % 360 - 180; height = TheTerrain->getHeight(TrashPositions[2].x, TrashPositions[2].z); TrashPositions[2].y = height; TrashPositions[3].x = rand() % 360 - 180; TrashPositions[3].z = rand() % 360 - 180; height = TheTerrain->getHeight(TrashPositions[3].x, TrashPositions[3].z); TrashPositions[3].y = height; TrashPositions[4].x = rand() % 360 - 180; TrashPositions[4].z = rand() % 360 - 180; height = TheTerrain->getHeight(TrashPositions[4].x, TrashPositions[4].z); TrashPositions[4].y = height; TrashPositions[5].x = rand() % 360 - 180; TrashPositions[5].z = rand() % 360 - 180; height = TheTerrain->getHeight(TrashPositions[5].x, TrashPositions[5].z); TrashPositions[5].y = height; TrashPositions[6].x = rand() % 360 - 180; TrashPositions[6].z = rand() % 360 - 180; height = TheTerrain->getHeight(TrashPositions[6].x, TrashPositions[6].z); TrashPositions[6].y = height; TrashPositions[7].x = rand() % 360 - 180; TrashPositions[7].z = rand() % 360 - 180; height = TheTerrain->getHeight(TrashPositions[7].x, TrashPositions[7].z); TrashPositions[7].y = height; TrashPositions[8].x = rand() % 360 - 180; TrashPositions[8].z = rand() % 360 - 180; height = TheTerrain->getHeight(TrashPositions[8].x, TrashPositions[8].z); TrashPositions[8].y = height; TrashPositions[9].x = rand() % 360 - 180; TrashPositions[9].z = rand() % 360 - 180; height = TheTerrain->getHeight(TrashPositions[9].x, TrashPositions[9].z); TrashPositions[9].y = height; for(int i = 0; i < numbertrees; i++) { TreePositions[i].x = rand() % 360 - 180; TreePositions[i].z = rand() % 360 - 180; height = TheTerrain->getHeight(TreePositions[i].x, TreePositions[i].z); TreePositions[i].y = height; } D3DXVECTOR3 lightDir(0.707f, -0.707f, 0.707f); D3DXCOLOR color(1.0f, 1.0f, 1.0f, 1.0f); D3DLIGHT9 light = d3d::InitDirectionalLight(&lightDir, &color); Device->SetLight(0, &light); Device->LightEnable(0, true); Device->SetRenderState(D3DRS_NORMALIZENORMALS, true); Device->SetRenderState(D3DRS_SPECULARENABLE, true); //build skybox BuildSkybox(Device); // // Set Camera. // D3DXVECTOR3 pos(-0.0f, -197.0f, -0.0f); D3DXVECTOR3 target(0.0, 0.0f, 0.0f); D3DXVECTOR3 up(0.0f, 1.0f, 0.0f); D3DXMATRIX V; D3DXMatrixLookAtLH(&V, &pos, &target, &up); Device->SetTransform(D3DTS_VIEW, &V); D3DXVECTOR3 pos2(-0.0f, -10.0f, 0.0f); D3DXVECTOR3 target2(0.0, 0.0f, 0.0f); D3DXVECTOR3 up2(0.0f, 1.0f, 0.0f); // D3DXMATRIX V; D3DXMatrixLookAtLH(&mview, &pos2, &target2, &up2); //Device->SetTransform(D3DTS_VIEW, &mview); // // Set projection matrix. // D3DXMATRIX proj; D3DXMatrixPerspectiveFovLH( &proj, D3DX_PI / 4.0f, // 45 - degree (float)Width / (float)Height, 1.0f, 20001.0f); Device->SetTransform(D3DTS_PROJECTION, &proj); D3DXMatrixPerspectiveFovLH(&mprojection, D3DX_PI / 4.0f, (float)Width / (float)Height, 1.0f, 20001.0f); //Device->SetTransform(D3DTS_PROJECTION, &mprojection); return true; }
void SceneLight2::Render() { // Clear color & depth buffer every frame glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); viewStack.LoadIdentity(); viewStack.LookAt( camera.position.x, camera.position.y, camera.position.z, camera.target.x, camera.target.y, camera.target.z, camera.up.x, camera.up.y, camera.up.z ); modelStack.LoadIdentity(); if (light[0].type == Light::LIGHT_DIRECTIONAL){ Vector3 lightDir(light[0].position.x, light[0].position.y, light[0].position.z); Vector3 lightDirection_cameraspace = viewStack.Top() * lightDir; glUniform3fv(m_parameters[U_LIGHT0_POSITION], 1, &lightDirection_cameraspace.x); } else if (light[0].type == Light::LIGHT_SPOT){ Position lightPosition_cameraspace = viewStack.Top() * light[0].position; glUniform3fv(m_parameters[U_LIGHT0_POSITION], 1, &lightPosition_cameraspace.x); Vector3 spotDirection_cameraspace = viewStack.Top() * light[0].spotDirection; glUniform3fv(m_parameters[U_LIGHT0_SPOTDIRECTION], 1, &spotDirection_cameraspace.x); } else{ Position lightPosition_cameraspace = viewStack.Top() * light[0].position; glUniform3fv(m_parameters[U_LIGHT0_POSITION], 1, &lightPosition_cameraspace.x); } //RENDER OBJECTS RenderMesh(meshList[GEO_AXES], false); modelStack.PushMatrix(); modelStack.Translate( light[0].position.x, light[0].position.y, light[0].position.z ); RenderMesh(meshList[GEO_LIGHTBALL], false); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(camera.target.x, camera.target.y, camera.target.z); RenderMesh(meshList[GEO_LIGHTBALL], true); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Rotate(-90, 1, 0, 0); RenderMesh(meshList[GEO_QUAD], true); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(-6, 3, -6); RenderMesh(meshList[GEO_BALL1], true); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(0, 3, -6); RenderMesh(meshList[GEO_BALL2], true); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(6, 3, -6); RenderMesh(meshList[GEO_BALL3], true); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(-6, 3, 0); RenderMesh(meshList[GEO_BALL4], true); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(0, 3, 0); RenderMesh(meshList[GEO_BALL5], true); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(6, 3, 0); RenderMesh(meshList[GEO_BALL6], true); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(-6, 3, 6); RenderMesh(meshList[GEO_BALL7], true); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(0, 3, 6); RenderMesh(meshList[GEO_BALL8], true); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(6, 3, 6); RenderMesh(meshList[GEO_BALL9], true); modelStack.PopMatrix(); modelStack.PushMatrix(); modelStack.Translate(0, 10, 0); RenderMesh(meshList[GEO_CONE], true); modelStack.PopMatrix(); }