vector<Texture> ModelLoader::loadMaterialTextures(aiMaterial* mat, aiTextureType type, TextureTypes texType) { TextureLoader textureLoader; vector<Texture> textures; for(GLuint i = 0; i < mat->GetTextureCount(type); i++) { aiString str; mat->GetTexture(type, i, &str); GLboolean skip = false; for(GLuint j = 0; j < textureCache.size(); j++) { if(textureCache[j].path == string(str.C_Str())) { textures.push_back(textureCache[j]); skip = true; break; } } if(!skip) { std::string filepath = directory + '/' + string(str.C_Str()); Texture texture = textureLoader.loadTexture(filepath, texType); texture.path = string(str.C_Str()); textures.push_back(texture); this->textureCache.push_back(texture); } } return textures; }
dp::sg::core::TextureHostSharedPtr loadTextureHost( const std::string & filename, const std::vector<std::string> &searchPaths ) { dp::sg::core::TextureHostSharedPtr tih; // appropriate search paths for the loader dll and the sample file. vector<string> binSearchPaths = searchPaths; std::string curDir = dp::util::getCurrentPath(); if ( find( binSearchPaths.begin(), binSearchPaths.end(), curDir ) == binSearchPaths.end() ) { binSearchPaths.push_back(curDir); } std::string modulePath = dp::util::getModulePath(); if ( find( binSearchPaths.begin(), binSearchPaths.end(), modulePath ) == binSearchPaths.end() ) { binSearchPaths.push_back(modulePath); } std::string ext = dp::util::getFileExtension( filename ); dp::util::UPIID piid = dp::util::UPIID( ext.c_str(), dp::util::UPITID(UPITID_TEXTURE_LOADER, UPITID_VERSION) ); dp::util::PlugIn * plug = 0; // TODO - Update me for stereo images TextureLoader * tls; if ( getInterface( binSearchPaths, piid, plug ) && dp::util::fileExists( filename ) ) { tls = reinterpret_cast<TextureLoader *>(plug); tih = tls->load( filename ); } return tih; }
void Bitmap::Invoke(const Event &event) { if (event.type == Event::COMPLETE) { TextureLoader* loader = (TextureLoader*)(event.target); cache[source_path] = source = loader->getTexture(); inner_size.x = source->width(); inner_size.y = source->height(); loader->removeEventListener(this); loader->deleteLater(); } }
/** * Overwrites the texturize method for the pane */ void Pane::texturize(std::string textureName){ TextureLoader* textureLoader = TextureLoader::getInstance(); GLuint textureId = textureLoader->getTextureId(textureName); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, textureId); //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); }
void Background::DrawBackground() const { TextureLoader* textureLoader = TextureLoader::Instance(); int texBackground = textureLoader->Load("stars.png"); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texBackground); glBegin(GL_QUADS); glTexCoord2f(0.0f, 0.0f); glVertex2f(-1.0f, -1.0f); glTexCoord2f(1.0f, 0.0f); glVertex2f(1.0f, -1.0f); glTexCoord2f(1.0f, 1.0f); glVertex2f(1.0f, 1.0f); glTexCoord2f(0.0f, 1.0f); glVertex2f(-1.0f, 1.0f); glEnd(); glDisable(GL_TEXTURE_2D); }
//---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- void EffectImplemented::UnloadResources() { Setting* loader = GetSetting(); TextureLoader* textureLoader = loader->GetTextureLoader(); if( textureLoader != NULL ) { for( int32_t ind = 0; ind < m_ImageCount; ind++ ) { textureLoader->Unload( m_pImages[ind] ); m_pImages[ind] = NULL; } for (int32_t ind = 0; ind < m_normalImageCount; ind++) { textureLoader->Unload(m_normalImages[ind]); m_normalImages[ind] = NULL; } for (int32_t ind = 0; ind < m_distortionImageCount; ind++) { textureLoader->Unload(m_distortionImages[ind]); m_distortionImages[ind] = NULL; } } SoundLoader* soundLoader = loader->GetSoundLoader(); if( soundLoader != NULL ) { for( int32_t ind = 0; ind < m_WaveCount; ind++ ) { soundLoader->Unload( m_pWaves[ind] ); m_pWaves[ind] = NULL; } } { ModelLoader* modelLoader = loader->GetModelLoader(); if( modelLoader != NULL ) { for( int32_t ind = 0; ind < m_modelCount; ind++ ) { modelLoader->Unload( m_pModels[ind] ); m_pModels[ind] = NULL; } } } }
void GameContextDemo::init() { angle = 0; camera = new Camera(0,0,-200,0); // reset model position TextureLoader loader; loader.loadFile("images/man.jpg"); unsigned char * rawData = loader.getData(); glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_SRC_COLOR); glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 512, 512, 0, GL_RGB, GL_UNSIGNED_BYTE, rawData); texCoords = new GLfloat[8]; texCoords[0] = 0.0; texCoords[1] = 1.0; texCoords[2] = 1.0; texCoords[3] = 1.0; texCoords[4] = 0.0; texCoords[5] = 0.0; texCoords[6] = 1.0; texCoords[7] = 0.0; mVertices = new signed short[12]; mVertices[0] = -80; mVertices[1] = -80; mVertices[2] = 0; mVertices[3] = 80; mVertices[4] = -80; mVertices[5] = 0; mVertices[6] = -80; mVertices[7] = 80; mVertices[8] = 0; mVertices[9] = 80; mVertices[10] = 80; mVertices[11] = 0; glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_SHORT, 0, mVertices); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glPointSize(4); }
Enemy::Enemy(TextureLoader& tl, Vector2f position) { type = 'n'; _sprite = (tl.getSprite("player")); _sprite.setColor(Color::Red); middleOrigin(); _sprite.setPosition(position); }
Bullet::Bullet(Vector2f pos, float rotation, TextureLoader tl, float velocity) { _sprite = (tl.getSprite("bullet")); _sprite.setPosition(pos); _sprite.scale(1.5f,1.0f); _rotation = rotation; //_boundaries = _sprite.getGlobalBounds(); _sprite.setRotation(_rotation+90); _velocity = velocity; }
vector<Texture> ModelLoader::loadMaterialTextures(aiMaterial* mat, aiTextureType type, TextureTypes texType) { TextureLoader textureLoader; vector<Texture> textures; for(GLuint i = 0; i < mat->GetTextureCount(type); i++) { aiString str; mat->GetTexture(type, i, &str); string filename = string(str.C_Str()); /* // <Eagle HASK> :( string filenameTMP = string(str.C_Str()); string filename = ""; for(int i = 4; i < filenameTMP.size(); i++){ if(filenameTMP[i] == '\\') filename += "/"; else filename += filenameTMP[i]; } // </Eagle HASK> :( */ GLboolean skip = false; for(GLuint j = 0; j < textureCache.size(); j++) { if(textureCache[j].path == filename) { textures.push_back(textureCache[j]); skip = true; break; } } if(!skip) { std::string filepath = directory + '/' + filename; Texture texture = textureLoader.loadTexture(filepath, texType); texture.path = string(str.C_Str()); textures.push_back(texture); this->textureCache.push_back(texture); } } return textures; }
void MS3D::reloadTextures() { for ( int i = 0; i < m_numMaterials; i++ ) { if ( strlen( m_pMaterials[i].m_pTextureFilename ) > 0 ) { std::stringstream fn; std::string file = m_pMaterials[i].m_pTextureFilename; file = file.substr(0, file.length() - 4); fn << _path << file << ".png"; TextureLoader *tload = new TextureLoader(); m_pMaterials[i].m_texture = tload->LoadTexture( fn.str().c_str() ); delete tload; } else { m_pMaterials[i].m_texture = 0; } } }
void Heightmap::loadHeightmap(string filename, float strength) { TextureLoader tl; Texture t = tl.loadTexture(filename, 1); if(t.getWidth() < columns || t.getHeight() < rows) { cout << "The provided file " << filename << " (" << t.getWidth() << "x" << t.getHeight() << ") is too small and cannot be used for this heightmap (" << columns << "x" << rows << ")" << endl; return; } int dx = t.getWidth()/columns; int dy = t.getHeight()/rows; for(int row = 0; row <= rows; row++) { for(int column = 0; column <= columns; column++) { setHeightAt(column, row, (t.getData()[row * t.getWidth() * dy + column * dx] / 255.0f) * strength); //assert(0.0f <= getHeightAt(column, row) && getHeightAt(column, row) <= strength); } } calculateNormals(); }
void FreezeParticle::InitializeFreezeParticleShader() { TextureLoader textureLoader; glTexture FreezeParticleTexture; FreezeParticleProfile = cgGLGetLatestProfile(CG_GL_FRAGMENT); cgGLSetOptimalOptions(FreezeParticleProfile); CheckForCgError("FreezeParticle", "selecting fragment profile"); FreezeParticleProgram = cgCreateProgramFromFile(ShaderContext, CG_SOURCE, "assets/pixelshaders/ps_freezeparticle.cg", FreezeParticleProfile, "pixelMain", 0); CheckForCgError("FreezeParticle", "creating fragment program from file"); cgGLLoadProgram(FreezeParticleProgram); CheckForCgError("FreezeParticle", "loading fragment program"); FreezeParticleCoord0 = cgGetNamedParameter(FreezeParticleProgram, "texcoord0"); textureLoader.LoadTextureFromDisk("assets/textures/weapon/freezeparticle.tga", &FreezeParticleTexture); FreezeParticleText1 = cgGetNamedParameter(FreezeParticleProgram, "text1"); cgGLSetTextureParameter(FreezeParticleText1, FreezeParticleTexture.TextureID); CheckForCgError("FreezeParticle", "setting decal 2D texture"); }
Model getSkybox(const std::vector<std::string>& skyboxTextures) { std::vector<Vertex> vertices(36); for (unsigned int i = 0; i < vertices.size(); i++) { vertices[i].position = glm::vec3(skybox_verts[i*3], skybox_verts[i*3+1], skybox_verts[i*3+2]); } std::vector<GLuint> indexes(36); for (unsigned int i = 0; i < indexes.size(); i++) { indexes[i] = i; } std::vector<Texture> textures; TextureLoader textureLoader; Texture texture = textureLoader.loadCubemap(skyboxTextures); textures.push_back(texture); Mesh mesh(vertices, indexes); Material material; material.setTextures(textures); return Model(mesh, material); }
//---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- void EffectImplemented::ReloadResources( const EFK_CHAR* materialPath ) { UnloadResources(); const EFK_CHAR* matPath = materialPath != NULL ? materialPath : m_materialPath.c_str(); Setting* loader = GetSetting(); { TextureLoader* textureLoader = loader->GetTextureLoader(); if( textureLoader != NULL ) { for( int32_t ind = 0; ind < m_ImageCount; ind++ ) { EFK_CHAR fullPath[512]; PathCombine( fullPath, matPath, m_ImagePaths[ ind ] ); m_pImages[ind] = textureLoader->Load( fullPath, TextureType::Color ); } } } { TextureLoader* textureLoader = loader->GetTextureLoader(); if (textureLoader != NULL) { for (int32_t ind = 0; ind < m_normalImageCount; ind++) { EFK_CHAR fullPath[512]; PathCombine(fullPath, matPath, m_normalImagePaths[ind]); m_normalImages[ind] = textureLoader->Load(fullPath, TextureType::Normal); } } } { TextureLoader* textureLoader = loader->GetTextureLoader(); if (textureLoader != NULL) { for (int32_t ind = 0; ind < m_distortionImageCount; ind++) { EFK_CHAR fullPath[512]; PathCombine(fullPath, matPath, m_distortionImagePaths[ind]); m_distortionImages[ind] = textureLoader->Load(fullPath, TextureType::Distortion); } } } { SoundLoader* soundLoader = loader->GetSoundLoader(); if( soundLoader != NULL ) { for( int32_t ind = 0; ind < m_WaveCount; ind++ ) { EFK_CHAR fullPath[512]; PathCombine( fullPath, matPath, m_WavePaths[ ind ] ); m_pWaves[ind] = soundLoader->Load( fullPath ); } } } { ModelLoader* modelLoader = loader->GetModelLoader(); if( modelLoader != NULL ) { for( int32_t ind = 0; ind < m_modelCount; ind++ ) { EFK_CHAR fullPath[512]; PathCombine( fullPath, matPath, m_modelPaths[ ind ] ); m_pModels[ind] = modelLoader->Load( fullPath ); } } } }
void Skydome::InitializeSkydomeShaders() { TextureLoader textureLoader; glTexture daySky, nightSky, redSky, sun, sunMask; textureLoader.LoadTextureFromDisk("assets/textures/sky/clouds2.tga", &daySky); textureLoader.LoadTextureFromDisk("assets/textures/sky/night.tga", &nightSky); textureLoader.LoadTextureFromDisk("assets/textures/sky/red.tga", &redSky); /* //Vertext Shader profile vsSkydomeProfile = cgGLGetLatestProfile(CG_GL_VERTEX); //Set profile cgGLSetOptimalOptions(vsFireballProfile); CheckForCgError("skydome", "selecting vertex profile"); //Load vertex shader vsFireballProgram = cgCreateProgramFromFile(ShaderContext, CG_SOURCE, "assets/vertexshaders/vs_fireball.cg", vsFireballProfile, "vertMain", 0); CheckForCgError("skydome", "creating vertex program from file"); cgGLLoadProgram(vsFireballProgram); CheckForCgError("skydome", "loading vertex program"); texVert = cgGetNamedParameter(vsFireballProgram, "texCoordIN"); position = cgGetNamedParameter(vsFireballProgram, "posIN"); move = cgGetNamedParameter(vsFireballProgram, "move"); mvMatrix = cgGetNamedParameter(vsFireballProgram, "ModelViewProj"); */ ///////////////////////////// //Pixel Shader psSkydomeProfile = cgGLGetLatestProfile(CG_GL_FRAGMENT); cgGLSetOptimalOptions(psSkydomeProfile); CheckForCgError("skydome", "selecting Skydome fragment profile"); psSkydomeProgram = cgCreateProgramFromFile(ShaderContext, CG_SOURCE, "assets/pixelshaders/ps_skydome.cg", psSkydomeProfile, "pixelMain", 0); CheckForCgError("skydome", "creating fragment program from file"); cgGLLoadProgram(psSkydomeProgram); CheckForCgError("skydome", "loading fragment program"); texcoord0 = cgGetNamedParameter(psSkydomeProgram, "texcoord0"); dayTime = cgGetNamedParameter(psSkydomeProgram, "lightdist"); transition = cgGetNamedParameter(psSkydomeProgram, "transition"); text1 = cgGetNamedParameter(psSkydomeProgram, "text1"); cgGLSetTextureParameter(text1, daySky.TextureID); text2 = cgGetNamedParameter(psSkydomeProgram, "text2"); cgGLSetTextureParameter(text2, nightSky.TextureID); text3 = cgGetNamedParameter(psSkydomeProgram, "text3"); cgGLSetTextureParameter(text3, redSky.TextureID); CheckForCgError("skydome", "setting decal 2D texture"); textureLoader.LoadTextureFromDisk("assets/textures/sky/sun.tga", &sun); textureLoader.LoadTextureFromDisk("assets/textures/sky/sunmask.tga", &sunMask); psSkydomeSunProfile = cgGLGetLatestProfile(CG_GL_FRAGMENT); cgGLSetOptimalOptions(psSkydomeSunProfile); CheckForCgError("skydome", "selecting Skydome sun fragment profile"); psSkydomeSunProgram = cgCreateProgramFromFile(ShaderContext, CG_SOURCE, "assets/pixelshaders/ps_skydomeSun.cg", psSkydomeSunProfile, "pixelMain", 0); CheckForCgError("skydome", "creating fragment program from file"); cgGLLoadProgram(psSkydomeSunProgram); CheckForCgError("skydome", "loading fragment program"); texcoord0 = cgGetNamedParameter(psSkydomeSunProgram, "texcoord0"); suntext1 = cgGetNamedParameter(psSkydomeSunProgram, "text1"); cgGLSetTextureParameter(suntext1, sun.TextureID); suntext2 = cgGetNamedParameter(psSkydomeSunProgram, "text2"); cgGLSetTextureParameter(suntext2, sunMask.TextureID); CheckForCgError("skydome", "setting decal 2D texture"); //Temporarily Unbind Texture //glDisable(GL_TEXTURE_2D); //glDisable(GL_BLEND); // Disable Blending //glBindTexture(GL_TEXTURE_2D,0); }
int main() { InitGlfw initGlfw; ShaderLoader shaderLoader; TextureLoader textureLoader; TextRenderer textRenderer; // Init initGlfw.Init(); textRenderer.Init(); glfwSetKeyCallback(initGlfw.window, KeyCallback); glfwSetMouseButtonCallback(initGlfw.window, MouseButtonCallback); glfwSetCursorPosCallback(initGlfw.window, MouseMoveCallback); // Shader loading GLuint defaultShaderProgram; GLuint textShaderProgram; GLuint simpleShaderProgram; defaultShaderProgram = shaderLoader.CreateProgram("Shaders\\vertex_shader.glsl", "Shaders\\fragment_shader.glsl"); textShaderProgram = shaderLoader.CreateProgram("Shaders\\text_vs.glsl", "Shaders\\text_fs.glsl"); simpleShaderProgram = shaderLoader.CreateProgram("Shaders\\simple_vertex_shader.glsl", "Shaders\\simple_fragment_shader.glsl"); // Load texture GLuint texture = textureLoader.LoadRGB("Images\\container.jpg"); GLuint blankTexture = textureLoader.LoadBlank(); cout << "Blank texture status: " << blankTexture << endl; // Define camera component vectors float wallDistanceMargin = 0.2f; float currentX; float currentZ; glm::vec3 cameraPos = glm::vec3(0.0f, -0.5f, 6.0f); glm::vec3 cameraFront = glm::vec3(0.0f, 0.0f, -1.0f); glm::vec3 cameraUp = glm::vec3(0.0f, 1.0f, 0.0f); float yaw = -90.0f; glm::vec3 front(cos(glm::radians(yaw)), 0.0f, sin(glm::radians(yaw))); // Define model and view matrices and get shader locations GLuint modelLocation = glGetUniformLocation(defaultShaderProgram, "model"); GLuint viewLocation = glGetUniformLocation(defaultShaderProgram, "view"); GLuint projectionLocation = glGetUniformLocation(defaultShaderProgram, "projection"); double currentTime = glfwGetTime(); double delta; glm::mat4 view; glm::mat4 proj1; glm::mat4 idm = glm::mat4(); // Hard-coded virtual environment Square backWall; Square leftWall; Square rightWall; Square floorSquare; Square frontWall; Square rewardZone; float corridorDepth = 10.0f; float corridorWidth = 3.0f; float wallHeight = 2.0f; float rewardZoneDepth = 2.0f; float rewardZonePosition = -3.0f; float rewardZoneLowZ = rewardZonePosition - rewardZoneDepth; float rewardZoneHighZ = rewardZonePosition + rewardZoneDepth; bool inRewardZone = false; backWall.SetColor(0.5f, 0.5f, 0.9f); backWall.SetScaling(corridorWidth, wallHeight); backWall.SetPosition(0.0f, wallHeight/2, -corridorDepth); frontWall.SetColor(0.5f, 0.5f, 0.9f); frontWall.SetScaling(corridorWidth, wallHeight); frontWall.SetPosition(0.0f, wallHeight / 2.0f, corridorDepth); leftWall.SetColor(0.5f, 0.9f, 0.5f); leftWall.SetScaling(corridorDepth, wallHeight); leftWall.SetRotation(0.0f, 90.0f, 0.0f); leftWall.SetPosition(-corridorWidth, wallHeight/2, 0.0f); rightWall.SetColor(0.5f, 0.9f, 0.5f); rightWall.SetScaling(corridorDepth, wallHeight); rightWall.SetRotation(0.0f, 90.0f, 0.0f); rightWall.SetPosition(corridorWidth,wallHeight/2, 0.0f); floorSquare.SetColor(0.1f, 0.1f, 0.1f); floorSquare.SetScaling(corridorWidth, corridorDepth); floorSquare.SetRotation(-90.0f, 0.0f, 0.0f); floorSquare.SetPosition(0.0f, -wallHeight/2.0f, 0.0f); rewardZone.SetColor(0.2f, 0.9f, 0.2f); rewardZone.SetScaling(corridorWidth, rewardZoneDepth); rewardZone.SetRotation(-90.0f, 0.0f, 0.0f); rewardZone.SetPosition(0.0f, -wallHeight / 2.0f + 0.01f, rewardZonePosition); proj1 = glm::perspective(45.0f, (float)2.0f*initGlfw.windowInfo.width / initGlfw.windowInfo.height, 0.1f, 100.0f); glEnable(GL_DEPTH_TEST); // Create frame buffer for offscreen rendering, configured to draw to a texture buffer from which we sample // to draw on each window. GLuint frameBufferObject; GLuint frameBufferTexture; GLuint renderBufferObject; int fullWidth = 2*initGlfw.windowInfo.width; glGenTextures(1, &frameBufferTexture); glBindTexture(GL_TEXTURE_2D, frameBufferTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, fullWidth, initGlfw.windowInfo.height, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glBindTexture(GL_TEXTURE_2D, 0); glGenRenderbuffers(1, &renderBufferObject); glBindRenderbuffer(GL_RENDERBUFFER, renderBufferObject); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, fullWidth, initGlfw.windowInfo.height); glBindRenderbuffer(GL_RENDERBUFFER, 0); glGenFramebuffers(1, &frameBufferObject); glBindFramebuffer(GL_FRAMEBUFFER, frameBufferObject); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, frameBufferTexture, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, renderBufferObject); glBindFramebuffer(GL_FRAMEBUFFER, 0); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE) cout << "Framebuffer completed" << endl; // Generate quads for left and right window GLfloat leftScreenVertices[] = { // Positions // TexCoords -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, -1.0f, 0.5f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 0.5f, 0.0f, 1.0f, 1.0f, 0.5f, 1.0f }; GLfloat rightScreenVertices[] = { // Positions // TexCoords -1.0f, 1.0f, 0.5f, 1.0f, -1.0f, -1.0f, 0.5f, 0.0f, 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.5f, 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f }; GLuint leftScreenVBO; GLuint rightScreenVBO; glGenBuffers(1, &leftScreenVBO); glBindBuffer(GL_ARRAY_BUFFER, leftScreenVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(leftScreenVertices), leftScreenVertices, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glGenBuffers(1, &rightScreenVBO); glBindBuffer(GL_ARRAY_BUFFER, rightScreenVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(rightScreenVertices), rightScreenVertices, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); // Game loop int updateTick = 0; while (!glfwWindowShouldClose(initGlfw.window)) { // Get time delta = glfwGetTime() - currentTime; currentTime = glfwGetTime(); std::string fpsString = "FPS: " + std::to_string(delta); // Update view matrix // sensor readings need to be plugged in here front = glm::vec3(cos(glm::radians(yaw)), 0.0f, sin(glm::radians(yaw))); currentX = cameraPos.x; currentZ = cameraPos.z; cameraPos += yVelocity * front; cameraPos -= glm::normalize(glm::cross(cameraFront, cameraUp)) * xVelocity; // Collision detection, reset to previous position if wall boundary is crossed if ( (cameraPos.x-wallDistanceMargin) < -corridorWidth | (cameraPos.x + wallDistanceMargin)> corridorWidth) cameraPos.x = currentX; if ((cameraPos.z-wallDistanceMargin) < -corridorDepth | (cameraPos.z + wallDistanceMargin) > corridorDepth) cameraPos.z = currentZ; // Check reward zone entries if (!inRewardZone && (cameraPos.z > rewardZoneLowZ && cameraPos.z < rewardZoneHighZ)) { inRewardZone = true; cout << "Reward zone ENTRY detected." << endl; } if (inRewardZone && (cameraPos.z < rewardZoneLowZ || cameraPos.z > rewardZoneHighZ)) { inRewardZone = false; cout << "Reward zone EXIT detected." << endl; } view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp); // Draw the complete screen to the offscreen framebuffer glfwMakeContextCurrent(initGlfw.window); glBindFramebuffer(GL_FRAMEBUFFER, frameBufferObject); glViewport(0, 0, fullWidth, initGlfw.windowInfo.height); glEnable(GL_DEPTH_TEST); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if (showFPS) textRenderer.RenderText(textShaderProgram, fpsString, 0.0f, GLfloat(initGlfw.windowInfo.height - 20), 1.0, glm::vec3(0.8, 0.6, 0.6)); glUseProgram(defaultShaderProgram); glUniformMatrix4fv(viewLocation, 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, glm::value_ptr(proj1)); glUniformMatrix4fv(modelLocation, 1, GL_FALSE, glm::value_ptr(idm)); glBindTexture(GL_TEXTURE_2D, texture); frontWall.Draw(); backWall.Draw(); leftWall.Draw(); rightWall.Draw(); floorSquare.Draw(); glBindTexture(GL_TEXTURE_2D, blankTexture); rewardZone.Draw(); glBindTexture(GL_TEXTURE_2D, 0); glBindFramebuffer(GL_FRAMEBUFFER, 0); // First monitor drawing calls //glfwMakeContextCurrent(initGlfw.window); glClear(GL_COLOR_BUFFER_BIT); glDisable(GL_DEPTH_TEST); glViewport(0, 0, initGlfw.windowInfo.width, initGlfw.windowInfo.height); glUseProgram(simpleShaderProgram); glBindTexture(GL_TEXTURE_2D, frameBufferTexture); glBindBuffer(GL_ARRAY_BUFFER, rightScreenVBO); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)(2 * sizeof(GLfloat))); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glDrawArrays(GL_TRIANGLES, 0, 6); glBindBuffer(GL_ARRAY_BUFFER, 0); glfwSwapBuffers(initGlfw.window); // Second monitor drawing calls glfwMakeContextCurrent(initGlfw.window2); glClear(GL_COLOR_BUFFER_BIT); glDisable(GL_DEPTH_TEST); glUseProgram(simpleShaderProgram); glBindTexture(GL_TEXTURE_2D, frameBufferTexture); glBindBuffer(GL_ARRAY_BUFFER, leftScreenVBO); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)(2 * sizeof(GLfloat))); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glDrawArrays(GL_TRIANGLES, 0, 6); glBindBuffer(GL_ARRAY_BUFFER, 0); glfwSwapBuffers(initGlfw.window2); // Check events glfwPollEvents(); // Output information ++updateTick; if (updateTick % 60 == 0) { cout << "Camera position: (" << cameraPos.x << ", " << cameraPos.y << ", " << cameraPos.z << ")" << endl; updateTick = 0; } } glfwTerminate(); // Clean up after exiting glDeleteFramebuffers(1, &frameBufferObject); return 0; }
void LayerNode::Apply(IRenderingView *rv) { glMatrixMode(GL_PROJECTION); // Select Projection glPushMatrix(); // Push The Matrix glLoadIdentity(); // Reset The Matrix glOrtho( 0, w , h , 0, -1, 1 ); // Select Ortho Mode glMatrixMode(GL_MODELVIEW); // Select Modelview Matrix glPushMatrix(); // Push The Matrix glLoadIdentity(); // Reset The Matrix // Render HUD glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); GLboolean l = glIsEnabled(GL_LIGHTING); glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); for(std::list<Layer>::iterator itr = layers.begin(); itr != layers.end(); itr++) { ITextureResourcePtr texr = itr->texr; float width = texr->GetWidth(); float height = texr->GetHeight(); float x = itr->origin[0]; float y = itr->origin[1]; if (texr != NULL) { if (texr->GetID() == 0) { TextureLoader* tl = new TextureLoader(); tl->LoadTextureResource(texr); } glBindTexture(GL_TEXTURE_2D, texr->GetID()); } else { glBindTexture(GL_TEXTURE_2D, 0); } glColor3f(1,1,1); glBegin(GL_QUADS); glTexCoord2f(0,0); glVertex3f(x,y,0); glTexCoord2f(0,1); glVertex3f(x,y+height,0); glTexCoord2f(1,1); glVertex3f(x+width,y+height,0); glTexCoord2f(1,0); glVertex3f(x+width,y,0); glEnd(); } glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); glEnable(GL_DEPTH_TEST); if (l) glEnable(GL_LIGHTING); // Reset state glMatrixMode( GL_PROJECTION ); // Select Projection glPopMatrix(); // Pop The Matrix glMatrixMode( GL_MODELVIEW ); // Select Modelview glPopMatrix(); // Pop The Matrix }
Model DuckLoader::loadDuckModel() { vector<Vertex> vertices; vector<GLuint> indices; string filepath = "res/models/duck/duck.txt"; ifstream fileStream(filepath); if(!fileStream){ throw new invalid_argument("No such duck file"); } string line; getline(fileStream, line); int vertexCount = stoi(line); for(int i = 0; i < vertexCount; i++){ getline(fileStream, line); vector<string> vertexStr = splitString(line, " "); if(vertexStr.size() != 8){ throw new invalid_argument("No such duck file"); } vec3 pos = vec3(atof(vertexStr[0].c_str()), atof(vertexStr[1].c_str()), atof(vertexStr[2].c_str())); vec3 norm = vec3(atof(vertexStr[3].c_str()), atof(vertexStr[4].c_str()), atof(vertexStr[5].c_str())); vec2 tex = vec2(atof(vertexStr[6].c_str()), atof(vertexStr[7].c_str())); Vertex vertex; vertex.Position = pos; vertex.Normal = norm; vertex.TexCoords = tex; vertices.push_back(vertex); } getline(fileStream, line); int indexCount = stoi(line); for(int i = 0; i < indexCount; i++){ getline(fileStream, line); vector<string> indexStr = splitString(line, " "); GLuint i1 = stoi(indexStr[0]); GLuint i2 = stoi(indexStr[1]); GLuint i3 = stoi(indexStr[2]); indices.push_back(i1); indices.push_back(i2); indices.push_back(i3); } TextureLoader textureLoader; string texturePath = "res/models/duck/ducktex.jpg"; Texture texture = textureLoader.loadTexture(texturePath, TextureTypes::DIFFUSE); Texture textureSpec = textureLoader.loadTexture(texturePath, TextureTypes::SPECULAR); vector<Texture> textures = {texture, textureSpec}; Material material; material.shininess = 32.0f; Mesh mesh(vertices, indices, textures); mesh.setMaterial(material); vector<Mesh> meshes = {mesh}; Model model (meshes); return model; }
//The main function int Main::start() { //Init if (init() == -1) { fprintf(stderr, "Could not initialise the program\n"); return -1; } //Create the scene Scene scene = Scene(window); Camera* camera = scene.getCamera(); camera->setFOV(45); //Create the loaders ModelLoader loader = ModelLoader(); TextureLoader textureLoader = TextureLoader(); //Create the models Model texturedModel = loader.loadToVao_OBJ_Textured("models/cube.obj", "textures/cube.bmp", glm::vec3(-3, 0, -5)); Model monkey = loader.loadToVao_OBJ("models/suzanne.obj", glm::vec3(0, 0, -5)); monkey.texture(textureLoader.loadBMP_custom("textures/suzanne texture.bmp")); monkey.setReflectivity(0.0); //Create an array of the same entities and add them to the scene std::vector<Entity> cubes; std::vector<glm::vec3> positions; int numOfCubes = 1000; Cube cubeTemp = Cube(); //Create the positions array for (int i = 0; i < numOfCubes; i++) { positions.insert(positions.end(), glm::vec3(rand() % 100, rand() % 100, rand() % 100)); } //Generate cloned cubes and put them at different positions cubes = cubeTemp.cloneEntity(positions); //Add the cubes to the entity map for (int i = 0; i < cubes.size(); i++) { scene.addEntity(&cubes[i]); } //Add the models to the scene scene.addModel(texturedModel); scene.addModel(monkey); //Create the onclick function auto onClick = []() { exit(0); }; //Create the UIs UIButton button = UIButton(0.06f, 0.05f, glm::vec2(1, -1), window, onClick); button.setAlignment(UIButton::ALIGN_BOTTOM_RIGHT); button.texture(textureLoader.loadBMP_custom("textures/Exit.bmp")); UIElement* ui = &button; //Add the UI scene.addPauseUI(ui); //Main loop while (!window.shouldClose()) { //Run the scene scene.run(); //Run the UI //Swap the buffers and poll events glfwSwapBuffers(window.getWindow()); glfwPollEvents(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } //Terminate glfw glfwTerminate(); return 0; }
void Sarge::InitializeSargeShaders() { TextureLoader textureLoader; ///////////////////////////// //Vertex Shader vsSargeProfile = cgGLGetLatestProfile(CG_GL_VERTEX); cgGLSetOptimalOptions(vsSargeProfile); CheckForCgError("sarge", "selecting vertex profile"); vsSargeProgram = cgCreateProgramFromFile(ShaderContext, CG_SOURCE, "assets/vertexshaders/vs_sarge.cg", vsSargeProfile, "sargeVertexShader", 0); CheckForCgError("sarge", "creating vertex program from file"); cgGLLoadProgram(vsSargeProgram); CheckForCgError("sarge", "loading vertex program"); ////////////////////////////// //Pixel Shader psSargeProfile = cgGLGetLatestProfile(CG_GL_FRAGMENT); cgGLSetOptimalOptions(psSargeProfile); CheckForCgError("sarge", "selecting pixel profile"); psSargeProgram = cgCreateProgramFromFile(ShaderContext, CG_SOURCE, "assets/pixelshaders/ps_sarge.cg", psSargeProfile, "sargeLightMap", 0); CheckForCgError("sarge", "creating fragment program from file"); cgGLLoadProgram(psSargeProgram); CheckForCgError("sarge", "loading fragment program"); modelViewProj = cgGetNamedParameter(vsSargeProgram, "modelViewProj"); lightViewProj = cgGetNamedParameter(vsSargeProgram, "lightViewProj"); vertin = cgGetNamedParameter(vsSargeProgram, "vertin"); lightPosition = cgGetNamedParameter(vsSargeProgram, "lightPosition"); fragin = cgGetNamedParameter(psSargeProgram, "fragin"); eyevector = cgGetNamedParameter(psSargeProgram, "eyevector"); CheckForCgError("sarge", "getting parameters"); textureLoader.LoadTextureFromDisk("assets/textures/shadermaps/sarge_normalmap.tga", &sargeNormalTexture); textureLoader.LoadTextureFromDisk("assets/textures/shadermaps/sarge_colormap.tga", &sargeColorTexture); //textureLoader.LoadTextureFromDisk("assets/textures/weapon/fire1.tga", &sargeColorTexture); normalmap = cgGetNamedParameter(psSargeProgram, "normalmap"); cgGLSetTextureParameter(normalmap, sargeNormalTexture.TextureID); decalmap = cgGetNamedParameter(psSargeProgram, "decalmap"); cgGLSetTextureParameter(decalmap, sargeColorTexture.TextureID); CheckForCgError("sarge", "setting decal 2D texture"); /* decalmap = cgGetNamedParameter(psSargeProgram, "decalmap"); cgGLSetTextureParameter(text1, sargeColorTexture.TextureID); CheckForCgError("sarge", "setting decal 2D texture"); */ mMeshObject.Scale(1.6f); }
void MainMenuController::preload() { // Tutorial button GameController* gc = GameController::create(TUTORIAL_KEY, TUTORIAL_FILE); gc->preload(); _tutButt = MainMenuButton::create(gc); _tutButt->index = -1; _tutButt->loadTextures("textures/Tutorial/tutorial.png", "textures/Tutorial/tutorial.png"); _tutButt->setTouchEnabled(true); //Add event listener _tutButt->addTouchEventListener([&](Ref* sender, ui::Widget::TouchEventType type) { switch (type) { case ui::Widget::TouchEventType::ENDED: _tutButt = ((MainMenuButton*)sender); _currController = _tutButt->index; _activeController = _tutButt->getController(); _rootnode->removeAllChildren(); _activeController->initialize(_rootnode); } }); _tutButt->retain(); loadGameController(LEVEL_ONE_KEY, LEVEL_ONE_FILE); loadGameController(LEVEL_TWO_KEY, LEVEL_TWO_FILE); loadGameController(LEVEL_THREE_KEY, LEVEL_THREE_FILE); loadGameController(LEVEL_FOUR_KEY, LEVEL_FOUR_FILE); loadGameController(LEVEL_FIVE_KEY, LEVEL_FIVE_FILE); loadGameController(LEVEL_SIX_KEY, LEVEL_SIX_FILE); loadGameController(LEVEL_SEVEN_KEY, LEVEL_SEVEN_FILE); loadGameController(LEVEL_EIGHT_KEY, LEVEL_EIGHT_FILE); loadGameController(LEVEL_NINE_KEY, LEVEL_NINE_FILE); // Load the textures (Autorelease objects) _assets = AssetManager::getInstance()->getCurrent(); TextureLoader* tloader = (TextureLoader*)_assets->access<Texture2D>(); tloader->loadAsync(EXPOSURE_BAR, "textures/exposure_bar.png"); tloader->loadAsync(EXPOSURE_FRAME, "textures/exposure_bar_frame.png"); tloader->loadAsync(DUDE_TEXTURE, "textures/player_animation.png"); tloader->loadAsync("dudepool", "textures/Level Pool/Shade_Swim_Animation.png"); tloader->loadAsync(PEDESTRIAN_TEXTURE, "textures/Pedestrian.png"); tloader->loadAsync(PEDESTRIAN_SHADOW_TEXTURE, "textures/Pedestrian_S.png"); tloader->loadAsync(PEDESTRIAN_POOL_TEXTURE, "textures/Level Pool/Level2_RotationP_Animation_New.png"); tloader->loadAsync(PEDESTRIAN_POOL_SHADOW_TEXTURE, "textures/Level2_RotationP_Animation_S.png"); tloader->loadAsync(INDICATOR, "textures/indicator.png"); tloader->loadAsync(CAR_TEXTURE, "textures/car_animation.png"); tloader->loadAsync(CAR_SHADOW_TEXTURE, "textures/Car1_S.png"); tloader->loadAsync(GOAL_TEXTURE, "textures/caster_animation.png"); //tloader->loadAsync("goalpool", "textures/caster_animation.png"); tloader->loadAsync(WIN_IMAGE, "textures/menu/Win Icon.png"); tloader->loadAsync(LOSE_IMAGE, "textures/menu/lose_icon.png"); tloader->loadAsync(WIN_TEXTURE, "textures/Shade_Win.png"); tloader->loadAsync(LOSE_TEXTURE, "textures/Shade_Sun.png"); _assets->loadAsync<Sound>(GAME_MUSIC, "sounds/DD_Main.mp3"); _assets->loadAsync<Sound>(WIN_MUSIC, "sounds/win.mp3"); _assets->loadAsync<Sound>(LOSE_MUSIC, "sounds/lose.mp3"); _assets->loadAsync<Sound>(LATCH_SOUND, "sounds/latch.mp3"); _assets->loadAsync<Sound>(SIGHTED_SOUND, "sounds/sighted.mp3"); _assets->loadAsync<Sound>(RUN_SOUND, "sounds/run.mp3"); JSONReader reader; reader.initWithFile(STATIC_OBJECTS); if (!reader.startJSON()) { CCASSERT(false, "Failed to load static objects"); return; } int count = reader.startArray("types"); for (int index = 0; index < count; index++) { reader.startObject(); string name = reader.getString("name"); string imageFormat = reader.getString("imageFormat"); string shadowImageFormat = reader.getString("shadowImageFormat"); if (shadowImageFormat == "") { shadowImageFormat = imageFormat; } tloader->loadAsync(name + OBJECT_TAG, "textures/static_objects/" + name + "." + imageFormat); tloader->loadAsync(name + SHADOW_TAG, "textures/static_objects/" + name + "_S." + shadowImageFormat); reader.endObject(); reader.advance(); } reader.endArray(); reader.endJSON(); // Background tloader->loadAsync(MENU_BACKGROUND_KEY, "textures/menu/Level Background-01.png"); }
int main(int argc, char* argv[]) { Graphics::WindowConfig wc; wc.width = 1280; wc.height = 720; wc.resizable = false; wc.mode = Graphics::WindowMode::WINDOW; Graphics::ContextConfig cc; cc.msaaSamples = 4; cc.debugContext = true; cc.glewExperimental = true; cc.coreProfileContext = true; #ifdef _DEBUG cc.synchronousDebugOutput = true; #else cc.synchronousDebugOutput = false; #endif Graphics::RenderingSystem renderingSystem; if (!renderingSystem.Init(wc, cc)) { fprintf(stderr, "Error while initializing renderingsystem.\n"); return 1; } auto deferredShader = renderingSystem.CreateShaderProgram( Graphics::ShaderInfo::VSFS("shaders/deferred.vs", "shaders/deferred.fs", "shaders/") ); auto deferredLightShader = renderingSystem.CreateShaderProgram( Graphics::ShaderInfo::VSFS("shaders/deferredlight.vs", "shaders/deferredlight.fs", "shaders/") ); auto copyShader = renderingSystem.CreateShaderProgram( Graphics::ShaderInfo::VSFS("shaders/copy.vs", "shaders/copy.fs", "shaders/") ); // Full-screen quad auto quadVertexBuffer = renderingSystem.CreateBuffer(); renderingSystem.UpdateBuffer(quadVertexBuffer, MeshUtils::quadVertices.data(), MeshUtils::quadVertices.size() * sizeof(float), Graphics::BufferType::STATIC); // Postprocessing PostProcess_SSAO ssaoPP; ssaoPP.Init(renderingSystem, quadVertexBuffer); // Rendertargets auto gBufferRT = renderingSystem.CreateRenderTarget(Graphics::RenderTargetOptions::SRGB8DepthRGB8(wc.width, wc.height)); auto tempRT = renderingSystem.CreateRenderTarget(Graphics::RenderTargetOptions::SRGB8Depth(wc.width, wc.height)); // For per-frame shader data PerFrameUBO perFrameUBO; perFrameUBO.nearPlane = 0.1f; perFrameUBO.farPlane = 100.0f; perFrameUBO.proj = glm::perspective(45.0f, wc.width / (float)wc.height, perFrameUBO.nearPlane, perFrameUBO.farPlane); perFrameUBO.flags = PerFrameUBO::Flags::NormalMapping | PerFrameUBO::Flags::ParallaxMapping; auto perFrameUBOHandle = renderingSystem.CreateBuffer(); renderingSystem.UpdateBuffer(perFrameUBOHandle, NULL, sizeof(perFrameUBO), Graphics::BufferType::DYNAMIC); renderingSystem.BindUniformBuffer(Constants::PER_FRAME_UBO_BINDING_INDEX, perFrameUBOHandle); // Used for per-drawcall shader data auto perDrawUBOHandle = renderingSystem.CreateBuffer(); renderingSystem.UpdateBuffer(perDrawUBOHandle, NULL, sizeof(DrawUBO), Graphics::BufferType::DYNAMIC); renderingSystem.BindUniformBuffer(Constants::PER_DRAW_UBO_BINDING_INDEX, perDrawUBOHandle); // Animates the lights and updates uniform buffer with lightdata LightManager<10> lightManager; lightManager.Init(renderingSystem); // To avoid having to load all textures at startup TextureLoader textureLoader; // Load the scene. // This can take a while for big scenes, so it'll poll the window to keep it responsive. std::vector<Renderable> renderables; if (!GetRenderables(dataFolder, textureLoader, renderingSystem, renderables /*out*/)) { return 0; } // Used for culling std::vector<bool> isCulled; FrustumCuller<Renderable> frustumCuller; glm::vec3 cameraPosition(0, 2, 0); glm::quat cameraOrientation; uint8_t ssaoState = 1; const std::array<const char*, 3> ssaoText = {{ "Off", "On", "Occlusion only" }}; bool parallaxMappingEnabled = true; bool normalMappingEnabled = true; int frames = 0; double timeAccum = 0.0; double lastTime = 0.0; while (!renderingSystem.CloseRequested()) { double time = renderingSystem.GetTime(); double dt = time - lastTime; lastTime = time; timeAccum += dt; // Sort renderables by material (could only be done once since it's not dynamic) std::sort(renderables.begin(), renderables.end(), [](const Renderable& a, const Renderable& b) { return a.GetMaterial() < b.GetMaterial(); }); // Update movement glm::vec3 movement(0, 0, 0); if (renderingSystem.IsKeyDown(Graphics::RenderingSystem::Key::W)) movement.z -= 1.0f; if (renderingSystem.IsKeyDown(Graphics::RenderingSystem::Key::S)) movement.z += 1.0f; if (renderingSystem.IsKeyDown(Graphics::RenderingSystem::Key::A)) movement.x -= 1.0f; if (renderingSystem.IsKeyDown(Graphics::RenderingSystem::Key::D)) movement.x += 1.0f; if (renderingSystem.IsKeyDown(Graphics::RenderingSystem::Key::Q)) movement.y -= 1.0f; if (renderingSystem.IsKeyDown(Graphics::RenderingSystem::Key::E)) movement.y += 1.0f; float movementScale = 3.0f; if (renderingSystem.IsKeyDown(Graphics::RenderingSystem::Key::SHIFT)) movementScale *= 4.0f; if (glm::length(movement) > 0) movement = glm::normalize(movement) * movementScale * float(dt); cameraPosition += movement * cameraOrientation; // Mouse look static glm::vec2 lastCursor = renderingSystem.GetCursorPosition(); auto cursor = renderingSystem.GetCursorPosition(); glm::vec2 diff = lastCursor - cursor; lastCursor = cursor; if (renderingSystem.IsMouseButtonDown(Graphics::RenderingSystem::MouseButton::Right)) { renderingSystem.SetCursorEnabled(false); diff *= 0.1f; cameraOrientation = cameraOrientation * glm::rotate(glm::quat(), -diff.x, glm::vec3(0, 1, 0)); // Yaw cameraOrientation = glm::rotate(glm::quat(), -diff.y, glm::vec3(1, 0, 0)) * cameraOrientation; // Pitch } else renderingSystem.SetCursorEnabled(true); // Update per-frame UBO perFrameUBO.view = glm::toMat4(cameraOrientation) * glm::translate(glm::mat4(1.0f), -cameraPosition); perFrameUBO.cameraPosition = glm::vec4(cameraPosition, 1.0); perFrameUBO.time = time; perFrameUBO.flags = 0; if (parallaxMappingEnabled) perFrameUBO.flags |= PerFrameUBO::Flags::ParallaxMapping; if(normalMappingEnabled) perFrameUBO.flags |= PerFrameUBO::Flags::NormalMapping; if (ssaoState == 2) perFrameUBO.flags |= PerFrameUBO::Flags::SSAOState; renderingSystem.UpdateBuffer(perFrameUBOHandle, &perFrameUBO, sizeof(perFrameUBO), Graphics::BufferType::DYNAMIC); // Update lights lightManager.Update(time, cameraPosition); // Do frustum-culling frustumCuller.Cull(renderables, isCulled, perFrameUBO.proj * perFrameUBO.view); #if 1 // Draw to G-buffer { // Bind G-buffer renderingSystem.BindRenderTarget(gBufferRT); // Clear it renderingSystem.ClearScreen(Graphics::ClearState::AllBuffers()); // Prepare to fill it renderingSystem.UseShaderProgram(deferredShader); renderingSystem.BindUniformBuffer(Constants::PER_FRAME_UBO_BINDING_INDEX, perFrameUBOHandle); renderingSystem.BindUniformBuffer(Constants::PER_DRAW_UBO_BINDING_INDEX, perDrawUBOHandle); // Draw objects DrawRenderables(renderingSystem, renderables, isCulled, perDrawUBOHandle); } // Do lighting to temporary rendertarget (all lights in one pass -- extremly wasteful; // would really want to cull and then draw individual bounding spheres/quads or similar). { // Prepare G-buffer textures renderingSystem.BindRenderTargetTexture(0, gBufferRT, Graphics::RenderTargetTexture::Color); renderingSystem.BindRenderTargetTexture(1, gBufferRT, Graphics::RenderTargetTexture::Depth); renderingSystem.BindRenderTargetTexture(2, gBufferRT, Graphics::RenderTargetTexture::Aux); // Prepare target RT renderingSystem.BindRenderTarget(tempRT); renderingSystem.ClearScreen(Graphics::ClearState::AllBuffers()); // Draw fullscreen quad renderingSystem.UseShaderProgram(deferredLightShader); renderingSystem.Draw(quadVertexBuffer, Graphics::BufferHandle::Invalid(), 6); // Bind tempRT's color texture renderingSystem.BindRenderTargetTexture(0, tempRT, Graphics::RenderTargetTexture::Color); } // Bind default framebuffer renderingSystem.BindRenderTarget(Graphics::DefaultRenderTarget()); renderingSystem.ClearScreen(Graphics::ClearState::AllBuffers()); // Bind depth- and normal-textures for postprocessing (color is from lighting pass) renderingSystem.BindRenderTargetTexture(1, gBufferRT, Graphics::RenderTargetTexture::Depth); renderingSystem.BindRenderTargetTexture(2, gBufferRT, Graphics::RenderTargetTexture::Aux); // Normals if (ssaoState > 0) ssaoPP.Run(Graphics::DefaultRenderTarget()); else { renderingSystem.UseShaderProgram(copyShader); renderingSystem.Draw(quadVertexBuffer, Graphics::BufferHandle::Invalid(), 6); } #endif renderingSystem.SubmitFrame(); ++frames; // Print FPS if (timeAccum > 1.0) { printf("FPS: %f\n", frames / timeAccum); frames = 0; timeAccum = 0.0; } textureLoader.LoadOne(renderingSystem, dataFolder); // Poll window-events renderingSystem.PollEvents(); // Enable/Disable features if (renderingSystem.WasPressed(Graphics::RenderingSystem::Key::F1)) { ssaoState = (ssaoState + 1) % 3; printf("SSAO: %s\n", ssaoText[ssaoState]); } if (renderingSystem.WasPressed(Graphics::RenderingSystem::Key::F2)) { normalMappingEnabled = !normalMappingEnabled; printf("Normal-mapping: %s\n", normalMappingEnabled ? "ON" : "OFF"); } if (renderingSystem.WasPressed(Graphics::RenderingSystem::Key::F3)) { parallaxMappingEnabled = !parallaxMappingEnabled; printf("Parallax-mapping: %s\n", parallaxMappingEnabled ? "ON" : "OFF"); } // Hot reload of shaders if (renderingSystem.IsKeyDown(Graphics::RenderingSystem::Key::SPACE)) renderingSystem.ReloadShaders(); if (renderingSystem.IsKeyDown(Graphics::RenderingSystem::Key::ESCAPE)) break; } renderingSystem.Shutdown(); return 0; }
int main() { DisplayManager displayManager(WINDOW_WIDTH, WINDOW_HEIGHT, "Neptune Physics Simulator"); displayManager.Enable(GL_DEPTH_TEST); //displayManager.Enable(GL_CULL_FACE); glCullFace(GL_BACK); //Input handling glfwSetInputMode(displayManager.getWindow(), GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetKeyCallback(displayManager.getWindow(), key_callback); glfwSetCursorPosCallback(displayManager.getWindow(), mouse_callback); //TODO: Add to camera setup glm::mat4 model; glm::mat4 view; glm::mat4 projection; projection = glm::perspective(45.0f, WINDOW_WIDTH / (float)WINDOW_HEIGHT, 0.1f, 100.0f); Renderer objRenderer; ObjectLoader objLoader; //Load Texture TextureLoader textLoader; GLuint textureId = textLoader.LoadTexture("..\\..\\external\\resources\\textures\\container.png"); //Loading OBJ mesh auto meshRawModel = objLoader.LoadMesh("..\\..\\external\\resources\\objects\\suzanneSmall.obj"); //Init physics system npDiscreteDynamicsWorld* world = new npDiscreteDynamicsWorld(); initializeObjects(world, meshRawModel.minVector, meshRawModel.maxVector); Light staticLight; staticLight.position = glm::vec3(0.0f, 1.0f, 10.0f); staticLight.color = glm::vec3(1.0f, 1.0f, 1.0f); //Init Shaders ModelShader meshShader("shaders\\vertexShader.vert", "shaders\\fragmentShader.frag"); ModelShader BVShader("shaders\\BVvertexShader.vert", "shaders\\BVfragmentShader.frag"); while (!glfwWindowShouldClose(displayManager.getWindow())) { GLdouble currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; glfwPollEvents(); gameCamera.ProcessKeyboard(keys, deltaTime); objRenderer.PrepareForRendering(); if (!pauseSimulation) { world->stepSimulation(deltaTime); } for (size_t i = 0; i < 2; i++) { auto rigidBdy = world->getRigidBody(i); #ifdef _DEBUG if (!pauseSimulation) { Log_DEBUG("main.cpp - 197", "Body position:", rigidBdy.getPosition()); } #endif npMatrix4 resultingModelMatrix = create4x4Matrix(rigidBdy.getTransformMatrix()).transpose(); //drawableBV has VBOs (vertex, color) BVShader.Use(); BVShader.LoadViewMatrix(gameCamera.GetViewMatrix()); BVShader.LoadProjectionMatrix(projection); BVShader.LoadModelMatrix(resultingModelMatrix); objRenderer.Render(drawableModelList.at(i)); BVShader.Stop(); //meshRawModel has other VBOs (vertex, normal, texCoords) meshShader.Use(); meshShader.LoadViewMatrix(gameCamera.GetViewMatrix()); meshShader.LoadProjectionMatrix(projection); meshShader.LoadModelMatrix(resultingModelMatrix); meshShader.LoadLightPosition(staticLight.position); meshShader.LoadLightColor(staticLight.color); meshShader.LoadShineVariables(0.0f, 0.0f); textLoader.UseTexture(textureId, meshShader.getProgramID(), "ourTexture"); objRenderer.Render(meshRawModel, wireFrameMode); meshShader.Stop(); } displayManager.UpdateDisplay(); } objLoader.CleanUp(); textLoader.CleanUp(); displayManager.CloseDisplay(); return 1; }