// loading a texture void loadTextures() { char *sbTextureNameSunnyDay[6] ={ "TropicalSunnyDayLeft2048.png", "TropicalSunnyDayRight2048.png", "TropicalSunnyDayUp2048.png", "TropicalSunnyDayDown2048.png", "TropicalSunnyDayFront2048.png", "TropicalSunnyDayBack2048.png" }; char *sbTextureNight[6] ={ "right.jpg", "left.jpg", "top.jpg", "bottom.jpg", "front.jpg", "back.jpg" }; char *texFileName = "sample.png"; // NOT USED IN THIS EXAMPLE. LEFT HERE TO SHOW HOW TO LOAD A TEXTURE // loadTexture(&tex, GL_TEXTURE_2D, texFileName); // in case one would like to load a colour skybox: // front (posZ) is purple (magenta), // back (negZ) is yellow, // left (negX) is green // right (posX) is red // top (posY) is blue) // bottom (negY) is cyan //skybox.loadColourTexture(); skybox.loadSkybox(sbTextureNameSunnyDay); skybox2.loadSkybox(sbTextureNight); }
osg::ref_ptr<osg::Node> CoreGraph::createSkyBox(){ if (appConf->getValue("Viewer.SkyBox.Noise").toInt() == 0) { SkyBox * skyBox = new SkyBox; return skyBox->createSkyBox(); } else { unsigned char red = (unsigned char) appConf->getValue("Viewer.Display.BackGround.R").toInt(); unsigned char green = (unsigned char) appConf->getValue("Viewer.Display.BackGround.G").toInt(); unsigned char blue =(unsigned char) appConf->getValue("Viewer.Display.BackGround.B").toInt() ; osg::ref_ptr<osg::Texture2D> skymap = PerlinNoiseTextureGenerator::getCoudTexture(2048, 1024, red, green, blue, 255); skymap->setDataVariance(osg::Object::DYNAMIC); skymap->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR_MIPMAP_LINEAR); skymap->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR); skymap->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE); skymap->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE); osg::ref_ptr<osg::StateSet> stateset = new osg::StateSet(); stateset->setTextureAttributeAndModes(0, skymap, osg::StateAttribute::ON); stateset->setMode( GL_LIGHTING, osg::StateAttribute::OFF ); stateset->setMode( GL_CULL_FACE, osg::StateAttribute::OFF ); stateset->setRenderBinDetails(-1,"RenderBin"); osg::ref_ptr<osg::Depth> depth = new osg::Depth; depth->setFunction(osg::Depth::ALWAYS); depth->setRange(1, 1); stateset->setAttributeAndModes(depth, osg::StateAttribute::ON ); osg::ref_ptr<osg::Drawable> drawable = new osg::ShapeDrawable(new osg::Sphere(osg::Vec3(0.0f,0.0f,0.0f), 1)); osg::ref_ptr<osg::Geode> geode = new osg::Geode; geode->setCullingActive(false); geode->setStateSet(stateset); geode->addDrawable(drawable); osg::ref_ptr<osg::Transform> transform = new SkyTransform; transform->setCullingActive(false); transform->addChild(geode); osg::ref_ptr<osg::ClearNode> clearNode = new osg::ClearNode; clearNode->setRequiresClear(false); clearNode->addChild(transform); return clearNode; } }
bool Main::Initialize() { // Initialize window settings first, since later classes will be using these if(!Settings->Initialize()) { cout << "Failed to initialize SettingsClass." << endl; return false; } // D3D11App initialized if(!D3D11App::Initialize()) { cout << "Failed to initialize app." << endl; return false; } Text->Initialize(mDirect3D->GetDevice(), mDirect3D->GetDevCon()); Texture->Initialize(mDirect3D->GetDevice()); Effects::Initialize(mDirect3D->GetDevice()); InputLayouts::Initialize(mDirect3D->GetDevice()); Loader->Initialize(mDirect3D->GetDevice()); mSkyBox->Initialize(mDirect3D->GetDevice(), 5000.0f); mGame->Initialize(); // Last part of the initialize of main D3D11App::ShowWindow(); OnResize(); return S_OK; }
void myApp::init_graphics() { m_d3ddev = m_pD3D->getDevice(); m_d3ddev->SetRenderState(D3DRS_LIGHTING, false); m_d3ddev->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); // creating cameras isWASDCameraActive = true; wasdCamera = new WASDCamera(); camera = new Camera(); float initPos = 500.0f; wasdCamera->setPosition({ initPos, -initPos, initPos }); wasdCamera->setUpDirection({ 0.0f, 1.0f, 0.0f }); wasdCamera->setLookAt(worldCenter); m_d3ddev->SetTransform(D3DTS_VIEW, wasdCamera->getViewMatrix()); // set the view transform to matView D3DXMatrixPerspectiveFovLH(&m_matProj, D3DXToRadian(45), // the horizontal field of view (FLOAT)SCREEN_WIDTH / (FLOAT)SCREEN_HEIGHT, // aspect ratio 1.0f, // the near view-plane 20000.0f); // the far view-plane m_d3ddev->SetTransform(D3DTS_PROJECTION, &m_matProj); // set the projection ZeroMemory(&globalMaterial, sizeof(D3DMATERIAL9)); // clear out the struct for use globalMaterial.Diffuse = hexToColor(0xffffff); globalMaterial.Ambient = hexToColor(0xffffff); globalMaterial.Emissive = hexToColor(0x000010); globalMaterial.Specular = hexToColor(0); m_nClearColor = 0xFF111111; SkyBox *box = new SkyBox(m_d3ddev); box->scale(10000.0f, 10000.0f, 10000.0f); objects.push_back(box); aroundCubeObjects.push_back(box); reflectingCube = new ReflectingCube(m_d3ddev); objects.push_back(reflectingCube); reflectingCube->scale(200.0f, 200.0f, 200.0f); }
//Calls the Skybox render function to render the skybox which is set up to render the skybox in a specific way //then gets uniforms so that it knows what variables it's accessing the appropriate shader file. //then passes values to the shader for it to calculate texture coordinates and such then proceeds //to draw the cube mesh to screen. void SplashScreen::renderSkyBox() { skyBoxObject->render(); Mesh * currentMesh = skyBoxObject->getMesh(); SkyBox * currentMaterial = (SkyBox*)skyBoxObject->getMaterial(); if (currentMesh && currentMaterial) { Camera * cam = mainCamera->getCamera(); currentMaterial->bind(); currentMesh->bind(); GLint cameraLocation = currentMaterial->getUniformLocation("cameraPos"); GLint viewLocation = currentMaterial->getUniformLocation("view"); GLint projectionLocation = currentMaterial->getUniformLocation("projection"); GLint cubeTextureLocation = currentMaterial->getUniformLocation("cubeTexture"); glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, glm::value_ptr(cam->getProjection())); glUniformMatrix4fv(viewLocation, 1, GL_FALSE, glm::value_ptr(cam->getView())); glUniform4fv(cameraLocation, 1, glm::value_ptr(cam->getPosition())); glUniform1i(cubeTextureLocation, 0); glDrawElements(GL_TRIANGLES, currentMesh->getIndexCount(), GL_UNSIGNED_INT, 0); currentMaterial->unbind(); } //CheckForErrors(); GLenum error; do{ error = glGetError(); } while (error != GL_NO_ERROR); }
void SSAODemo::init() { scene = engine->createScene(); FixedArray<std::string, 6> skyBoxTextureFileNames = { Engine::getAssetPath() + "Textures/Skybox/miramar_ft.tga", Engine::getAssetPath() + "Textures/Skybox/miramar_bk.tga", Engine::getAssetPath() + "Textures/Skybox/miramar_up.tga", Engine::getAssetPath() + "Textures/Skybox/miramar_dn.tga", Engine::getAssetPath() + "Textures/Skybox/miramar_rt.tga", Engine::getAssetPath() + "Textures/Skybox/miramar_lf.tga" }; scene->setGlobalAmbientLight(Vector3(1.0f, 1.0f, 1.0f)); SkyBox* skyBox = (SkyBox*)scene->createSceneItem("SkyBox"); skyBox->setTextureFiles(skyBoxTextureFileNames); Mesh* sponza = scene->createSceneItem<Mesh>(); engine->getSceneImporter().importMesh(Engine::getAssetPath() + "Models/Sponza/sponza.obj", sponza); sponza->scale(0.05f); float width = static_cast<float>(engine->getRenderer().getScreenViewPort().width); float height = static_cast<float>(engine->getRenderer().getScreenViewPort().height); scene->getMainCamera()->setAspectRatio((float)width / (float)height); camera = scene->getMainCamera(); camera->translate(Vector3(20.0f, 5.0f, 0.0f), FrameOfReference::World); camera->setRotation(Quaternion(-90.0f, Vector3::UNIT_Y)); }
// this is the render function. It contains flags to set up the differnt shaders and what // to draw. One can remove most of is not all of theem void renderFun() { // DEBUGGING FLAGS static int drawTri = 1; static int drawSkybox = 1; static int drawLines = 0; static Vector3f pos=Vector3f(0,0,100); static Vector3f lookat=Vector3f(0 ,0 ,0); static Vector3f up=Vector3f(0,1,0); static int zoom = -70; static int camZoom = 1; static int setCam = 0; // setting up the camera manually if needed // can be remved if (setCam) { cam.setCamera(pos, lookat, up); setCam = 0; } // setting up the camera zoom manually if needed // can be remved if (camZoom) { cam.zoomIn(zoom); camZoom = 0; } // setting opengl - clearing the buffers glEnable(GL_DEPTH_TEST); // need depth test to correctly draw 3D objects glClearColor(1.0,1.0,1.0,1); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); if (drawSkybox) { skybox.displaySkybox(cam); } if (drawTri) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); displayBoxFun(sphereBoxProg); } // if (drawLines) { // glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); // displayBoxFun(sphereLinesBoxProg); // } glutSwapBuffers(); }
// Draw function, I don't know or care that much about what's going on here, as long as it works void Main::Draw() { mDirect3D->GetDevCon()->ClearRenderTargetView(mDirect3D->GetRTView(), reinterpret_cast<const float*>(&Colors::Cyan)); mDirect3D->GetDevCon()->ClearDepthStencilView(mDirect3D->GetDSView(), D3D11_CLEAR_DEPTH|D3D11_CLEAR_STENCIL, 1.0f, 0); float blendFactor[] = {0.0f, 0.0f, 0.0f, 0.0f}; mDirect3D->GetDevCon()->RSSetState(0); mDirect3D->GetDevCon()->OMSetDepthStencilState(0, 0); mDirect3D->GetDevCon()->OMSetBlendState(0, blendFactor, 0xffffffff); mGame->Draw(mDirect3D->GetDevCon()); mSkyBox->Draw(mDirect3D->GetDevCon(), mGame->GetPlayerCam()); // If the text isn't drawn last, objects in the world might hide it Text->Draw(); mDirect3D->GetSwapChain()->Present(1, 0); }
void SetupScene() { //hField.Create(heightmapFile, heightmapTexture, 256, 256); hField.Create(heightmapTexture); char* SkyBoxTextures[6] = {"Data/textures/skybox/front.tga", "Data/textures/skybox/back.tga", "Data/textures/skybox/left.tga", "Data/textures/skybox/right.tga", "Data/textures/skybox/up.tga", "Data/textures/skybox/down.tga" }; sbox.Create(SkyBoxTextures); camera = OpenGLCamera(real3(50,10,10), real3(50, 1, 20), real3(0, 1, 0),0.5); //create enemy tanks for (int i = 0; i < 4; i++) { tanks[i] = new Tank(turretmodelFile, turrettextureFile, 2, Vec3(30+(10*i), 0, 50)); tanks[i]->setRotation(Vec3(0, 270, 0)); scene->AddObject(tanks[i]); } Crate *crates[50]; for (int i = 0; i < 15; i++) { crates[i] = new Crate(Vec3(65, 1, 30+(2*i)), Vec3(0, 0, 0)); scene->AddObject(crates[i]); } for (int i = 15; i < 30; i++) { crates[i] = new Crate(Vec3(25, 1, (2*i)), Vec3(0, 0, 0)); scene->AddObject(crates[i]); } for (int i = 30; i < 50; i++) { crates[i] = new Crate(Vec3((2*i)-34, 1, 61), Vec3(0, 0, 0)); scene->AddObject(crates[i]); } //player setup player = new Tank(tankmodelFile, tanktextureFile, 2, Vec3(50, 0, 25)); player->setPlayer(); player->initKeyboard(); scene->AddObject(player); //setup hud text[0] = new Font("Health: ", Vec3(50, 20, 0)); text[1] = new Font("Score: ", Vec3(650, 20, 0)); text[2] = new Font("FPS: ", Vec3(50, 550, 0)); glClearColor( 0.0f, 0.0f, 0.0f, 0.0f ); }
void display( void ) { glClearColor(1.0,1.0,1.0,1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); // draw all walls for(int i = 0; i< walls.size(); i++) { wallVAO->drawAt(walls[i]); } // draw all trees for(int i = 0; i< trees.size(); i++) { treeVAO->drawAt(trees[i]); } // draw the skybox skybox.draw(); glutSwapBuffers(); }
int main(int argc, char** argv) { int rc; Shader s; // set the camera to an initial position cam.setCamera(Vector3f(0,-10,100), Vector3f(0,0,0), Vector3f(0,1,0)); glutInit(&argc, argv); // glutInitDisplayMode(GLUT_RGBA|GLUT_DOUBLE|GLUT_DEPTH|GLUT_3_2_CORE_PROFILE); glutInitDisplayMode(GLUT_RGBA|GLUT_DOUBLE|GLUT_DEPTH); glutInitWindowSize(600,600); glutInitWindowPosition(10, 10); glutCreateWindow("skybox"); glutDisplayFunc(renderFun); glutIdleFunc(idleFun); // setCallbackFun(); // initialize GLEW // GLenum err = glewInit(); // if ( err != GLEW_OK) printf(" Error initializing GLEW! \n"); loadTextures(); skybox.init(); // skybox2.init(); Init_Geometry(); InitVBO(); rc = loadShaders(s); if (rc != 0) { printf("error after createing shaders rc = %d \n", rc); getchar(); } glutMainLoop(); }
void init() { init_gl(); srand(time(NULL)); gameclock = new Timer(); gameMouse = new Mouse(); //use kent's skybox skybox.init_data(); skybox.init_VAO(); skybox.init_VBO(); skybox.init_shader(); skybox.init_texture_map(); // load my shader quadShader = new Shader("glsl/quad_vshader.glsl","glsl/quad_fshader.glsl"); // load textures brickTexture = new Texture2D("Brick.bmp"); treeTexture = new Texture2D("trees.bmp"); //generat meshes brickMesh = new TriMesh(); makeBrickMesh(brickMesh); treeMesh = new TriMesh(); makeTreeMesh(treeMesh); // creat tree and wall voa's treeVAO = new VertexArrayObject(treeMesh, treeTexture, quadShader); wallVAO = new VertexArrayObject(brickMesh, brickTexture, quadShader); // rotate camera to point into the level Camera::GetInstance()->transform.rotateY(-90 - 45,ROTATE_GLOBAL); //10 random trees for(int i = 0; i < 10; i++) { vec4 pos; pos.w = 1; float rot = 0; pos.x = rand()%900; pos.x /= 100; pos.z = rand()%900; pos.z /= 100; rot = rand()%9000; rot /= 100; trees.push_back(Transform()); trees[trees.size() - 1].position = pos; trees[trees.size() - 1].rotateY(rot, ROTATE_GLOBAL); } //z- wall for(int i = 0; i < 10; i++) { walls.push_back(Transform()); walls[walls.size() - 1].position.z = -0.5; walls[walls.size() - 1].position.x = i; } //z+ wall for(int i = 0; i < 10; i++) { walls.push_back(Transform()); walls[walls.size() - 1].position.z = 9.5; walls[walls.size() - 1].position.x = i; } //x- wall for(int i = 0; i < 10; i++) { walls.push_back(Transform()); walls[walls.size() - 1].position.x = -0.5; walls[walls.size() - 1].position.z = i; walls[walls.size() - 1].rotateY(90,ROTATE_GLOBAL); } //x+ wall for(int i = 0; i < 10; i++) { walls.push_back(Transform()); walls[walls.size() - 1].position.x = 9.5; walls[walls.size() - 1].position.z = i; walls[walls.size() - 1].rotateY(90,ROTATE_GLOBAL); } //y- floor for(int i = 0; i < 10; i++) { for(int j = 0; j < 10; j++) { walls.push_back(Transform()); walls[walls.size() - 1].position.y = -0.5; walls[walls.size() - 1].position.x = i; walls[walls.size() - 1].position.z = j; walls[walls.size() - 1].rotateX(90,ROTATE_GLOBAL); } } Camera::GetInstance()->transform.position.y += 0.1; GL_CHECK_ERRORS }
// RENDERS AN OBJECT USING A SKYBOX AS THE TEXTURE SOURCE void displayBoxFun(GLuint shaderProg) { Matrix4f viewMat, projMat, modelMat, m; // set up the mode to wireframe // setting up the transformaiton of the object from model coord. system to world coord. modelMat = Matrix4f::identity(); //modelMat = Matrix4f::translation(0,0,0); modelMat = Matrix4f::scale(50,50,50); // ROATE THE OBJECT AROUND THE CAMERA VECTOR // CAN ADD ROTATIONS AROUND THE PRIMARY AXIS modelMat = modelMat * Matrix4f::rotateVector(cam.getLookAtVector(),angle,1); // setting up the viewpoint transformation viewMat = cam.getViewMatrix(NULL); // setting up the projection transformation projMat= cam.getProjectionMatrix(NULL); // putting it all together m = projMat * viewMat * modelMat; // tell openfl which shader program to use glUseProgram(shaderProg); // transfer the modelViewProjection matrix to the shader GLuint locMat= 0; locMat=glGetUniformLocation(shaderProg, "modelViewProjMat"); glUniformMatrix4fv(locMat,1,1,(float *)m.vm); // transfer the modelView matrix to the shader m = viewMat * modelMat; locMat=glGetUniformLocation(shaderProg, "modelViewMat"); glUniformMatrix4fv(locMat,1,1,(float *)m.vm); // transfer the model matrix to the shader m = modelMat; locMat=glGetUniformLocation(shaderProg, "modelMat"); glUniformMatrix4fv(locMat,1,1,(float *)m.vm); // load the camera position to the shader locMat=glGetUniformLocation(shaderProg, "camPos"); Vector3f camPos = cam.getPosition(); glUniform3fv(locMat,1, (float *) &camPos); // load the refract flag to the shader locMat=glGetUniformLocation(shaderProg, "refractFlag"); glUniform1i(locMat, refractFlag); glActiveTexture(GL_TEXTURE3); GLuint texCube = skybox.getTexHandle(); glBindTexture(GL_TEXTURE_CUBE_MAP, texCube); GLuint samLoc = glGetUniformLocation(shaderProg, "texCube"); glUniform1i(samLoc, 3); GLint ttt = 0; glGetUniformiv(shaderProg, samLoc, &ttt); // bind the buffers to the shaders GLuint positionLoc = glGetAttribLocation(shaderProg, "vertex_position"); GLuint normalLoc = glGetAttribLocation(shaderProg, "vertex_normal"); glEnableVertexAttribArray(positionLoc); glEnableVertexAttribArray(normalLoc); glBindBuffer(GL_ARRAY_BUFFER, vertex_handle); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, triangle_handle); // Tells OpenGL how to walk through the two VBOs struct sphereVertex v; int relAddress = (char *) v.pos - (char *) &v; glVertexAttribPointer(positionLoc,4,GL_FLOAT, GL_FALSE, sizeof(struct sphereVertex),(char*) NULL+relAddress); relAddress = (char *) v.normal - (char *) &v; glVertexAttribPointer(normalLoc,4,GL_FLOAT, GL_FALSE, sizeof(struct sphereVertex),(char*) NULL+relAddress); // draw the triangles glDrawElements(GL_TRIANGLES, numTriangles*3, GL_UNSIGNED_INT, (char*) NULL+0); // glUseProgram(0); // glUseProgram(shaderProg); // draw the second sphere modelMat = Matrix4f::identity(); //modelMat = Matrix4f::translation(0,0,0); modelMat = Matrix4f::scale(50,50,50) * Matrix4f::translation(2, 0, 0); // ROATE THE OBJECT AROUND THE CAMERA VECTOR // CAN ADD ROTATIONS AROUND THE PRIMARY AXIS modelMat = modelMat * Matrix4f::rotateVector(cam.getLookAtVector(),angle,1); // setting up the viewpoint transformation viewMat = cam.getViewMatrix(NULL); // setting up the projection transformation projMat= cam.getProjectionMatrix(NULL); // putting it all together m = projMat * viewMat * modelMat; locMat= 0; locMat=glGetUniformLocation(shaderProg, "modelViewProjMat"); glUniformMatrix4fv(locMat,1,1,(float *)m.vm); // transfer the modelView matrix to the shader m = viewMat * modelMat; locMat=glGetUniformLocation(shaderProg, "modelViewMat"); glUniformMatrix4fv(locMat,1,1,(float *)m.vm); // transfer the model matrix to the shader m = modelMat; locMat=glGetUniformLocation(shaderProg, "modelMat"); glUniformMatrix4fv(locMat,1,1,(float *)m.vm); glActiveTexture(GL_TEXTURE3); GLuint texCube2 = skybox2.getTexHandle(); glBindTexture(GL_TEXTURE_CUBE_MAP, texCube2); GLuint samLoc2 = glGetUniformLocation(shaderProg, "texCube"); glUniform1i(samLoc2, 3); GLint ttt2 = 0; glGetUniformiv(shaderProg, samLoc, &ttt2); glBindBuffer(GL_ARRAY_BUFFER, vertex_handle2); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, triangle_handle2); // Tells OpenGL how to walk through the two VBOs // struct sphereVertex v; relAddress = (char *) v.pos - (char *) &v; glVertexAttribPointer(positionLoc,4,GL_FLOAT, GL_FALSE, sizeof(struct sphereVertex),(char*) NULL+relAddress); relAddress = (char *) v.normal - (char *) &v; glVertexAttribPointer(normalLoc,4,GL_FLOAT, GL_FALSE, sizeof(struct sphereVertex),(char*) NULL+relAddress); // draw the triangles glDrawElements(GL_TRIANGLES, numTriangles*3, GL_UNSIGNED_INT, (char*) NULL+0); return; }
// display callback void display_callback( void ){ if (gameOver == true){ drawGameOver(); } CalculateFPS(); if (shoot == true) { player->shoot(player->getRotation()); } int current_window; // retrieve the currently active window current_window = glutGetWindow(); // clear the color and depth buffers glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if (rmode == SELECT) { startPicking(); } glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective( 70.0f, float(glutGet(GLUT_WINDOW_WIDTH))/float(glutGet(GLUT_WINDOW_HEIGHT)), 0.1f, 2000.0f ); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); camera.Update(hField.getHeight(camera.camera_pos.x, camera.camera_pos.z)); glPushMatrix(); glColor3f(1.0, 1.0, 1.0); hField.Render(); sbox.Render(camera.camera_pos.x,camera.camera_pos.y,camera.camera_pos.z,1024,1024,1024); scene->RenderObjects(); //player->setHeight(hField.getHeight(player.getPosition()[0], player.getPosition()[2])); player->Render(); glPopMatrix(); // swap the front and back buffers to display the scene glutSetWindow( current_window ); //PICKING // for(int i = 0; i < 2; i++) { // for(int j = 0; j < 2; j++) { // glPushMatrix(); // glPushName(i*2+j); // glTranslatef(i*3.0,0,-j * 3.0); // glCallList(display_list); // glPopName(); // glPopMatrix(); // } // } //draw HUD drawHUD(); if (rmode == SELECT) { stopPicking(); } else { if (gameOver == false) glutSwapBuffers(); } }
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { XEngine *engine = XEngine::GetInstance(); if( engine->Init(hInstance) == FALSE ) { return -1; } Rect rec(Position(-10000.0, 10000.0), Position(10000.0, -10000.0)); TestScene *scene = new TestScene; scene->SetTime(0); //Scene *scene = new Scene; scene->Init(rec); scene->camera->MoveForwardBy(-40); scene->camera->MoveUpBy(18); scene->camera->Pitch(-XM_PI / 10); Material material; material.ambient = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); material.diffuse = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); material.specular = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); material.power = 9.0f; //material.texture = SRVBatch::GetInstance()->LoadSRV("media/", "cup.jpg"); Particle *fire = new Particle; fire->Init("media/","fire.png"); fire->SetPosition(0, 0, 10); //scene->AddRenderableThing(*fire); SkyBox *sky = new SkyBox; //sky->Init("textures/", "skymap.dds"); sky->Init("textures/", "Above_The_Sea.dds"); //sky->Init("textures/", "desert_skymap.dds"); scene->AddSky(sky); Terrain *terrain = new Terrain; //terrain->Init("terrain/testHight.bmp", "terrain/", "dirt01.dds"); terrain->Init("terrain/heightmap01.bmp", "terrain/", "grass.jpg"); scene->AddTerrain(terrain); Wall *wall = new Wall; wall->Init(30, 30, 0.3); wall->Pitch(XM_PI / 2); wall->SetPosition(0, -3, 0); //scene->AddRenderableThing(*wall); //¿É¼ûÐÔ²âÊÔ Wall *wall0 = new Wall; wall0->Init(30, 30, 0.3); wall0->Pitch(XM_PI / 2); wall0->SetPosition(1000, -3, 0); //scene->AddRenderableThing(*wall0); Obj *obj = new Obj; obj->CreateBox(1, 3, 2, material); obj->SetPosition(5, 1, 12); obj->Yaw(XM_PI / 3); obj->Roll(XM_PI / 3); obj->SetScale(1.3); //scene->AddRenderableThing(*obj); Cube *cube = new Cube; cube->Init(2); cube->Pitch(XM_PI / 3); cube->Roll(XM_PI / 3); cube->SetMaterial(material); //scene->AddRenderableThing(*cube); Ball *ball = new Ball; ball->Init(1); ball->SetPosition(0, 0, 6); Obj *objInWall = new Obj; objInWall->CreateBox(1, 1, 1, material); objInWall->SetPosition(0, 1, 0); ball->AddChild(objInWall); //scene->AddRenderableThing(*ball); Ship *ship = new Ship; //ship->Init(); //ship->SetPosition(-10, 0, 0); //scene->AddRenderableThing(*ship); Model *test = new Model; test->LoadModel("media/", "chair.obj"); test->SetScale(1.7); test->SetPosition(-15, 0, 0); test->Pitch(-1.2); test->Yaw(-1.5); //scene->AddRenderableThing(*test); //SmileBoy *smileBoy= new SmileBoy; //smileBoy->Init(); //smileBoy->SetHandleInput(FALSE); //scene->AddRenderableThing(*smileBoy); Female *female = new Female; female->Init(); //female->SetPosition(-7, 0,0); female->SetHandleInput(TRUE); scene->AddRenderableThing(*female); RenderSystem::GetInstance()->SetShadowOpen(true); engine->LoadScene(scene); { Light *light = new Light; light->type = 0; light->position = XMFLOAT4(0.0f, 5.0f, -5.0f, 1.0f); XMStoreFloat4(&light->direction, XMVector4Normalize(XMVectorSet(1.0f, -1.0f, 0.0f, 0.0f))); light->ambient = XMFLOAT4(0.4f, 0.2f, 0.3f, 1.0f); light->diffuse = XMFLOAT4(0.3f, 0.4f, 0.5f, 1.0f); light->specular = XMFLOAT4(0.5f, 0.3f, 0.2f, 1.0f); light->attenuation0 = 0.0f; light->attenuation1 = 0.0f; light->attenuation2 = 0.0f; light->alpha = 0.0f; light->beta = 0.0f; light->falloff = 0.0f; scene->AddLight(light); } //******************************************* engine->Run(); return 0; }
bool myWorld::Init(int perso) { cont_cond_t cond; uint8 c; GLboolean xp = GL_FALSE; GLboolean yp = GL_FALSE; Vehicle *vehicle; int i; int f=NEG; float d=0.0; int ft=f; int throttle=0; int brake=0; int ang=0; ogg sultan("/rd/sons/ogg/sultanTribes.ogg"); init(); //speed tabulation for(i=-NEG;i<0;i++) aSpeed[i+NEG]=-(0.24*(float)7*i/(PLUS+NEG)+2)* log((float) -10*(float)7*i/(PLUS+NEG)+1)*3.6; for(i=NEG;i<PLUS+NEG;i++) aSpeed[i]=(-0.11*(float)(7*(i-NEG))/(PLUS+NEG)+2)*5* log((float) 3*(float)7*(i-NEG)/(PLUS+NEG)+1)*3.6; /* Declaration des objets */ SkyBox *skyBox = new SkyBox(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f); Landscape *cliff = new Landscape(JPEG, "/rd/terrain.jpg", "/rd/terrain.pcx", 256.0f, 32, 1, 1, 0); Landscape *sand = new Landscape(JPEG, "/rd/circuit.jpg", "/rd/circuit.pcx", 450.0f, 30, 4, 1/3.0f, -12.0f); PalmTree *palmier = new PalmTree("/rd/palmier.png", 69.0f, (sand->getYFromXZ(69,12)) + 10, 12.0f, 20.0f, 20.0f, 20.0f); PalmTree *cactus= new PalmTree("/rd/cactus.png", 10.0f, sand->getYFromXZ(10, 30) + 10, 30.0f, 40.0f, 40.0f, 40.0f); Landscape *sea = new Landscape(NJPEG, NULL, "/rd/eau.pcx", 700.0f, 7, 4, 0.0f, 3.0f, 0.5f, 0.6f, 0.8f); TheLittleHouseOnThePrairie *house = new TheLittleHouseOnThePrairie(-170.0f, 4.5f, -140.0f, 4.0f, 4.0f, 4.0f); StartPane *startPane = new StartPane(-155.0f,sand->getYFromXZ(69,12) , 35.0f, 25.0f, 50.0f, 50.0f); Caisse *caisse1 = new Caisse("/rd/decor/caisses/caisseGrande.png", -320.0f, -5.0f, -280.0f, 15.0f, 15.0f, 15.0f); Caisse *caisse2 = new Caisse("/rd/decor/caisses/caisseCroix.png", 80.0f, 2.0f, -280.0f, 15.0f, 15.0f, 15.0f); /*Caisse *caisse3 = new Caisse("/cd/decor/caisses/explosif.png", 280.0f, 2.0f, -220.0f, 15.0f, 15.0f, 15.0f);*/ /* Character creation */ switch(perso + 2) { case 2: vehicle = new OisisVehicle(-155.0f, (sand->getYFromXZ (-155, 35)) + 1.25, 35.0f, -155.0f, (sand->getYFromXZ (-155, 34.9)) + 1.25, 34.9f, 6.25f, 2.5f, 2.5f, 1.5); break; case 3: vehicle = new MomoVehicle(-155.0f, sand->getYFromXZ (-155, 35) + 1.25, 35.0f, -155.0f, sand->getYFromXZ (-155, 34.9) + 1.25 - 0.5, 34.9f, 2.5f , 5.0f, 2.5f, 0.5); break; case 4: vehicle = new NoelVehicle(-155.0f, sand->getYFromXZ (-155, 35) + 7.5, 35.0f, -155.0f, sand->getYFromXZ (-155, 34.9) + 7.5 - 10, 34.9f, 3.25f , 15.0f, 13.0f, 10); break; default: vehicle = new NoelVehicle(-155.0f, sand->getYFromXZ (-155, 35) + 7.5, 35.0f, -155.0f, sand->getYFromXZ (-155, 34.9) + 7.5, 34.9f, 3.25f , 15.0f, 13.0f, 10); break; } sultan.play(1); //vehicle->updateSlope(sand); //Vector3D tmp1= (vehicle->getPosition()) + (Vector3D (0, 10,17.5)); /*Vector3D tmp1= (vehicle->getPosition()) + (Vector3D (0, 10 - vehicle->getOffset(), 17.5)); Vector3D tmp2= Vector3D (0,1,0); Camera cam(tmp1, vehicle->getPosition(), tmp2);*/ Vector3D tmp1= (vehicle->getPosition()) + (Vector3D (0, 10 - vehicle->getOffset(), 17.5)); Vector3D tmp3= Vector3D (0,1,0); Vector3D tmp2 = vehicle->getPosition(); tmp2.y -= vehicle->getOffset(); Camera cam(tmp1, tmp2, tmp3); palmier->shape(); cactus->setColor(0.0f, 0.6f, 0.2f); cactus->shape(); cliff->shape(); sand->shape(); sea->shape(); startPane->shape(); house->shape(); vehicle->shape(); caisse1->shape(); caisse2->shape(); /*caisse3->shape();*/ c = maple_first_controller(); bool noRotatingThisFrame = false; while(1) { noRotatingThisFrame = false; c = maple_first_controller(); ft=f; if (c == 0) continue; if (cont_get_cond(c, &cond) < 0) continue; if (!(cond.buttons & CONT_START)) { sultan.stop(); return false; } if (!(cond.buttons & CONT_DPAD_LEFT)){ if(f!=NEG){ vehicle->rotate(ROT_ANGLE, sand); cam.move(vehicle->getPosition(), vehicle->getDirection()); } } if (!(cond.buttons & CONT_DPAD_RIGHT)) { if(f!=NEG){ vehicle->rotate(-ROT_ANGLE, sand); cam.move(vehicle->getPosition(), vehicle->getDirection()); } } brake=0; if (!(cond.buttons & CONT_B)) brake=1; throttle=0; if (!(cond.buttons & CONT_A)) throttle=1; if (!(cond.buttons & CONT_B )&&!(cond.buttons & CONT_X )) screenShot(); if (!(cond.buttons & CONT_Y)) { wav klaxon ("/rd/Klaxon.wav"); klaxon.play(); } if (cond.ltrig) { noRotatingThisFrame = true; cam.rotateAroundView(2); } if (cond.rtrig) { noRotatingThisFrame = true; cam.rotateAroundView(-2); } if (!(cond.buttons & CONT_B)&&!(cond.buttons & CONT_X)&&!(cond.buttons & CONT_A)&&!(cond.buttons & CONT_Y)) { return false; } /* Begin frame */ /* Draw the GL "scene" */ Vector3D dir = vehicle->getDirection(); Vector3D dirNoY (dir.x, 0, dir.z); if (!noRotatingThisFrame) cam.updateRotation(vehicle->getPosition(), dirNoY); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glKosBeginFrame(); /* Switch to the blended polygon list if needed */ glKosFinishList(); glDepthMask(0); /*******************************************/ glLoadIdentity(); glPushMatrix(); cam.affiche(); glEnable(GL_KOS_NEARZ_CLIPPING); glPushMatrix(); glScalef(350.0f, 200.0f, 350.0f); /* Paint the Sky Box */ skyBox->shape(); glPopMatrix(); cliff->displayElement(); sea->displayElement(); glPushMatrix(); glScalef(2.0f, 2.0f, 2.0f); house->displayElement(); glPopMatrix(); palmier->displayElement(); cactus->displayElement(); /* Draw the second house on the Prairie */ glPushMatrix(); glTranslatef(200.0f, 60.0f, 200.0f); house->displayElement(); glPopMatrix(); /* Draw a second cactus */ glPushMatrix(); glTranslatef(-320.0f, sand->getYFromXZ (120, 250), -120.0f); cactus->displayElement(); glPopMatrix(); /* Draw a second palmtree */ glPushMatrix(); glTranslatef(-125.0f, sand->getYFromXZ (-125, 10), 10.0f); cactus->displayElement(); glPopMatrix(); sand->displayElement(); startPane->displayElement(); caisse1->displayElement(); caisse2->displayElement(); /*caisse3->displayElement();*/ /* Draw the vehicle */ glPushMatrix(); /* METTRE LA PENTE A LA PLACE DU PREMIER 0 */ f=PhysicalEngine::speed(f,throttle,brake,0,0); float d=PhysicalEngine::distance(ft,f)*SCALE; vehicle->moveRelatif(d,sand); cam.move(vehicle->getPosition(),vehicle->getDirection()); glTranslatef(vehicle->getPosition().x, vehicle->getPosition().y, vehicle->getPosition().z); //1st rotation, in x and z float rotatefAngle = angleBetweenVectorsWithReference (Vector3D(0,0,1), Vector3D(1,0,0), dirNoY); //convert to degrees : rotatefAngle = radToDeg (rotatefAngle); Vector3D rotateUp = cam.getUpVector(); glRotatef(rotatefAngle, rotateUp.x, rotateUp.y, rotateUp.z); //2nd rotation, in z and y Vector3D tF = vehicle->getFront(); Vector3D tPos = vehicle->getPosition(); Vector3D dir2 = tF - tPos; rotatefAngle = asin (dir2.y / dir2.Magnitude()); //convert to degrees : rotatefAngle = radToDeg (rotatefAngle); Vector3D rotateX (1,0,0); glRotatef(-rotatefAngle, rotateX.x, rotateX.y, rotateX.z); vehicle->displayElement(); glPopMatrix(); glDisable(GL_KOS_NEARZ_CLIPPING); glPopMatrix(); /* Finish the frame */ glKosFinishFrame(); } }
void DxManager::CreateSkyBox(string texture) { if(this->skybox) delete this->skybox; SkyBox* sb = new SkyBox(this->camera->getPosition(), 10, 10); MeshStrip* strip = sb->GetStrips()->get(0); // Create the desc for the buffer BUFFER_INIT_DESC BufferDesc; BufferDesc.ElementSize = sizeof(Vertex); BufferDesc.InitData = strip->getVerts(); BufferDesc.NumElements = strip->getNrOfVerts(); BufferDesc.Type = VERTEX_BUFFER; BufferDesc.Usage = BUFFER_DEFAULT; // Create the buffer Buffer* VertexBuffer = new Buffer(); if(FAILED(VertexBuffer->Init(this->Dx_Device, this->Dx_DeviceContext, BufferDesc))) MaloW::Debug("Failed to init skybox"); BUFFER_INIT_DESC indiceBufferDesc; indiceBufferDesc.ElementSize = sizeof(int); indiceBufferDesc.InitData = strip->getIndicies(); indiceBufferDesc.NumElements = strip->getNrOfIndicies(); indiceBufferDesc.Type = INDEX_BUFFER; indiceBufferDesc.Usage = BUFFER_DEFAULT; Buffer* IndexBuffer = new Buffer(); if(FAILED(IndexBuffer->Init(this->Dx_Device, this->Dx_DeviceContext, indiceBufferDesc))) MaloW::Debug("Failed to init skybox"); D3DX11_IMAGE_LOAD_INFO loadSMInfo; loadSMInfo.MiscFlags = D3D11_RESOURCE_MISC_TEXTURECUBE; ID3D11Texture2D* SMTexture = 0; D3DX11CreateTextureFromFile(this->Dx_Device, texture.c_str(), &loadSMInfo, 0, (ID3D11Resource**)&SMTexture, 0); D3D11_TEXTURE2D_DESC SMTextureDesc; SMTexture->GetDesc(&SMTextureDesc); D3D11_SHADER_RESOURCE_VIEW_DESC SMViewDesc; SMViewDesc.Format = SMTextureDesc.Format; SMViewDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURECUBE; SMViewDesc.TextureCube.MipLevels = SMTextureDesc.MipLevels; SMViewDesc.TextureCube.MostDetailedMip = 0; ID3D11ShaderResourceView* text; this->Dx_Device->CreateShaderResourceView(SMTexture, &SMViewDesc, &text); SMTexture->Release(); Object3D* ro = new Object3D(VertexBuffer, IndexBuffer, text, sb->GetTopology()); strip->SetRenderObject(ro); this->skybox = sb; }
Scene *SceneBuilder::build() { PRINT_GL_ERROR(); Camera *camera = new Camera(); PRINT_GL_ERROR(); // camera->setMouse(QCursor::pos().x(), QCursor::pos().y()); camera->setMouse(0, 0); camera->reset(); PRINT_GL_ERROR(); SkyBox *skyBox = new SkyBox( new MaterialSkyBox(new TextureCube("data/resources/cubemaps/miramar/"))); PRINT_GL_ERROR(); skyBox->setPosition(camera->getPosition()); PRINT_GL_ERROR(); // SUN Texture::resetUnit(); PRINT_GL_ERROR(); Texture *sunDiffuse = Texture::newFromNextUnit(); PRINT_GL_ERROR(); Texture *sunAlpha = Texture::newFromNextUnit(); PRINT_GL_ERROR(); sunDiffuse->load("data/resources/maps/sun/sun_1k.png"); PRINT_GL_ERROR(); sunDiffuse->setFilters(GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR); PRINT_GL_ERROR(); sunDiffuse->init(); PRINT_GL_ERROR(); sunAlpha->load("data/resources/maps/sun/sun_1k_alpha.png"); PRINT_GL_ERROR(); sunAlpha->setFilters(GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR); PRINT_GL_ERROR(); sunAlpha->init(); PRINT_GL_ERROR(); MaterialSun *sunMat = new MaterialSun(sunDiffuse, sunAlpha); PRINT_GL_ERROR(); Sun *sun = new Sun(sunMat); PRINT_GL_ERROR(); // GROUND Texture::resetUnit(); // diffuses Texture *groundMoss = Texture::newFromNextUnit(); Texture *groundEarth = Texture::newFromNextUnit(); Texture *groundShatter = Texture::newFromNextUnit(); groundMoss->load("data/resources/maps/ground/moss.png"); groundMoss->setFilters(GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR); groundMoss->init(); groundEarth->load("data/resources/maps/ground/earth.png"); groundEarth->setFilters(GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR); groundEarth->init(); groundShatter->load("data/resources/maps/ground/shatter.png"); groundShatter->setFilters(GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR); groundShatter->init(); PRINT_GL_ERROR(); // normals Texture *groundNormalMoss = Texture::newFromNextUnit(); Texture *groundNormalEarth = Texture::newFromNextUnit(); Texture *groundNormalShatter = Texture::newFromNextUnit(); groundNormalMoss->load("data/resources/maps/ground/moss_normal.png"); groundNormalMoss->setFilters(GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR); groundNormalMoss->init(); groundNormalEarth->load("data/resources/maps/ground/earth_normal.png"); groundNormalEarth->setFilters(GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR); groundNormalEarth->init(); groundNormalShatter->load("data/resources/maps/ground/shatter_normal.png"); groundNormalShatter->setFilters(GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR); groundNormalShatter->init(); PRINT_GL_ERROR(); // init MaterialGround *groundMat = new MaterialGround( groundMoss, groundEarth, groundShatter, groundNormalMoss, groundNormalEarth, groundNormalShatter); Ground *ground = new Ground("data/resources/heightmaps/heightmap.png", groundMat); PRINT_GL_ERROR(); // ROCK 1 Texture::resetUnit(); PRINT_GL_ERROR(); Texture *rock1Diffuse = Texture::newFromNextUnit(); Texture *rock1Alpha = Texture::newFromNextUnit(); Mesh *rock1 = ObjLoader::loadObj("data/resources/meshes/rock1/rock1.obj"); rock1Diffuse->load("data/resources/maps/rock1/rock1_1k.png"); rock1Diffuse->setFilters(GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR); rock1Diffuse->init(); rock1Alpha->load("data/resources/maps/noalpha.png"); rock1Alpha->setFilters(GL_NEAREST, GL_NEAREST); rock1Alpha->init(); ((MaterialBasic *)(rock1->getMaterial()))->setDiffuse(rock1Diffuse); ((MaterialBasic *)(rock1->getMaterial()))->setAlpha(rock1Alpha); rock1->setPosition(Vector3(-3, 0.5, 0)); rock1->setScale(Vector3(0.6, 0.6, 0.6)); rock1->setScale(Vector3(0.0, 0.0, 0.0)); rock1->setScaleRdn(0.2); rock1->setHeightRdn(0.5); rock1->setPourcentage(0.2); rock1->setInstanceType(Mesh::INSTANCE_ROCK); rock1->setRangeScale(0.4); createInstances(rock1, ground, NB_INSTANCE * rock1->getPourcentage()); PRINT_GL_ERROR(); // PALM TREE Texture::resetUnit(); Texture *palmDiffuse = Texture::newFromNextUnit(); Texture *palmAlpha = Texture::newFromNextUnit(); Mesh *palm = ObjLoader::loadObj("data/resources/meshes/palmtree/palmtree.obj"); palmDiffuse->load("data/resources/maps/palmtree/palmtree_1k.png"); palmDiffuse->setFilters(GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR); palmDiffuse->init(); palmAlpha->load("data/resources/maps/palmtree/palmtree_1k_alpha.png"); palmAlpha->setFilters(GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR); palmAlpha->init(); ((MaterialBasic *)(palm->getMaterial()))->setDiffuse(palmDiffuse); ((MaterialBasic *)(palm->getMaterial()))->setAlpha(palmAlpha); palm->setPosition(Vector3(0, 0, -10)); palm->setScale(Vector3(2, 2, 2)); palm->setScale(Vector3(0, 0, 0)); palm->setScaleRdn(0.8); palm->setHeightRdn(-2.5); palm->setPourcentage(0.07); palm->setInstanceType(Mesh::INSTANCE_PALM); palm->setRangeScale(0.8); createInstances(palm, ground, NB_INSTANCE * palm->getPourcentage()); PRINT_GL_ERROR(); // HIGH TREE Texture::resetUnit(); Texture *htreeDiffuse = Texture::newFromNextUnit(); Texture *htreeAlpha = Texture::newFromNextUnit(); Mesh *htree = ObjLoader::loadObj("data/resources/meshes/hightree/hightree.obj"); htreeDiffuse->load("data/resources/maps/hightree/hightree_1k.png"); htreeDiffuse->setFilters(GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR); htreeDiffuse->init(); htreeAlpha->load("data/resources/maps/hightree/hightree_1k_alpha.png"); htreeAlpha->setFilters(GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR); htreeAlpha->init(); ((MaterialBasic *)(htree->getMaterial()))->setDiffuse(htreeDiffuse); ((MaterialBasic *)(htree->getMaterial()))->setAlpha(htreeAlpha); htree->setPosition(Vector3(-6, 2, -16)); htree->setScale(Vector3(0.6, 0.6, 0.6)); htree->setScale(Vector3(0, 0, 0)); htree->setScaleRdn(0.3); htree->setHeightRdn(-2.0); htree->setPourcentage(0.3); htree->setInstanceType(Mesh::INSTANCE_HTREE); htree->setRangeScale(0.4); createInstances(htree, ground, NB_INSTANCE * htree->getPourcentage()); PRINT_GL_ERROR(); // BAMBOO PALM Texture::resetUnit(); Texture *btreeDiffuse = Texture::newFromNextUnit(); Texture *btreeAlpha = Texture::newFromNextUnit(); Mesh *btree = ObjLoader::loadObj("data/resources/meshes/bamboopalm/bamboopalm.obj"); btreeDiffuse->load("data/resources/maps/bamboopalm/bamboopalm_1k.png"); btreeDiffuse->setFilters(GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR); btreeDiffuse->init(); btreeAlpha->load("data/resources/maps/bamboopalm/bamboopalm_1k_alpha.png"); btreeAlpha->setFilters(GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR); btreeAlpha->init(); ((MaterialBasic *)(btree->getMaterial()))->setDiffuse(btreeDiffuse); ((MaterialBasic *)(btree->getMaterial()))->setAlpha(btreeAlpha); btree->setPosition(Vector3(-4, -2, 4)); btree->setScale(Vector3(0.6, 0.6, 0.6)); btree->setScale(Vector3(0, 0, 0)); btree->setScaleRdn(0.3); btree->setHeightRdn(-2.0); btree->setPourcentage(0.15); btree->setInstanceType(Mesh::INSTANCE_BTREE); btree->setRangeScale(1.0); createInstances(btree, ground, NB_INSTANCE * btree->getPourcentage()); PRINT_GL_ERROR(); // GROUND PALM Texture::resetUnit(); Texture *gpalmDiffuse = Texture::newFromNextUnit(); Texture *gpalmAlpha = Texture::newFromNextUnit(); Mesh *gpalm = ObjLoader::loadObj("data/resources/meshes/groundpalm/groundpalm.obj"); gpalmDiffuse->load("data/resources/maps/groundpalm/groundpalm_1k.png"); gpalmDiffuse->setFilters(GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR); gpalmDiffuse->init(); gpalmAlpha->load("data/resources/maps/groundpalm/groundpalm_1k_alpha.png"); gpalmAlpha->setFilters(GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR); gpalmAlpha->init(); ((MaterialBasic *)(gpalm->getMaterial()))->setDiffuse(gpalmDiffuse); ((MaterialBasic *)(gpalm->getMaterial()))->setAlpha(gpalmAlpha); gpalm->setPosition(Vector3(-3, -1, 0)); gpalm->setScaleRdn(0.9); gpalm->setScale(Vector3(0, 0, 0)); gpalm->setHeightRdn(-1.0); gpalm->setPourcentage(0.14); gpalm->setInstanceType(Mesh::INSTANCE_GPALM); gpalm->setRangeScale(0.4); createInstances(gpalm, ground, NB_INSTANCE * gpalm->getPourcentage()); PRINT_GL_ERROR(); // SMALL PLANT 1 /*Texture::resetUnit(); Texture* splant1Diffuse = Texture::newFromNextUnit(); Texture* splant1Alpha = Texture::newFromNextUnit(); Mesh* splant1 = ObjLoader::loadObj("data/resources/meshes/smallplant1/smallplant1.obj"); splant1Diffuse->load("data/resources/maps/smallplant1/smallplant1.png"); splant1Diffuse->setFilters(GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR_MIPMAP_LINEAR); splant1Diffuse->init(); splant1Alpha->load("data/resources/maps/smallplant1/smallplant1_alpha.png"); splant1Alpha->setFilters(GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR_MIPMAP_LINEAR); splant1Alpha->init(); ((MaterialBasic*)(splant1->getMaterial()))->setDiffuse(splant1Diffuse); ((MaterialBasic*)(splant1->getMaterial()))->setAlpha(splant1Alpha); splant1->setPosition(Vector3(2,4,-8)); splant1->setScale(Vector3(0.6,0.6,0.6)); splant1->castsShadows(true);*/ // BUSH 1 Texture::resetUnit(); Texture *bush1Diffuse = Texture::newFromNextUnit(); Texture *bush1Alpha = Texture::newFromNextUnit(); Mesh *bush1 = ObjLoader::loadObj("data/resources/meshes/bush1/bush1.obj"); bush1Diffuse->load("data/resources/maps/bush1/bush1_1k.png"); bush1Diffuse->setFilters(GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR); bush1Diffuse->init(); bush1Alpha->load("data/resources/maps/bush1/bush1_1k_alpha.png"); bush1Alpha->setFilters(GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR); bush1Alpha->init(); ((MaterialBasic *)(bush1->getMaterial()))->setDiffuse(bush1Diffuse); ((MaterialBasic *)(bush1->getMaterial()))->setAlpha(bush1Alpha); bush1->setPosition(Vector3(-3, 0, 0)); bush1->setScale(Vector3(0.6, 0.6, 0.6)); bush1->setScale(Vector3(0, 0, 0)); bush1->setScaleRdn(0.3); bush1->setHeightRdn(0.0); bush1->setPourcentage(0.14); bush1->setInstanceType(Mesh::INSTANCE_BUSH); bush1->setRangeScale(0.4); createInstances(bush1, ground, NB_INSTANCE * bush1->getPourcentage()); PRINT_GL_ERROR(); Scene *scene = new Scene(); scene->addCamera(camera); scene->setCurrentCamera(camera); scene->setSky(skyBox); scene->setSun(sun); scene->setGround(ground); PRINT_GL_ERROR(); scene->addMesh(rock1); scene->addMesh(palm); scene->addMesh(gpalm); // scene->addMesh(splant1); scene->addMesh(htree); scene->addMesh(btree); scene->addMesh(bush1); PRINT_GL_ERROR(); scene2 = scene; ground2 = ground; PRINT_GL_ERROR(); return scene; }
int main(int , char**) { int width = 1280, height = 760; Display mainWindow(width, height, "DEngine"); //mainWindow.ShowCursor(false); mainWindow.WrapMouse(false); glm::vec3 lightPosition(-4.0f, 8.0f, -6.0f); Light sun(lightPosition, glm::vec3(1.0f, 1.0f, 1.0f), DIRECTIONAL_LIGHT); Camera camera(glm::vec3(0.0f, 2.0f, 1.0f)); camera.SetCameraMode(FLY); Shader simpleProgram; simpleProgram.LoadShaders("./SHADERS/SOURCE/NoNormal_vs.glsl", "./SHADERS/SOURCE/NoNormal_fs.glsl"); Shader skyBoxShaders; skyBoxShaders.LoadShaders("./SHADERS/SOURCE/skyBox_vs.glsl", "./SHADERS/SOURCE/skyBox_fs.glsl"); Shader shadowShaders; shadowShaders.LoadShaders("./SHADERS/SOURCE/ShadowDepth_vs.glsl", "./SHADERS/SOURCE/ShadowDepth_fs.glsl"); EventListener eventListener(&mainWindow, &camera, &simpleProgram); SkyBox sky; sky.LoadCubeMap("./Models/skybox"); Model box; box.LoadModelFromFile(".\\Models\\Box.obj"); box.TranslateModel(glm::vec3(0.0f, 2.0f, 0.0f)); box.meshes[0].AddTexture("./Models/textures/154.png", textureType::DIFFUSE_MAP); box.meshes[0].AddTexture("./Models/textures/154_norm.png", textureType::NORMAL_MAP); box.meshes[0].AddTexture("./Models/textures/154s.png", textureType::SPECULAR_MAP); box.TranslateModel(glm::vec3(0.0f, -0.5f, -2.0f)); Model floor; floor.LoadModelFromFile("./Models/Plane/plane.obj"); floor.meshes[0].AddTexture("./Models/textures/196.png", textureType::DIFFUSE_MAP); floor.meshes[0].AddTexture("./Models/textures/196_norm.png", textureType::NORMAL_MAP); floor.meshes[0].AddTexture("./Models/textures/196s.png", textureType::SPECULAR_MAP); floor.TranslateModel(glm::vec3(0.0f, -2.0f, 0.0f)); Clock clock; while (!mainWindow.isClosed) { eventListener.Listen(); clock.NewFrame(); //DRAWING SCENE TO SHADOWMAP //sun.StartDrawingShadows(shadowShaders.programID); // //glCullFace(GL_FRONT); ////nanosuit.Draw(&mainWindow, camera, &sun, shadowShaders); //box.Draw(&mainWindow, camera, &sun, shadowShaders); //floor.Draw(&mainWindow, camera, &sun, shadowShaders); // //sun.StopDrawingShadows(); // //glCullFace(GL_BACK); //glViewport(0, 0, width, height); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //NORMAL DRAWING SCENE simpleProgram.UseProgram(); glUniformMatrix4fv(glGetUniformLocation(simpleProgram.programID, "lightSpaceMatrix"), 1, GL_FALSE, glm::value_ptr(sun.shadowMatrix)); glUniform1f(glGetUniformLocation(simpleProgram.programID, "time"), clock.time); //glActiveTexture(GL_TEXTURE15); //glBindTexture(GL_TEXTURE_2D, sun.shadowTexture.textureID); //glUniform1i(glGetUniformLocation(simpleProgram.programID, "depth_map"), 15); floor.Draw(&mainWindow, camera, &sun, simpleProgram); box.Draw(&mainWindow, camera, &sun, simpleProgram); //sky.Draw(&mainWindow, camera, skyBoxShaders); camera.Update(clock.deltaTime); mainWindow.Update(); } return 0; }
int main(int argc, char** argv) { if (!glfwInit()) // 初始化glfw库 { std::cout << "Error::GLFW could not initialize GLFW!" << std::endl; return -1; } // 开启OpenGL 3.3 core profile std::cout << "Start OpenGL core profile version 3.3" << std::endl; glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // 创建窗口 GLFWwindow* window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Demo of EnviromentMapping(reflection)", NULL, NULL); if (!window) { std::cout << "Error::GLFW could not create winddow!" << std::endl; glfwTerminate(); std::system("pause"); return -1; } // 创建的窗口的context指定为当前context glfwMakeContextCurrent(window); // 注册窗口键盘事件回调函数 glfwSetKeyCallback(window, key_callback); // 注册鼠标事件回调函数 glfwSetCursorPosCallback(window, mouse_move_callback); // 注册鼠标滚轮事件回调函数 glfwSetScrollCallback(window, mouse_scroll_callback); // 鼠标捕获 停留在程序内 glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // 初始化GLEW 获取OpenGL函数 glewExperimental = GL_TRUE; // 让glew获取所有拓展函数 GLenum status = glewInit(); if (status != GLEW_OK) { std::cout << "Error::GLEW glew version:" << glewGetString(GLEW_VERSION) << " error string:" << glewGetErrorString(status) << std::endl; glfwTerminate(); std::system("pause"); return -1; } // 设置视口参数 glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); //Section1 加载模型数据 Model objModel; if (!objModel.loadModel("../../resources/models/sphere/sphere.obj")) { glfwTerminate(); std::system("pause"); return -1; } // Section2 创建Skybox std::vector<const char*> faces; faces.push_back("../../resources/skyboxes/sky/sky_rt.jpg"); faces.push_back("../../resources/skyboxes/sky/sky_lf.jpg"); faces.push_back("../../resources/skyboxes/sky/sky_up.jpg"); faces.push_back("../../resources/skyboxes/sky/sky_dn.jpg"); faces.push_back("../../resources/skyboxes/sky/sky_bk.jpg"); faces.push_back("../../resources/skyboxes/sky/sky_ft.jpg"); SkyBox skybox; skybox.init(faces); // Section3 准备着色器程序 Shader shader("scene.vertex", "scene.frag"); Shader skyBoxShader("skybox.vertex", "skybox.frag"); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glDepthFunc(GL_LESS); // 开始游戏主循环 while (!glfwWindowShouldClose(window)) { GLfloat currentFrame = (GLfloat)glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; glfwPollEvents(); // 处理例如鼠标 键盘等事件 do_movement(); // 根据用户操作情况 更新相机属性 // 设置colorBuffer颜色 glClearColor(0.18f, 0.04f, 0.14f, 1.0f); // 清除colorBuffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // 先绘制场景 shader.use(); glm::mat4 projection = glm::perspective(camera.mouse_zoom, (GLfloat)(WINDOW_WIDTH) / WINDOW_HEIGHT, 0.1f, 100.0f); // 投影矩阵 glUniformMatrix4fv(glGetUniformLocation(shader.programId, "projection"), 1, GL_FALSE, glm::value_ptr(projection)); glm::mat4 view = camera.getViewMatrix(); // 视变换矩阵 glUniformMatrix4fv(glGetUniformLocation(shader.programId, "view"), 1, GL_FALSE, glm::value_ptr(view)); glm::mat4 model; // model = glm::translate(model, glm::vec3(0.0f, -1.55f, 0.0f)); // 适当下调位置 // model = glm::scale(model, glm::vec3(0.2f, 0.2f, 0.2f)); // 适当缩小模型 glUniformMatrix4fv(glGetUniformLocation(shader.programId, "model"), 1, GL_FALSE, glm::value_ptr(model)); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_CUBE_MAP, skybox.getTextId()); glUniform1i(glGetUniformLocation(shader.programId, "envText"), 0); glUniform3f(glGetUniformLocation(shader.programId, "cameraPos"), camera.position.x, camera.position.y, camera.position.z); // 注意设置观察者位置 objModel.draw(shader); // 绘制球体 // 然后绘制包围盒 skyBoxShader.use(); view = glm::mat4(glm::mat3(camera.getViewMatrix())); // 视变换矩阵 移除translate部分 glUniformMatrix4fv(glGetUniformLocation(skyBoxShader.programId, "projection"), 1, GL_FALSE, glm::value_ptr(projection)); glUniformMatrix4fv(glGetUniformLocation(skyBoxShader.programId, "view"), 1, GL_FALSE, glm::value_ptr(view)); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_CUBE_MAP, skybox.getTextId()); glUniform1i(glGetUniformLocation(skyBoxShader.programId, "skybox"), 0); skybox.draw(skyBoxShader); glBindVertexArray(0); glUseProgram(0); glfwSwapBuffers(window); // 交换缓存 } // 释放资源 glfwTerminate(); return 0; }
DemoScene( unsigned int windowWidth, unsigned int windowHeight, bool fullscreen, unsigned int multisample ) : time(0.0f), fps(0.0f), dt(0.0f), drawHelp(true), needToTakeScreenshot(false) { Engine* engine = Engine::Instance(); // setup graphics { using namespace slon::scene; using namespace slon::animation; // setup logging { log::currentLogManager().redirectOutput("database", "database_log.txt"); log::currentLogManager().redirectOutput("graphics", "graphics_log.txt"); } GraphicsManager& graphicsManager = engine->getGraphicsManager(); graphicsManager.setVideoMode(windowWidth, windowHeight, 32, fullscreen, false, multisample); // create renderer { ForwardRendererDesc desc; desc.useDepthPass = true; desc.makeDepthMap = true; desc.useDebugRender = true; Renderer* renderer = graphicsManager.initRenderer(desc); renderer->connectPostRenderCallback( boost::bind(&DemoScene::OnPostRender, this, _1) ); } #ifdef WIN32 FreeConsole(); #endif // create world realm::World* world = realm::currentWorld(); realm::location_ptr location(new realm::BVHLocation); world->addLocation(location); // Create skybox SkyBox* skyBox = new SkyBox(); { const std::string SKY_BOX_MAPS[6] = { "Data/SkyBox/sunset_west.jpg", "Data/SkyBox/sunset_east.jpg", "Data/SkyBox/sunset_up.jpg", "Data/SkyBox/sunset_down.jpg", "Data/SkyBox/sunset_south.jpg", "Data/SkyBox/sunset_north.jpg" }; skyBox->MakeFromSideTextures(SKY_BOX_MAPS); } world->addInfiniteNode(skyBox); // create scene { database::library_ptr library = database::loadLibrary("Data/Models/troll.DAE"); location->add(library->visualScenes.begin()->second.get()); database::Library::key_animation_map animations = library->animations; if ( !animations.empty() ) { StartStopTimer* timer = new StartStopTimer(); timer->start(); animations.begin()->second->play(timer); } // create light scene::DirectionalLight* light = new DirectionalLight(); light->setDirection( normalize( Vector3f(-1.5f, -0.1f, 0.85f) ) ); light->setColor( Vector4f(0.8f, 0.8f, 0.8f, 1.0f) ); light->setAmbient(0.3f); light->setIntensity(1.5f); world->addInfiniteNode(light); } // Create camera { sgl::rectangle viewport(0, 0, windowWidth, windowHeight); camera.reset( createMainCamera(viewport) ); graphicsManager.addCamera( camera.get() ); } camera->setPosition( Vector3f(60.0f, 20.0f, 0.0f) ); camera->setDirection( Vector3f(-1.0f, -1.0f, 1.0f) ); camera->setUp( Vector3f(0.0f, 1.0f, 0.0f) ); // create font font.reset( currentDevice()->CreateFont() ); { sgl::Image* image = currentDevice()->CreateImage(); image->LoadFromFile("Data/Fonts/font.png"); font->SetTexture( image->CreateTexture2D() ); } } // setup input { using boost::bind; using namespace slon::input; using namespace slon::thread; InputManager& inputManager = engine->getInputManager(); inputManager.showCursor(false); // fix cursor in the window center Vector2ui cursorPosition = screenSize / 2 ; inputManager.setCursorPosition(cursorPosition.x, cursorPosition.y); inputManager.fixCursorPosition(cursorPosition.x, cursorPosition.y); keyboardHandler.reset( new KeyboardHandler() ); inputManager.addInputHandler( keyboardHandler.get() ); keyboardHandler->connectKeyPressEventHandler( input::KEY_F1, bind(&DemoScene::toggleHelpText, this) ); keyboardHandler->connectKeyPressEventHandler( input::KEY_F2, bind(&DemoScene::toggleWireframe, this) ); keyboardHandler->connectKeyPressEventHandler( input::KEY_F9, bind(&DemoScene::takeScreenShot, this) ); keyboardHandler->connectKeyPressEventHandler( input::KEY_ESCAPE, bind(&DemoScene::stopDemo, this) ); keyboardHandler->connectKeyDownHandler( input::KEY_w, bind(&DemoScene::flyCamera, this, math::Vector3f( 0.0f, 0.0f, 10.0f)) ); keyboardHandler->connectKeyDownHandler( input::KEY_s, bind(&DemoScene::flyCamera, this, math::Vector3f( 0.0f, 0.0f, -10.0f)) ); keyboardHandler->connectKeyDownHandler( input::KEY_d, bind(&DemoScene::flyCamera, this, math::Vector3f( 10.0f, 0.0f, 0.0f)) ); keyboardHandler->connectKeyDownHandler( input::KEY_a, bind(&DemoScene::flyCamera, this, math::Vector3f(-10.0f, 0.0f, 0.0f)) ); keyboardHandler->connectKeyDownHandler( input::KEY_q, bind(&DemoScene::flyCamera, this, math::Vector3f( 0.0f, 10.0f, 0.0f)) ); keyboardHandler->connectKeyDownHandler( input::KEY_e, bind(&DemoScene::flyCamera, this, math::Vector3f( 0.0f, -10.0f, 0.0f)) ); // setup mouse input MouseHandler* mouseHandler = new MouseHandler(); inputManager.addInputHandler(mouseHandler); mouseHandler->connectRelativeMouseMotionEventHandler( bind(&DemoScene::turnCamera, this, _1, _2) ); } Engine::DESC desc; desc.multithreaded = false; desc.grabInput = true; engine->run(desc); }
static int engine_init_display(struct engine* engine) { // initialize OpenGL ES and EGL const EGLint attribs[] = { EGL_NATIVE_VISUAL_ID, WINDOW_FORMAT_RGB_565, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_BLUE_SIZE, 5, EGL_GREEN_SIZE, 6, EGL_RED_SIZE, 5, EGL_DEPTH_SIZE,1, EGL_NONE }; EGLint w, h, dummy, format; EGLint numConfigs; EGLConfig config; EGLSurface surface; EGLContext context; EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); EGLint majorVersion; EGLint minorVersion; eglInitialize(display, &majorVersion, &minorVersion); //eglInitialize(display, 0, 0); LOGI("OpenGL %i.%i", majorVersion,minorVersion); //query num of configs int* num_conf = new int[1]; eglGetConfigs(display, NULL, 0, num_conf); //if configuration array is null it still returns the number of configurations int configurations = num_conf[0]; LOGI("total num configs: %i", configurations); //just some debugging info if the need arises... LOGI("EGL_OPENGL_ES2_BIT id:%i", EGL_OPENGL_ES2_BIT); //print the numerical code for the ES2 bit mask, etc LOGI("EGL_SURFACE_TYPE::EGL_WINDOW_BIT id:%i", EGL_WINDOW_BIT); LOGI("WINDOW_FORMAT_RGB_565 id:%i", WINDOW_FORMAT_RGB_565); //now query the configs EGLConfig* conf = new EGLConfig[configurations]; eglGetConfigs(display, conf, configurations, num_conf); int* depth = new int[1]; int* r = new int[1]; int* g = new int[1]; int* b = new int[1]; int* a = new int[1]; int* s = new int[1]; int* renderType = new int[1]; int* surfaceType = new int[1]; int* formatType = new int[1]; EGLConfig configToUse; //this is the one true config that we will use for(int i = 0; i < configurations; i++) { eglGetConfigAttrib(display, conf[i], EGL_DEPTH_SIZE, depth); eglGetConfigAttrib(display, conf[i], EGL_RED_SIZE, r); eglGetConfigAttrib(display, conf[i], EGL_GREEN_SIZE, g); eglGetConfigAttrib(display, conf[i], EGL_BLUE_SIZE, b); eglGetConfigAttrib(display, conf[i], EGL_ALPHA_SIZE, a); eglGetConfigAttrib(display, conf[i], EGL_RENDERABLE_TYPE, renderType); eglGetConfigAttrib(display, conf[i], EGL_STENCIL_SIZE, s); eglGetConfigAttrib(display, conf[i], EGL_SURFACE_TYPE, surfaceType); eglGetConfigAttrib(display, conf[i], EGL_NATIVE_VISUAL_ID, formatType); LOGI("(R%i,G%i,B%i,A%i)depth:(%i) stencil:(%i) surfaceType:(%i) renderType:(%i) formatType:(%i)",r[0],g[0],b[0],a[0],depth[0],s[0],surfaceType[0], renderType[0],formatType[0]); if((renderType[0] & EGL_OPENGL_ES2_BIT) > 0 && (surfaceType[0] & EGL_WINDOW_BIT) > 0 && (formatType[0] & WINDOW_FORMAT_RGB_565) > 0 && depth[0]>0) { configToUse=conf[i]; LOGI("Config #%i" , i ); LOGI("(R%i,G%i,B%i,A%i) %idepth %istencil %isurfaceType %iNativeVisualId",r[0],g[0],b[0],a[0],depth[0],s[0],surfaceType[0],formatType[0]); } } //bridge the pixel format back into android eglGetConfigAttrib(display, configToUse, EGL_NATIVE_VISUAL_ID, &format); ANativeWindow_setBuffersGeometry(engine->app->window, 0, 0, format); surface = eglCreateWindowSurface(display, configToUse, engine->app->window, NULL); if(surface == EGL_NO_SURFACE ) { LOGW("Error making surface, EGL_NO_SURFACE"); } //now create the OpenGL ES2 context const EGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION , 2, EGL_NONE }; context = eglCreateContext(display, configToUse, NULL, contextAttribs); if(context == EGL_NO_CONTEXT ) { LOGW("Error making context, EGL_NO_CONTEXT"); } if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) { LOGW("Unable to eglMakeCurrent"); return -1; } eglQuerySurface(display, surface, EGL_WIDTH, &w); eglQuerySurface(display, surface, EGL_HEIGHT, &h); ContextWidth = w; ContextHeight = h; engine->display = display; engine->context = context; engine->surface = surface; engine->width = w; engine->height = h; engine->state.angle = 0; glEnable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); //GLubyte* rendererString = new GLubyte[512]; const GLubyte* rendererString = rendererString=glGetString(GL_VERSION); LOGI("Renderer: %s",rendererString); // // // LOAD ALL RESOURCES // // ////////////////// // PHONG SHADER // ////////////////// if(!PhongShader.createShader((char*)"phong.vs",(char*)"phong.fs")) { LOGE("Could not create phong program."); return false; } PositionAttributes = glGetAttribLocation(PhongShader.ID, "aPosition"); NormalAttributes = glGetAttribLocation(PhongShader.ID, "aNormal"); TexCoordAttributes = glGetAttribLocation(PhongShader.ID, "aTexCoords"); MVPMatrixUniform = glGetUniformLocation( PhongShader.ID, "MVPMatrixUniform" ); EyePosUniform = glGetUniformLocation(PhongShader.ID,"EyePosUniform"); LightPosUniform = glGetUniformLocation(PhongShader.ID,"LightPosUniform"); TextureSampler = glGetUniformLocation(PhongShader.ID,"sTexture"); LOGI("===PHONG-DEBUG VALUES==="); LOGI("PositionAttributes: %i",PositionAttributes); LOGI("NormalAttributes: %i",NormalAttributes); LOGI("TexCoordAttributes: %i",TexCoordAttributes); LOGI("MVPMatrixUniform: %i",MVPMatrixUniform); LOGI("EyePosUniform: %i",EyePosUniform); LOGI("LightPosUniform: %i",LightPosUniform); LOGI("TextureSampler: %i",TextureSampler); LOGI("===END==="); ////////////////// // DEPTH SHADER // ////////////////// if(!DepthShader.createShader((char*)"depthcolor.vs",(char*)"depthcolor.fs")) { LOGE("Could not create depth shader program."); return false; } DepthShaderMVPMatrixUniform = glGetUniformLocation(DepthShader.ID, "MVPMatrixUniform"); DepthShaderPositionAttributes = glGetAttribLocation(DepthShader.ID, "aPosition"); LOGI("===DEPTH-DEBUG VALUES==="); LOGI("DepthShaderPositionAttributes: %i",DepthShaderPositionAttributes); LOGI("DepthShaderMVPMatrixUniform: %i",DepthShaderMVPMatrixUniform); LOGI("===END==="); ///////////////////////////////// // TEXPASSTHRU (SKYBOX) SHADER // ///////////////////////////////// if(!TexPassThruShader.createShader((char*)"texpassthru.vs",(char*)"texpassthru.fs")) { LOGE("Could not create texpassthru program."); return false; } TexPassThruSampler = glGetUniformLocation(TexPassThruShader.ID,"sTexture"); TexPassThruMVPMatrixUniform = glGetUniformLocation(TexPassThruShader.ID,"MVPMatrixUniform"); TexPassThruPositionAttributes = glGetAttribLocation(TexPassThruShader.ID, "aPosition"); TexPassThruTexCoordAttributes = glGetAttribLocation(TexPassThruShader.ID, "aTexCoords"); LOGI("===TEXPASSTHRU-DEBUG VALUES==="); LOGI("TexPassThruSampler: %i",TexPassThruSampler); LOGI("TexPassThruMVPMatrixUniform: %i",TexPassThruMVPMatrixUniform); LOGI("TexPassThruPositionAttributes: %i",TexPassThruPositionAttributes); LOGI("TexPassThruTexCoordAttributes: %i",TexPassThruTexCoordAttributes); LOGI("===END==="); //////////////////////// // ENVIRONMENT SHADER // //////////////////////// if (!EnvironmentMappingShader.createShader((char*)"environmentcubemap.vs",(char*)"environmentcubemap.fs")) { LOGE("Could not create program."); return false; } EnvironmentMappingShaderMVPMatrixUniform=glGetUniformLocation(EnvironmentMappingShader.ID,"MVPMatrixUniform"); EnvironmentMappingShaderPositionAttributes=glGetAttribLocation(EnvironmentMappingShader.ID, "aPosition"); EnvironmentMappingShaderNormalAttributes=glGetAttribLocation(EnvironmentMappingShader.ID, "aNormal"); EnvironmentMappingShaderCubeSampler=glGetUniformLocation(EnvironmentMappingShader.ID,"sCubeTexture"); LOGI("===ENVIRONMENT-DEBUG VALUES==="); LOGI("EnvironmentMappingShaderCubeSampler: %i",EnvironmentMappingShaderCubeSampler); LOGI("EnvironmentMappingShaderMVPMatrixUniform: %i",EnvironmentMappingShaderMVPMatrixUniform); LOGI("EnvironmentMappingShaderPositionAttributes: %i",EnvironmentMappingShaderPositionAttributes); LOGI("TexPassThruTeEnvironmentMappingShaderNormalAttributesxCoordAttributes: %i",EnvironmentMappingShaderNormalAttributes); LOGI("===END==="); //Matrices esMatrixLoadIdentity(&MVPMatrix); //viewport glViewport(0, 0, w, h); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); checkGlError("glViewport"); //load resources internally from the APK StatueMesh.loadMesh((char*)"athena.obj"); checkGlError("loadMesh"); if(!StoneTexture.loadTexture((char*)"rockish.tga")) { LOGE("texture loading FAILED"); } CubeSkyBox.loadSkyBox(); if(!EnvironmentCubeTexture.loadCubeTexture()) LOGE("Could not load cube texture."); return 0; }
//Sets up the appropriate vertice positions for the cube, selects the appropriate indices to form the cube, //then intiailizes the mesh so we can copy the mesh related data(indices/triangledata) to the mesh so we are ready //for setting the material. We set up the position, intialize the material and load in the cube texture then set //the material/mesh and transform then check to make sure no errors occur. void SplashScreen::createSkyBox() { Vertex triangleData[] = { { vec3(-50.0f, 50.0f, 50.0f) },// Top Left { vec3(-50.0f, -50.0f, 50.0f) },// Bottom Left { vec3(50.0f, -50.0f, 50.0f) }, //Bottom Right { vec3(50.0f, 50.0f, 50.0f) },// Top Right { vec3(-50.0f, 50.0f, -50.0f) },// Top Left { vec3(-50.0f, -50.0f, -50.0f) },// Bottom Left { vec3(50.0, -50.0f, -50.0f) }, //Bottom Right { vec3(50.0f, 50.0f, -50.0f) }// Top Right }; GLuint indices[] = { //front 0, 1, 2, 3, 2, 0, //left 3, 2, 6, 6, 7, 3, //right 7, 6, 5, 5, 4, 7, //bottom 4, 5, 1, 1, 0, 4, //top 4, 0, 3, 3, 7, 4, //back 1, 5, 6, 6, 2, 1 }; ////creat mesh and copy in Mesh * pMesh = new Mesh(); pMesh->init(); pMesh->copyVertexData(8, sizeof(Vertex), (void**)triangleData); pMesh->copyIndexData(36, sizeof(int), (void**)indices); Transform *t = new Transform(); t->setPosition(0.0f, 0.0f, 0.0f); //load textures and skybox material + Shaders SkyBox *material = new SkyBox(); material->init(); std::string vsPath = ASSET_PATH + SHADER_PATH + "/skyVS.glsl"; std::string fsPath = ASSET_PATH + SHADER_PATH + "/skyFS.glsl"; material->loadShader(vsPath, fsPath); std::string posZTexturename = ASSET_PATH + TEXTURE_PATH + "CloudyLightRaysFront2048.png"; std::string negZTexturename = ASSET_PATH + TEXTURE_PATH + "CloudyLightRaysBack2048.png"; std::string posXTexturename = ASSET_PATH + TEXTURE_PATH + "CloudyLightRaysLeft2048.png"; std::string negXTexturename = ASSET_PATH + TEXTURE_PATH + "CloudyLightRaysRight2048.png"; std::string posYTexturename = ASSET_PATH + TEXTURE_PATH + "CloudyLightRaysUp2048.png"; std::string negYTexturename = ASSET_PATH + TEXTURE_PATH + "CloudyLightRaysDown2048.png"; material->loadCubeTexture(posZTexturename, negZTexturename, posXTexturename, negXTexturename, posYTexturename, negYTexturename); //create gameobject but don't add to queue! skyBoxObject = new GameObject(); skyBoxObject->setMaterial(material); skyBoxObject->setTransform(t); skyBoxObject->setMesh(pMesh); GLenum error; do{ error = glGetError(); } while (error != GL_NO_ERROR); }