void BaseApp::RenderWater() { water.Bind(2); g_texFP162.Bind(1); g_texWaterReflect.Bind(0); Mat4 mBias = Mat4( 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f ); Mat4 mModelViewProjection = mBias * projMat * modelViewMat; m_shdWater->enable(); m_shdWater->sendUniform1i("g_texReflection", 0); m_shdWater->sendUniform1i("g_texRefraction", 1); m_shdWater->sendUniform1i("g_texNormalMap", 2); LARGE_INTEGER time; QueryPerformanceCounter(&time); m_shdWater->sendUniform1f("g_waterTranslation", float(time.QuadPart) * 0.00000000008f); m_shdWater->sendUniform3f("g_vEyePos", m_camera.m_vEye.x, m_camera.m_vEye.y, m_camera.m_vEye.z); m_shdWater->sendUniformMatrix4fv("g_mModelViewProjection", 1, 0, mModelViewProjection.m); glDisable(GL_CULL_FACE); RenderInfinitePlane(5000, 10, 0.0f, m_camera.m_vEye.x, m_camera.m_vEye.z); glEnable(GL_CULL_FACE); m_shdWater->disable(); }
void SpriteRenderer::RenderSelection(int selection_code, Texture &texture, glm::vec2 position, glm::vec2 size, GLfloat rotate) { assert(initialized); initRenderData(); // Prepare transformations this->selectionShader->Use(); glm::mat4 model; model = glm::translate(model, glm::vec3(position, 0.0f)); // First translate (transformations are: scale happens first, then rotation and then finall translation happens; reversed order) model = glm::translate(model, glm::vec3(0.5f * size.x, 0.5f * size.y, 0.0f)); // Move origin of rotation to center of quad model = glm::rotate(model, rotate, glm::vec3(0.0f, 0.0f, 1.0f)); // Then rotate model = glm::translate(model, glm::vec3(-0.5f * size.x, -0.5f * size.y, 0.0f)); // Move origin back model = glm::scale(model, glm::vec3(size, 1.0f)); // Last scale GLint model_loc = selectionShader->GetUniform("model"); glUniformMatrix4fv(model_loc, 1, false, glm::value_ptr(model)); glm::mat4 projection = glm::ortho(0.0f, static_cast<GLfloat>(Window::width), static_cast<GLfloat>(Window::height), 0.0f, -1.0f, 1.0f); GLint projection_loc = selectionShader->GetUniform("projection"); glUniformMatrix4fv(projection_loc, 1, false, glm::value_ptr(projection)); GLint code_loc = selectionShader->GetUniform("code"); glUniform1i(code_loc, selection_code); texture.Bind(GL_TEXTURE0); glBindVertexArray(this->quadVAO); glDrawArrays(GL_TRIANGLES, 0, 6); glBindVertexArray(0); }
void TerrainRenderer::Draw(const std::vector<Terrain*>& terrains, Vector4 clipPlane) { EnableCulling(true); shader->Bind(); shader->SetUniformMatrix4fv("gCamera", camera->GetTransform()->GetMatrix()); shader->SetUniform3f("eyeWorldPosition", camera->GetTransform()->GetPosition()); shader->SetUniform4f("clipPlane", clipPlane); for (unsigned int i = 0; i < terrains.size(); ++i) { shader->SetUniformMatrix4fv("gWorld", terrains[i]->GetWorldMatrix()); RawModel* model = terrains[i]->GetTexturedModel()->GetRawModel(); Texture* texture = terrains[i]->GetTexturedModel()->GetTexture(); texture->Bind(); model->GetVertexArray()->Bind(); model->GetIndexBuffer()->Bind(); glDrawElements(GL_TRIANGLES, model->GetIndexBuffer()->GetCount(), GL_UNSIGNED_INT, 0); model->GetIndexBuffer()->Unbind(); model->GetVertexArray()->Unbind(); texture->Unbind(); } shader->Unbind(); }
void GUIbutton::BuildList() { static Texture tex; if(!tex) { vector < paletteentry_s > vTransparentColors; paletteentry_s peBlack; peBlack.peBlue = peBlack.peGreen = peBlack.peRed = 0; peBlack.peFlags = 0; vTransparentColors.push_back( peBlack ); tex=LoadTexture("bitmaps/button.bmp", &vTransparentColors); } glNewList(displayList, GL_COMPILE); tex.Bind(); DrawThemeRect(10, 32, w, h); if(highlight) glColor4f(1.0,0.4f,0.4f,1.0f); if(centerText) guifont->output((w-guifont->GetWidth(caption.c_str()))/2.0, (h-guifont->GetHeight())/2.0, caption.c_str()); else guifont->output(7, (h-guifont->GetHeight())/2.0, caption.c_str()); glEndList(); }
Texture* GraphicsEngine::BlurCurrentOutput(float radius, bool halfRes) { Texture* texture = GaussianBlur(gBuffer->GetOutput(), radius, halfRes); texture->Bind(); return texture; }
void ResizeLightMask(GLuint width, GLuint height) { Texture::Active(light_tex_unit); Texture::Target tex_tgt = Texture::Target::Rectangle; light_mask.Bind(tex_tgt); Texture::Image2D( tex_tgt, 0, PixelDataInternalFormat::Red, width, height, 0, PixelDataFormat::Red, PixelDataType::UnsignedByte, nullptr ); Renderbuffer::Target rbo_tgt = Renderbuffer::Target::Renderbuffer; light_rbo.Bind(rbo_tgt); Renderbuffer::Storage( rbo_tgt, PixelDataInternalFormat::DepthComponent, width, height ); }
void Skybox::Render (const Texture &envmap) { // activate shader program program.Use (); // bind texture, vertex array and index buffer envmap.Bind (GL_TEXTURE_CUBE_MAP); glBindVertexArray (vertexarray); glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, indexbuffer); // render the framing glDrawElements (GL_TRIANGLES, 36, GL_UNSIGNED_SHORT, 0); }
void Render() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); auto view = camera.GetViewMatrix(); auto projection = glm::perspective(glm::radians(fov), 800.0f / 600.0f, 0.1f, 1000.0f); shaderProgram.Use(); glUniformMatrix4fv(shaderProgram.UniformLocation("view"), 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(shaderProgram.UniformLocation("projection"), 1, GL_FALSE, glm::value_ptr(projection)); // Bind textures using texture units glActiveTexture(GL_TEXTURE0); texture1.Bind(); glUniform1i(shaderProgram.UniformLocation("ourTexture1"), 0); glActiveTexture(GL_TEXTURE1); texture2.Bind(); glUniform1i(shaderProgram.UniformLocation("ourTexture2"), 1); glBindVertexArray(VAO); for (GLuint i = 0; i < 10; i++) { glm::mat4 model; model = glm::translate(model, cubePositions[i]); GLfloat angle = 20.0f * i; if (i % 3 == 0) model = glm::rotate(model, glm::radians(angle + (GLfloat)SDL_GetTicks() * 0.05f), glm::vec3(0.5f, 1.0f, 0.0f)); else model = glm::rotate(model, glm::radians(angle), glm::vec3(0.5f, 1.0f, 0.0f)); glUniformMatrix4fv(shaderProgram.UniformLocation("model"), 1, GL_FALSE, glm::value_ptr(model)); glDrawArrays(GL_TRIANGLES, 0, 36); } glBindVertexArray(0); }
ObjMeshExample(void) : gl() , objects(load_objects()) , depth_prog() , draw_prog() , depth_vao(objects.VAOForProgram(depth_prog)) , draw_vao(objects.VAOForProgram(draw_prog)) { UniformSampler(draw_prog, "DepthTex").Set(0); Texture::Active(0); depth_tex.Bind(Texture::Target::Rectangle); gl.ClearColor(0.8f, 0.8f, 0.7f, 0.0f); gl.Enable(Capability::DepthTest); gl.Enable(Capability::CullFace); }
void Planet::Draw(ShaderProgram &shaderProgram, Camera *camera, Texture moonTexture) { // modelMatrix has to be set // moonModelMatrices have to be set shaderProgram.UseProgram(); shaderProgram.SetUniform("mvpMatrix", camera->GetMVP(modelMatrix)); modelData->Draw(); for(GLint i = 0; i < moonModelMatrices.size(); i++) { moonTexture.Bind(0); shaderProgram.SetUniform("mvpMatrix", camera->GetMVP(moonModelMatrices[i])); modelData->Draw(); } shaderProgram.DisUseProgram(); }
value nme_gl_bind_bitmap_data_texture(value inBitmapData) { Surface *surface; if (AbstractToObject(inBitmapData,surface) ) { HardwareContext *ctx = gDirectRenderContext; if (!ctx) ctx = nme::HardwareContext::current; if (ctx) { Texture *texture = surface->GetOrCreateTexture(*gDirectRenderContext); if (texture) texture->Bind(surface,-1); } } return alloc_null(); }
FBTexExample(void) : gl() , vertex_shader(ObjectDesc("Vertex")) , prog(make_prog()) , projection_matrix(prog, "ProjectionMatrix") , camera_matrix(prog, "CameraMatrix") , model_matrix(prog, "ModelMatrix") , cube(List("Position")("Normal")("TexCoord").Get(), shapes::Cube(), prog) , width(800) , height(600) { UniformSampler(prog, "TexUnit").Set(0); Uniform<Vec3f>(prog, "LightPos").Set(40.0f, 40.0f, -80.0f); Texture::Active(0); tex.Bind(Texture::Target::_2D); Use(); }
FireEffect::FireEffect(const Vector3f& position) { constexpr float minV = 0.886f; constexpr float maxV = minV + 0.2f; constexpr float range = 1.305f; SetMinVelocity(Vector3f(-range,minV,-range) ); SetMaxVelocity(Vector3f(+range,maxV,+range)); SetBaseParticleLifetime(1.5f); SetParticleLifetimeVariance(1.5f); SetBaseStartSize(0.70f); SetBaseEndSize(0.38f); SetStartSizeVariance(0.22f); SetEndSizeVariance(0.16f); SetStartColor(Color(1.0f,0.2f,0.0f,0.6f)); SetEndColor(Color(1.0f,0.2f,0.0f,0.0f)); SetBlendingMode(ADDITIVE_BLENDING_MODE); SetEmitPosition(position); SetEmitPositionVariance(Vector3f(0.05f)); Texture* texture = Texture2D::Load("img/particle_post2.png"); if(!texture) { PrintErrorExit(); } texture->Bind(); texture->SetTextureRepeat(); texture->GenerateMipmap(); texture->SetMinFilter(GL_LINEAR_MIPMAP_LINEAR); texture->SetMagFilter(GL_LINEAR); texture->Unbind(); SetTexture(texture); }
void SpriteRenderer::DrawSprite(Texture &texture, glm::vec2 position, glm::vec2 size, GLfloat rotate, glm::vec3 color) { if (!initialized) { //shader = new Shader("src/Graphics/Shaders/sprite.vert", "src/Graphics/Shaders/sprite.frag"); //selectionShader = new Shader("src/Graphics/Shaders/selection.vert", "src/Graphics/Shaders/selection.frag"); shader = ShaderManager::GetShader("Sprite"); selectionShader = ShaderManager::GetShader("Selection"); initRenderData(); initialized = true; } // Prepare transformations this->shader->Use(); glm::mat4 model; model = glm::translate(model, glm::vec3(position, 0.0f)); // First translate (transformations are: scale happens first, then rotation and then finall translation happens; reversed order) model = glm::translate(model, glm::vec3(0.5f * size.x, 0.5f * size.y, 0.0f)); // Move origin of rotation to center of quad model = glm::rotate(model, rotate, glm::vec3(0.0f, 0.0f, 1.0f)); // Then rotate model = glm::translate(model, glm::vec3(-0.5f * size.x, -0.5f * size.y, 0.0f)); // Move origin back model = glm::scale(model, glm::vec3(size, 1.0f)); // Last scale GLint model_loc = shader->GetUniform("model"); glUniformMatrix4fv(model_loc, 1, false, glm::value_ptr(model)); // Render textured quad GLint image_loc = shader->GetUniform("image"); glUniform1i(image_loc, 0); glm::mat4 projection = glm::ortho(0.0f, static_cast<GLfloat>(Window::width), static_cast<GLfloat>(Window::height), 0.0f, -1.0f, 1.0f); GLint projection_loc = shader->GetUniform("projection"); glUniformMatrix4fv(projection_loc, 1, false, glm::value_ptr(projection)); //glActiveTexture(GL_TEXTURE0); texture.Bind(GL_TEXTURE0); glBindVertexArray(this->quadVAO); glDrawArrays(GL_TRIANGLES, 0, 6); glBindVertexArray(0); }
void Object::Draw(ShaderProgram &prog) { Texture *tex = objectType.texture; int i = 0; for (std::vector<Bone *>::iterator it = bones.begin(); it != bones.end(); ++it, ++i) { char name[20]; sprintf(name, "mat_model[%d]", i); prog.Set(name, (*it)->transformation); } bool bound = tex->Bind(prog, "modeltex"); bool boundS = objectType.specularT->Bind(prog, "speculartex"); bool boundN = objectType.normalT->Bind(prog, "normaltex"); bool boundE = objectType.emissiveT->Bind(prog, "emissivetex"); objectType.gfxModel->Draw(prog); if (bound) prog.curtex--; if (boundS) prog.curtex--; if (boundN) prog.curtex--; if (boundE) prog.curtex--; }
void BMPFontDraw(const char* txt, const void* fontvoid, float x, float y) { Texture* font = (Texture*)fontvoid; glMatrixMode(GL_MODELVIEW); glTranslatef(x,y,0); glEnable(GL_TEXTURE_2D); font->Bind(); glColor4f(1.,1.,1.,1.); volatile register float sizesofar = 0.; volatile register float linessofar = 0.; for (volatile register unsigned char *t = (unsigned char*)txt; *t; ++t) { switch (*t) { default: BMPFontDrawChar(*t, font); sizesofar += 0.7; break; case '\n': case '\r': glTranslatef(-sizesofar, 1. ,0); linessofar += 1.; sizesofar = 0; //printf("\n"); if (*t == '\n' && *(t+1)=='\r' || *t == '\r' && *(t+1)=='\n' ) t++; break; } } //printf("\n"); //glTranslatef(-sizesofar, linessofar ,0); glTranslatef(-sizesofar, -linessofar ,0); glTranslatef(-x, -y, 0); glDisable(GL_TEXTURE_2D); }
void SetupLightMask(void) { Texture::Active(light_tex_unit); Texture::Target tex_tgt = Texture::Target::Rectangle; light_mask.Bind(tex_tgt); draw_prog.Use(); UniformSampler(draw_prog, "LightMap").Set(GLuint(light_tex_unit)); Texture::MinFilter(tex_tgt, TextureMinFilter::Linear); Texture::MagFilter(tex_tgt, TextureMagFilter::Linear); Texture::WrapS(tex_tgt, TextureWrap::ClampToEdge); Texture::WrapT(tex_tgt, TextureWrap::ClampToEdge); Framebuffer::Target fbo_tgt = Framebuffer::Target::Draw; light_fbo.Bind(fbo_tgt); Framebuffer::AttachTexture(fbo_tgt, FramebufferAttachment::Color, light_mask, 0); Renderbuffer::Target rbo_tgt = Renderbuffer::Target::Renderbuffer; light_rbo.Bind(rbo_tgt); Framebuffer::AttachRenderbuffer(fbo_tgt, FramebufferAttachment::Depth, light_rbo); }
void draw() // fixme take handles as parameters { gWorld = world_matrix; gWVP = gProj * view * gWorld; glUniformMatrix4fv(h_gWorld, 1, GL_FALSE, glm::value_ptr(gWorld) ); glUniformMatrix4fv(h_gWVP, 1, GL_FALSE, glm::value_ptr(gWVP) ); glEnableVertexAttribArray(h_Position); glEnableVertexAttribArray(h_TexCoord); glEnableVertexAttribArray(h_Normal); glBindBuffer(GL_ARRAY_BUFFER, vbo); glVertexAttribPointer(h_Position, 3, GL_FLOAT, GL_FALSE, sizeof(Point), 0); glVertexAttribPointer(h_TexCoord, 2, GL_FLOAT, GL_FALSE, sizeof(Point), (void*)offsetof(Point,texture)); // fixme color to textcoord glVertexAttribPointer(h_Normal, 3, GL_FLOAT, GL_FALSE, sizeof(Point), (void*)offsetof(Point,normal)); // m_pTexture->Bind(GL_TEXTURE0); // fixme // light->SetWorldMatrix( Matrix4f(this->gWVP) ); if (tex) { tex->Bind(GL_TEXTURE0);//m } else { std::cout << "No Texture Bound To " << name << std::endl; } glDrawArrays(GL_TRIANGLES, 0, data.size() ); //mode, starting index, count // ORIGINAL glDisableVertexAttribArray(h_Position); glDisableVertexAttribArray(h_TexCoord); glDisableVertexAttribArray(h_Normal); }
void ForwardDirectional::UpdateUniforms(const mat4& modelMatrix, const Material& material) { static Texture WHITE = Texture(1, 1, whitePixel); if (material.GetTexture() != NULL) material.GetTexture()->Bind(0); else { WHITE.Bind(0); } mat4 MVP = GetRenderEngine()->GetCamera()->GetProjectionMatrix() * GetRenderEngine()->GetCamera()->GetViewMatrix() * modelMatrix; SetUniform("MVP", MVP); SetUniform("ModelMatrix", modelMatrix); SetUniform("NormalMatrix", glm::inverseTranspose(mat3(modelMatrix))); SetUniform("directionalLight.direction", static_cast<DirectionalLight*>(GetRenderEngine()->GetActiveLight())->GetDirection()); SetUniform("directionalLight.base.color", static_cast<DirectionalLight*>(GetRenderEngine()->GetActiveLight())->GetColor()); SetUniform("directionalLight.base.intensity", static_cast<DirectionalLight*>(GetRenderEngine()->GetActiveLight())->GetIntensity()); SetUniform("specularIntensity", material.GetSpecularIntensity()); SetUniform("specularPower", material.GetSpecularPower()); SetUniform("eyePosition", GetRenderEngine()->GetCamera()->GetPosition()); }
void ModelRenderer::RenderInitialPose( Model & p_Model ) { // Get const free graphic device GraphicDevice & graphicDevice = const_cast<GraphicDevice &>( m_GraphicDevice ); // Get the default shader program. ShaderProgram * pShaderProgram = m_GraphicDevice.GetDefaultShaderProgram( GraphicDevice::InitialPoseShader ); // Error check the shader program. if( pShaderProgram == NULL ) { return; } // Error check the vertex data. if( p_Model.GetVertexGroup( ).GetVertexDataCount( ) == 0 ) { return; } // Bind the shader program. pShaderProgram->Bind( ); // Set uniform data. pShaderProgram->SetUniformMatrix4x4f( "uProjectionMatrix", MatrixManager::GetProjectionMatrix( ) ); pShaderProgram->SetUniformMatrix4x4f( "uModelViewMatrix", MatrixManager::GetModelViewMatrix( ) ); // Set light uniforms GraphicDevice::DefaultModelSettings & modelSettings = graphicDevice.GetDefaultModelSettings( ); // Set light count pShaderProgram->SetUniform1i( "uLightCount", modelSettings.GetActiveLightCount( ) ); // Set ambient color const Vector3f32 & ambColor = modelSettings.GetAmbientLight( ); pShaderProgram->SetUniform3f("uAmbientColor", ambColor.x, ambColor.y, ambColor.z); // Go throguh all the lights for( SizeType i = 0; i < modelSettings.GetActiveLightCount( ); i++ ) { std::stringstream positionStream; positionStream << "uLightPositions[" << i << "]"; std::stringstream colorStream; colorStream << "uLightColors[" << i << "]"; const Vector4f32 & pos = modelSettings.GetLight( i ).GetPosition( ); const Vector3f32 & color = modelSettings.GetLight( i ).GetColor( ); pShaderProgram->SetUniform4f( positionStream.str( ).c_str( ), pos.x, pos.y, pos.z, pos.w ); pShaderProgram->SetUniform3f( colorStream.str( ).c_str( ), color.x, color.y, color.z ); } // Get the vertex group ModelVertexGroup & vertexGroup = p_Model.GetVertexGroup( ); // Go throguh all the vertex data elements. for( SizeType i = 0; i < vertexGroup.GetVertexDataCount( ); i++ ) { // Get the current vertex data. ModelVertexData * vertexData = vertexGroup.GetVertexData( i ); // Error check the vertex data pointer. if( vertexData == NULL || vertexData->GetVertexArray( ) == NULL ) { continue; } // Get the model material const ModelMaterial & material = vertexData->GetMaterial(); // Bind the color texture if any Texture * pTexture = material.GetColorTexture(); //pShaderProgram->SetUniform4f( "uColor", 1.0f, 1.0f, 1.0f, 1.0f ); if (vertexData->GetBitmask() & 0x02 && pTexture) { pShaderProgram->SetUniform1i( "uUseTexture", 1 ); } else { pShaderProgram->SetUniform1i( "uUseTexture", 0 ); } // Set use normals flag. if( vertexData->GetBitmask( ) & 0x04 ) { pShaderProgram->SetUniform1i( "uUseNormals", 1 ); } else { pShaderProgram->SetUniform1i( "uUseNormals", 0 ); } // Set diffuse color Vector4f32 diffuseColor = material.GetDiffuseColor(); pShaderProgram->SetUniform4f("uDiffuseColor", diffuseColor.x, diffuseColor.y, diffuseColor.z, diffuseColor.w); // Bind the texture. if( pTexture ) { pTexture->Bind( 0 ); } // Render the model. vertexData->GetVertexArray( )->Render( PrimitiveMode::Triangles ); // Unbind the texture. if (pTexture) { pTexture->Unbind(); } } // Unbind the shader program. pShaderProgram->Unbind( ); }
TorusExample(void) : make_torus(1.0, 0.5, 72, 48) , torus_instr(make_torus.Instructions()) , torus_indices(make_torus.Indices()) , projection_matrix(prog, "ProjectionMatrix") , camera_matrix(prog, "CameraMatrix") , model_matrix(prog, "ModelMatrix") { // Set the vertex shader source and compile it vs.Source( "#version 330\n" "uniform mat4 ProjectionMatrix, CameraMatrix, ModelMatrix;" "in vec4 Position;" "in vec3 Normal;" "in vec2 TexCoord;" "out vec3 vertNormal;" "out vec3 vertLight;" "out vec2 vertTexCoord;" "uniform vec3 LightPos;" "void main(void)" "{" " gl_Position = ModelMatrix * Position;" " vertNormal = mat3(ModelMatrix)*Normal;" " vertLight = LightPos - gl_Position.xyz;" " vertTexCoord = TexCoord;" " gl_Position = ProjectionMatrix * CameraMatrix * gl_Position;" "}" ).Compile(); // set the fragment shader source and compile it fs.Source( "#version 330\n" "uniform sampler2D TexUnit;" "in vec3 vertNormal;" "in vec3 vertLight;" "in vec2 vertTexCoord;" "out vec4 fragColor;" "void main(void)" "{" " float l = sqrt(length(vertLight));" " float d = l > 0? dot(" " vertNormal, " " normalize(vertLight)" " ) / l : 0.0;" " float i = 0.2 + 3.2*max(d, 0.0);" " fragColor = texture(TexUnit, vertTexCoord)*i;" "}" ).Compile(); // attach the shaders to the program prog.AttachShader(vs).AttachShader(fs); // link and use it prog.Link().Use(); // bind the VAO for the torus torus.Bind(); // bind the VBO for the torus vertices verts.Bind(Buffer::Target::Array); { std::vector<GLfloat> data; GLuint n_per_vertex = make_torus.Positions(data); // upload the data Buffer::Data(Buffer::Target::Array, data); // setup the vertex attribs array for the vertices VertexAttribArray attr(prog, "Position"); attr.Setup<GLfloat>(n_per_vertex); attr.Enable(); } // bind the VBO for the torus normals normals.Bind(Buffer::Target::Array); { std::vector<GLfloat> data; GLuint n_per_vertex = make_torus.Normals(data); // upload the data Buffer::Data(Buffer::Target::Array, data); // setup the vertex attribs array for the vertices VertexAttribArray attr(prog, "Normal"); attr.Setup<GLfloat>(n_per_vertex); attr.Enable(); } // bind the VBO for the torus texture coordinates texcoords.Bind(Buffer::Target::Array); { std::vector<GLfloat> data; GLuint n_per_vertex = make_torus.TexCoordinates(data); // upload the data Buffer::Data(Buffer::Target::Array, data); // setup the vertex attribs array for the vertices VertexAttribArray attr(prog, "TexCoord"); attr.Setup<GLfloat>(n_per_vertex); attr.Enable(); } // setup the texture Texture::Target tex_tgt = Texture::Target::_2D; tex.Bind(tex_tgt); { GLuint s = 256; std::vector<GLubyte> tex_data(s*s); for(GLuint v=0;v!=s;++v) for(GLuint u=0;u!=s;++u) tex_data[v*s+u] = rand() % 0x100; Texture::Image2D( tex_tgt, 0, PixelDataInternalFormat::Red, s, s, 0, PixelDataFormat::Red, PixelDataType::UnsignedByte, tex_data.data() ); Texture::MinFilter(tex_tgt, TextureMinFilter::Linear); Texture::MagFilter(tex_tgt, TextureMagFilter::Linear); Texture::WrapS(tex_tgt, TextureWrap::Repeat); Texture::WrapT(tex_tgt, TextureWrap::Repeat); Texture::SwizzleG(tex_tgt, TextureSwizzle::Red); Texture::SwizzleB(tex_tgt, TextureSwizzle::Red); } // typechecked uniform with exact data type // on compilers supporting strongly typed enums // you can use: //Typechecked<Uniform<SLtoCpp<SLDataType::Sampler2D>>>(prog, "TexUnit").Set(0); // without strongly typed enums you need to do: typedef SLtoCpp<OGLPLUS_CONST_ENUM_VALUE(SLDataType::Sampler2D)> GLSLsampler2D; Typechecked<Uniform<GLSLsampler2D>>(prog, "TexUnit").Set(0); // Uniform<Vec3f>(prog, "LightPos").Set(4.0f, 4.0f, -8.0f); gl.ClearColor(0.8f, 0.8f, 0.7f, 0.0f); gl.ClearDepth(1.0f); gl.Enable(Capability::DepthTest); gl.Enable(Capability::CullFace); gl.FrontFace(make_torus.FaceWinding()); gl.CullFace(Face::Back); }
JNIEXPORT void JNICALL Java_sp_graphics_Texture_native_1bind (JNIEnv *env, jclass cls, jlong handler) { Texture* texture = getHandle<Texture>(handler); texture->Bind(); }
int main() { EinApplication::setErrorCallback(onError); EinApplication *app = new EinApplication(); EinWindow* window = new EinWindow(WIN_WIDTH, WIN_HEIGHT, "cgBentRendering", false); Camera* mainCamera = new Camera(glm::vec3(0.0f, 0.0f, 3.0f)); GLfloat quadVertices[] = { // Vertex attributes for a quad that fills the entire screen in Normalized Device Coordinates. // Positions // TexCoords -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f }; // Setup screenQuad VAO GLuint quadVAO, quadVBO; glGenVertexArrays(1, &quadVAO); glGenBuffers(1, &quadVBO); glBindVertexArray(quadVAO); glBindBuffer(GL_ARRAY_BUFFER, quadVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), &quadVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)(2 * sizeof(GLfloat))); glBindVertexArray(0); Shader modelGbuffer("shaders/modelGbuffer.vert", "shaders/modelGbuffer.frag"); modelGbuffer.Link(); // Shader bentNormalsShader("shaders/quad.vert", "shaders/bent_normals.frag"); // bentNormalsShader.Link(); // // algorithm params // Params params; // params.sampleRadius = 1.0f; // params.maxDistance = params.sampleRadius * 1.6f; // params.numRayMarchingSteps = 3; // params.patternSize = 8; // params.sampleCount = 8; // params.rayMarchingBias = params.sampleRadius / float(params.numRayMarchingSteps) / 1000.0f; // // glUniform1f(glGetUniformLocation(bentNormalsShader.Program, "sampleRadius"), params.sampleRadius); // glUniform1f(glGetUniformLocation(bentNormalsShader.Program, "maxDistance"), params.maxDistance); // glUniform1i(glGetUniformLocation(bentNormalsShader.Program, "patternSize"), params.patternSize); // glUniform1i(glGetUniformLocation(bentNormalsShader.Program, "sampleCount"), params.sampleCount); // glUniform1i(glGetUniformLocation(bentNormalsShader.Program, "numRayMarchingSteps"), params.numRayMarchingSteps); // // int kernelSize = 32; // glm::vec3 *kernel = new glm::vec3[kernelSize]; // srandTimeSeed(); // for (int i = 0; i < kernelSize; i++) { // kernel[i] = glm::vec3( // randMToN(-1.0f, 1.0f), // randMToN(-1.0f, 1.0f), // randMToN(0.0f, 1.0f)); // kernel[i] = glm::normalize(kernel[i]); // // float scale = (float)i / (float)kernelSize; // kernel[i] *= lerp(0.1f, 1.0f, scale * scale); // } // // for (int i = 0; i< kernelSize; i++) { // std::cerr << kernel[i].x << " " << kernel[i].y << " " << kernel[i].z << std::endl; // } // glUniform1i(glGetUniformLocation(bentNormalsShader.Program, "uKernelSize"), kernelSize); // glUniform3fv(glGetUniformLocation(bentNormalsShader.Program, "uKernelOffsets"), kernelSize, (const GLfloat*)glm::value_ptr(kernel[0])); // // int ssaoNoiseSize = 8; // int noiseDataSize = ssaoNoiseSize * ssaoNoiseSize; // glm::vec3 *noiseData = new glm::vec3[noiseDataSize]; // srandTimeSeed(); // for (int i = 0; i < noiseDataSize; i++) { // noiseData[i] = glm::vec3( // randMToN(-1.0f, 1.0f), // randMToN(-1.0f, 1.0f), // 0.0f); // noiseData[i] = glm::normalize(noiseData[i]); // } // Texture noiseTex; // // noiseTex.Bind(); // glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, ssaoNoiseSize, ssaoNoiseSize, 0, GL_RGB, GL_FLOAT, noiseData); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // noiseTex.Unbind(); Shader lightingShader("shaders/quad.vert", "shaders/lighting.frag"); lightingShader.Link(); Shader simpleShader("shaders/simple.vert", "shaders/simple.frag"); simpleShader.Link(); // Load models Model demonHeadModel("models/bake/monkeyright.obj"); Texture bentNormalsTexture("models/bake/nice_bent_normals.png", GL_REPEAT, GL_REPEAT, GL_NEAREST, GL_NEAREST); // Setup gBuffer Framebuffer *gBuffer = new Framebuffer(); gBuffer->BindFb(); gBuffer->addTextureAttachment(TexAttachmentType::DEPTH, window->GetFramebufferSize()); gBuffer->addTextureAttachment(TexAttachmentType::RGBA, window->GetFramebufferSize(), "position"); gBuffer->addTextureAttachment(TexAttachmentType::RGB, window->GetFramebufferSize(), "normal"); gBuffer->addTextureAttachment(TexAttachmentType::RGB, window->GetFramebufferSize(), "bentNormal"); gBuffer->addTextureAttachment(TexAttachmentType::RGB, window->GetFramebufferSize(), "color"); gBuffer->setupMRT(); if(!gBuffer->isReady()) std::cerr << "Gbuffer incomplete" << std::endl; gBuffer->UnbindFb(); // Get textures from gBuffer Texture depthTex = gBuffer->getTextureAttachment(DEPTH); Texture positionTex = gBuffer->getTextureAttachment("position"); Texture normalTex = gBuffer->getTextureAttachment("normal"); Texture bentNormalsTex = gBuffer->getTextureAttachment("bentNormal"); Texture colorTex = gBuffer->getTextureAttachment("color"); // // Setup bent_normalsBuffer // Framebuffer *bentNormalsBuffer = new Framebuffer(); // bentNormalsBuffer->BindFb(); // bentNormalsBuffer->addTextureAttachment(TexAttachmentType::RGBA, window->GetFramebufferSize(), "bent_normals"); // if(!bentNormalsBuffer->isReady()) // std::cerr << "Bent normals buffer incomplete" << std::endl; // bentNormalsBuffer->UnbindFb(); // // Get bent normals texture // Texture bentNormalsTex = bentNormalsBuffer->getTextureAttachment("bent_normals"); bool useBentNormals = false; float bentNormalsInfluence = 0.3f; EinInputManager *inputManager = window->GetInputManager(); while(!window->ShouldClose()) { // Set frame time GLfloat currentFrame = app->GetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // Pool events inputManager->pollEvents(); if(inputManager->isExit(KeyActionType::KEY_UP)) { window->SetShouldClose(true); } if(inputManager->isKey(GLFW_KEY_T, KeyActionType::KEY_UP)) { if (useBentNormals) useBentNormals = false; else useBentNormals = true; } if(inputManager->isKey(GLFW_KEY_Y, KeyActionType::KEY_DOWN)) { bentNormalsInfluence -= 0.01f; if(bentNormalsInfluence < 0.0f) bentNormalsInfluence = 0.0f; } if(inputManager->isKey(GLFW_KEY_U, KeyActionType::KEY_DOWN)) { bentNormalsInfluence += 0.01f; if(bentNormalsInfluence > 1.0f) bentNormalsInfluence = 1.0f; } // Handle camera movements doMovement(window->GetInputManager(), mainCamera); // Bind gBuffer gBuffer->BindFb(); // Setup OpenGL options // Clear the screen to black glEnable(GL_DEPTH_TEST); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Activate shader modelGbuffer.Use(); // Create transformations glm::mat4 view = mainCamera->GetViewMatrix(); glm::mat4 projection = glm::perspective(mainCamera->zoomQuantity, (float)(window->GetWindowSize().width)/(float)(window->GetWindowSize().height), 0.1f, 10.0f); glm::mat4 model; // model = glm::rotate(model, -90.0f, glm::vec3(1.0, 0.0, 0.0)); // Get the uniform locations GLint modelLoc = glGetUniformLocation(modelGbuffer.Program, "model"); GLint viewLoc = glGetUniformLocation(modelGbuffer.Program, "view"); GLint projLoc = glGetUniformLocation(modelGbuffer.Program, "projection"); // Pass the matrices to the shader glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model)); glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection)); glActiveTexture(GL_TEXTURE0); bentNormalsTexture.Bind(); glUniform1i(glGetUniformLocation(modelGbuffer.Program, "normalMap"), 0); demonHeadModel.Draw(modelGbuffer); gBuffer->UnbindFb(); // bentNormalsBuffer->BindFb(); // glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // glClear(GL_COLOR_BUFFER_BIT); // glDisable(GL_DEPTH_TEST); // // bentNormalsShader.Use(); // glBindVertexArray(quadVAO); // GLint viewMatrixLoc = glGetUniformLocation(bentNormalsShader.Program, "viewMatrix"); // GLint viewProjectionMatrixLoc = glGetUniformLocation(bentNormalsShader.Program, "projectionMatrix"); // // Pass the matrices to the shader // glUniformMatrix4fv(viewMatrixLoc, 1, GL_FALSE, glm::value_ptr(view)); // glUniformMatrix4fv(viewProjectionMatrixLoc, 1, GL_FALSE, glm::value_ptr(projection)); // // glActiveTexture(GL_TEXTURE0); // positionTex.Bind(); // glUniform1i(glGetUniformLocation(bentNormalsShader.Program, "positionTexture"), 0); // // glActiveTexture(GL_TEXTURE1); // normalTex.Bind(); // glUniform1i(glGetUniformLocation(bentNormalsShader.Program, "normalTexture"), 1); // // glActiveTexture(GL_TEXTURE2); // depthTex.Bind(); // glUniform1i(glGetUniformLocation(bentNormalsShader.Program, "depthTexture"), 2); // // glActiveTexture(GL_TEXTURE3); // noiseTex.Bind(); // glUniform1i(glGetUniformLocation(bentNormalsShader.Program, "uNoiseTex"), 3); // glDrawArrays(GL_TRIANGLES, 0, 6); // glBindVertexArray(0); // bentNormalsBuffer->UnbindFb(); // Activate shader glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glDisable(GL_DEPTH_TEST); lightingShader.Use(); glBindVertexArray(quadVAO); glActiveTexture(GL_TEXTURE0); positionTex.Bind(); glUniform1i(glGetUniformLocation(lightingShader.Program, "tPosition"), 0); glActiveTexture(GL_TEXTURE1); normalTex.Bind(); glUniform1i(glGetUniformLocation(lightingShader.Program, "tNormals"), 1); glActiveTexture(GL_TEXTURE2); colorTex.Bind(); glUniform1i(glGetUniformLocation(lightingShader.Program, "tDiffuse"), 2); glActiveTexture(GL_TEXTURE3); bentNormalsTex.Bind(); glUniform1i(glGetUniformLocation(lightingShader.Program, "tBentNormals"), 3); GLint lightPosLoc = glGetUniformLocation(lightingShader.Program, "lightPos"); GLint viewerPosLoc = glGetUniformLocation(lightingShader.Program, "viewerPos"); glUniform3f(viewerPosLoc, mainCamera->position.x, mainCamera->position.y, mainCamera->position.z); glUniform3f(lightPosLoc, lightPos.x, lightPos.y, lightPos.z); glUniform1i(glGetUniformLocation(lightingShader.Program, "useBentNormals"), useBentNormals); glUniform1f(glGetUniformLocation(lightingShader.Program, "bentNormalsInfluence"), bentNormalsInfluence); glDrawArrays(GL_TRIANGLES, 0, 6); glBindVertexArray(0); // Swap screen buffer window->SwapBuffers(); showFPS(window); } // Clean up resources lightingShader.Delete(); modelGbuffer.Delete(); glDeleteVertexArrays(1, &quadVAO); delete window; delete mainCamera; delete app; }
void GUIcontroller::Draw() { if(selectedUnits.CommandsChanged()) guicontroller->UpdateCommands(); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0, gu->screenx, gu->screeny,0,-1000,1000); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE); glColor3f(1, 1, 1); glEnable(GL_TEXTURE_2D); mainFrame->Draw(); GUIframe *over=mainFrame->ControlAtPos(mouse->lastx, mouse->lasty); if(over) { mouse->cursorText=""; over->SelectCursor(); string tooltip=over->Tooltip(); if(!tooltip.empty()) { size_t lf; int x=mouse->lastx; int y=mouse->lasty+30; if(mouse->hide) { x=gu->screenx/2; y=gu->screeny/2+30; } string temp=tooltip; int numLines=0; int width=0; int tempWidth; // find out number of lines and width of tooltip while((lf=temp.find("\n"))!=string::npos) { tempWidth=(int)guifont->GetWidth(temp.substr(0, lf)); if(tempWidth>width) width=tempWidth; temp=temp.substr(lf+1, string::npos); numLines++; } tempWidth=(int)guifont->GetWidth(temp.substr(0, lf)); if(tempWidth>width) width=tempWidth; if(tempWidth) numLines++; static Texture tex; if(!tex) tex=LoadTexture("bitmaps/tooltip.bmp"); tex.Bind(); glColor4f(1.0, 1.0, 1.0, 0.5); // draw bkgnd pane for tooltip glPushMatrix(); glTranslatef(x, y, 0); DrawThemeRect(20, 128, width+20, (int)guifont->GetHeight()*numLines+10); glPopMatrix(); x+=10; y+=5; glColor3f(1.0, 1.0, 1.0); temp=tooltip; // draw tooltip with line wrapping while((lf=temp.find("\n"))!=string::npos) { guifont->PrintColor(x, y, temp.substr(0, lf)); y+=(int)guifont->GetHeight(); temp=temp.substr(lf+1, string::npos); } guifont->PrintColor(x, y, temp); } } glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glColor3f(1, 1, 1); }
LandscapeExample(void) : grid_side(128) , make_plane( Vec3f(0.0f, 0.0f, 0.0f), Vec3f(9.0f, 0.0f, 0.0f), Vec3f(0.0f, 0.0f,-9.0f), grid_side*3, grid_side*3 ), plane_instr(make_plane.Instructions()) , plane_indices(make_plane.Indices()) , light_pos(prog, "LightPos") , projection_matrix(prog, "ProjectionMatrix") , camera_matrix(prog, "CameraMatrix") , light_path( ListOf<Vec3f> (Vec3f(-3.0f, 2.0f, -3.5f)) (Vec3f( 0.0f, 5.0f, 0.5f)) (Vec3f( 3.0f, 3.0f, 3.0f)) (Vec3f( 3.0f, 3.0f, -3.0f)) (Vec3f( 0.0f, 5.0f, 0.5f)) (Vec3f(-3.2f, 2.0f, 3.0f)) .Get() ) { VertexShader vs; vs.Source( "#version 330\n" "uniform mat4 ProjectionMatrix, CameraMatrix;" "uniform sampler2D TexUnit;" "in vec4 Position;" "in vec2 TexCoord;" "out vec3 vertLight;" "out vec3 vertNormal;" "uniform vec3 LightPos;" "void main(void)" "{" " gl_Position = Position;" " float o = 0.0;" " float s[9];" " int k=0;" " for(int y=-1; y!=2; ++y)" " for(int x=-1; x!=2; ++x)" " {" " s[k] = sqrt(texture(" " TexUnit, " " TexCoord*3.0+" " vec2(x, y)/128.0" " ).r);" " o += s[k++];" " }" " gl_Position.y += o*0.5;" " vec3 c = vec3( 0.0, s[4], 0.0);" " float d = 1.0/32.0;" " vertNormal = normalize(" " cross(" " vec3( 0.0, s[1], -d) - c," " vec3( -d, s[3], 0.0) - c" " )+" " cross(" " vec3( d, s[5], 0.0) - c," " vec3( 0.0, s[1], -d) - c" " )+" " cross(" " vec3( 0.0, s[7], d) - c," " vec3( d, s[5], 0.0) - c" " )+" " cross(" " vec3( -d, s[3], 0.0) - c," " vec3( 0.0, s[7], d) - c" " )" " );" " vertLight = LightPos - gl_Position.xyz;" " gl_Position = " " ProjectionMatrix *" " CameraMatrix *" " gl_Position;" "}" ); vs.Compile(); FragmentShader fs; fs.Source( "#version 330\n" "in vec3 vertNormal;" "in vec3 vertLight;" "out vec4 fragColor;" "void main(void)" "{" " float l = length(vertLight);" " float d = l > 0? dot(" " normalize(vertNormal), " " normalize(vertLight)" " ) / l : 0.0;" " float i = 0.1 + 1.2*max(d, 0.0) + 4.2*pow(d, 2.0);" " fragColor = vec4(i*0.7, i*0.7, i*0.3, 1.0);" "}" ); fs.Compile(); // attach the shaders to the program prog.AttachShader(vs); prog.AttachShader(fs); // link and use it prog.Link(); prog.Use(); // bind the VAO for the plane plane.Bind(); // bind the VBO for the plane vertices verts.Bind(Buffer::Target::Array); { std::vector<GLfloat> data; GLuint n_per_vertex = make_plane.Positions(data); // upload the data Buffer::Data(Buffer::Target::Array, data); // setup the vertex attribs array for the vertices VertexAttribArray attr(prog, "Position"); attr.Setup<GLfloat>(n_per_vertex); attr.Enable(); } // bind the VBO for the plane texture coordinates texcoords.Bind(Buffer::Target::Array); { std::vector<GLfloat> data; GLuint n_per_vertex = make_plane.TexCoordinates(data); // upload the data Buffer::Data(Buffer::Target::Array, data); // setup the vertex attribs array for the vertices VertexAttribArray attr(prog, "TexCoord"); attr.Setup<GLfloat>(n_per_vertex); attr.Enable(); } // setup the texture Texture::Target tex_tgt = Texture::Target::_2D; tex.Bind(tex_tgt); { auto image = images::NewtonFractal( grid_side, grid_side, Vec3f(0.0f, 0.1f, 0.2f), Vec3f(1.0f, 0.8f, 0.9f), Vec2f(-1.0f, -1.0f), Vec2f( 1.0f, 1.0f), images::NewtonFractal::X3Minus1(), images::NewtonFractal::DefaultMixer() ); Texture::Image2D(tex_tgt, image); Texture::MinFilter(tex_tgt, TextureMinFilter::Linear); Texture::MagFilter(tex_tgt, TextureMagFilter::Linear); Texture::WrapS(tex_tgt, TextureWrap::MirroredRepeat); Texture::WrapT(tex_tgt, TextureWrap::MirroredRepeat); } // UniformSampler(prog, "TexUnit").Set(0); gl.ClearColor(0.8f, 0.8f, 0.7f, 0.0f); gl.ClearDepth(1.0f); gl.Enable(Capability::DepthTest); gl.Enable(Capability::CullFace); gl.FrontFace(make_plane.FaceWinding()); gl.CullFace(Face::Back); }
void Display() { glMatrixMode(GL_MODELVIEW); glScalef(2,2,2); glTranslated(0,-12.0,0); GLfloat light_matrix[16]; { // draw depth map SaveAttrib save; glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mFramebuffer); glClear(GL_DEPTH_BUFFER_BIT); glCullFace(GL_FRONT); glViewport(0, 0, SHADOW_MAP_SIZE, SHADOW_MAP_SIZE); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(-20, 20, -20, 20, 20, 200); glTranslated(0, 1, 1); gluLookAt(0, 100, 100, 0, 0, 0, 0, 10, 0); glGetFloatv(GL_PROJECTION_MATRIX, light_matrix); glMatrixMode(GL_MODELVIEW); glUseProgram( *Program::Get("simple.vert+simple.frag") ); glEnableClientState(GL_VERTEX_ARRAY); mModel->mVertexBuf->BindAsVertex(); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, *mModel->mFaceBuf); for(auto &m: mModel->mMaterial) { if( m.flag == 0 ) continue; glDrawElements(GL_TRIANGLES, sizeof(GLushort)*3*m.count, GL_UNSIGNED_SHORT, (void*)(m.start_index*3*sizeof(GLushort))); } glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); } glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glDepthFunc(GL_LEQUAL); glUseProgram(*Program::Get("depth_shadow.vert+depth_shadow.frag")); // set shadow texture Program *prog = Program::Get("depth_shadow.vert+depth_shadow.frag"); (*prog)["shadow_texture"] = mDepth->Bind(1); mat4 x = translate(vec3(0.5)) * scale(vec3(0.5)) * translate<float>(0,0,-0.001) * make_mat4(light_matrix); glUniformMatrix4fv(glGetUniformLocation(*prog, "light_matrix"), 1, GL_FALSE, value_ptr(x)); mModel->mVertexBuf->BindAsVertex(); mModel->mNormalBuf->BindAsNormal(); mModel->mUvBuf->BindAsTexCoord(); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, *mModel->mFaceBuf); for(auto &m: mModel->mMaterial) { glMaterialfv(GL_FRONT, GL_DIFFUSE, m.diffuse_color); glMaterialfv(GL_FRONT, GL_SPECULAR, m.specular_color); glMaterialf(GL_FRONT, GL_SHININESS, m.specularity); glBindTexture(GL_TEXTURE_2D, *m.texture); glDrawElements(GL_TRIANGLES, sizeof(GLushort)*3*m.count, GL_UNSIGNED_SHORT, (void*)(m.start_index*3*sizeof(GLushort))); } { SaveAttrib save; glDisable(GL_DEPTH_TEST); int size = Util::GetFloat(GL_MAX_VIEWPORT_DIMS); Util::SetMatrix(GL_PROJECTION, ortho<float>(0, size, 0, size, -1, 1)); glViewport(0, 0, size, size); Util::SetMatrix(GL_MODELVIEW, mat4()); glUseProgram(Program::Get("depth_view.frag")->Handle()); glBindTexture(GL_TEXTURE_2D, *mDepth); Util::DrawRect(0, 0, 256, 256); } CHECK(); }
void FrameBuffer::Init() { glGenFramebuffers(1, &id); glBindFramebuffer(GL_FRAMEBUFFER, id); // GetGame()->Log(glGetError()); drawBuffers.clear(); Texture* tex = nullptr; if(textures.size() > 0) { for(uint i = 0; i < textures.size(); ++i) { tex = textures[i]; // tex->scaleFilter = Texture::ScaleFilter::Linear; tex->wrapMode = Texture::WrapMode::Clamp; // tex->mode = GL_TEXTURE_2D_MULTISAMPLE; tex->size = uvec2(rect.width, rect.height); tex->SetIndex(startIndex+i); tex->InitData(0); uint32 attachment = startIndex+GL_COLOR_ATTACHMENT0+i; GetGame()->Log("Setting up textures for FrameBuffer, tex ", i, " gets attachment ", attachment, ". GL_COLOR_ATTACHMENT0 = ", GL_COLOR_ATTACHMENT0); tex->Bind(); glFramebufferTexture2D(GL_FRAMEBUFFER, attachment, tex->GetMode(), tex->GetId(), 0); drawBuffers.push_back(attachment); } } if(hasDepth) { /* glGenRenderbuffers(1, &depthBuffer); glBindRenderbuffer(GL_RENDERBUFFER, depthBuffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, rect.width, rect.height); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, depthBuffer); */ if(depthTexture) { // depthTexture->SetFormat(Texture::Format::Depth32F_Stencil8, Texture::Format::Depth); depthTexture->SetFormat(Texture::Format::Depth32F, Texture::Format::Depth); depthTexture->wrapMode = Texture::WrapMode::Clamp; depthTexture->dataType = Texture::DataType::Float; depthTexture->size = uvec2(rect.width, rect.height); depthTexture->SetIndex(startIndex+textures.size()); depthTexture->InitData(0); depthTexture->Bind(); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, depthTexture->GetMode(), depthTexture->GetId(), 0); GetGame()->Log(glGetError()); } } DrawBuffers(); BeginRender(); Unbind(); }
void RenderShadowMap(GLuint size) { // matrices auto lt_proj= CamMatrixf::PerspectiveX(Degrees(12), 1.0, 85.0, 110.0); auto light = CamMatrixf::LookingAt(light_position, Vec3f()); // setup the texture Texture::Active(shadow_tex_unit); mask_prog.Use(); Uniform<Mat4f>(mask_prog, "LightMatrix").Set(lt_proj*light); UniformSampler(mask_prog, "ShadowMap").Set(GLuint(shadow_tex_unit)); draw_prog.Use(); Uniform<Mat4f>(draw_prog, "LightMatrix").Set(lt_proj*light); UniformSampler(draw_prog, "ShadowMap").Set(GLuint(shadow_tex_unit)); Texture::Target tex_tgt = Texture::Target::_2D; shadow_map.Bind(tex_tgt); Texture::MinFilter(tex_tgt, TextureMinFilter::Linear); Texture::MagFilter(tex_tgt, TextureMagFilter::Linear); Texture::WrapS(tex_tgt, TextureWrap::ClampToEdge); Texture::WrapT(tex_tgt, TextureWrap::ClampToEdge); Texture::CompareMode(tex_tgt, TextureCompareMode::CompareRefToTexture); Texture::Image2D( tex_tgt, 0, PixelDataInternalFormat::DepthComponent32, size, size, 0, PixelDataFormat::DepthComponent, PixelDataType::Float, nullptr ); // create shadow program ShadowProgram shadow_prog(vert_shader); // VAO for the meshes in shadow program VertexArray vao = meshes.VAOForProgram(shadow_prog); vao.Bind(); // FBO for offscreen rendering of the shadow map Framebuffer::Target fbo_tgt = Framebuffer::Target::Draw; Framebuffer fbo; fbo.Bind(fbo_tgt); Framebuffer::AttachTexture(fbo_tgt, FramebufferAttachment::Depth, shadow_map, 0); // RBO for offscreen rendering Renderbuffer::Target rbo_tgt = Renderbuffer::Target::Renderbuffer; Renderbuffer rbo; rbo.Bind(rbo_tgt); Renderbuffer::Storage(rbo_tgt, PixelDataInternalFormat::RGBA, size, size); Framebuffer::AttachRenderbuffer(fbo_tgt, FramebufferAttachment::Color, rbo); // setup the matrices shadow_prog.projection_matrix.Set(lt_proj); shadow_prog.camera_matrix.Set(light); // setup and clear the viewport gl.Viewport(size, size); gl.Clear().DepthBuffer(); // draw the meshes gl.PolygonOffset(1.0, 1.0); gl.Enable(Capability::PolygonOffsetFill); meshes.Draw(); gl.Disable(Capability::PolygonOffsetFill); gl.Finish(); // bind the default framebuffer DefaultFramebuffer().Bind(Framebuffer::Target::Draw); }
void BaseApp::RenderFrame() { m_fpsCounter.MarkFrameStart(); POINT mousePos; GetCursorPos(&mousePos); m_mouseX = mousePos.x - m_winPosX; m_mouseY = mousePos.y - m_winPosY; if(lockMouse) { m_camera.SetViewByMouse( float(m_mouseLockedX - m_mouseX) * 0.2f , float(m_mouseLockedY - m_mouseY) * 0.2f); CenterMouse(); } float height = g_heightMap->GetInterpolatedHeight(m_camera.m_vEye.x, m_camera.m_vEye.z); //if( m_camera.m_vEye.y <= height + 2.0f ) { float oldY = m_camera.m_vEye.y; m_camera.m_vEye.y = height + 12.0f; float newY = m_camera.m_vEye.y; m_camera.m_vCenter.y += newY - oldY; } glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, g_frameBuffer); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, g_texFP16.GetID(), 0); glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, g_renderBuffer[0]); glClearColor(0.8f, 1.0f, 0.8f, 1.0f); glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); m_camera.BuildViewMatrix(&modelViewMat); glLoadMatrixf(modelViewMat); if(!m_freezeFrustum) frustum.ComputeFrustum(projMat, modelViewMat); glPushMatrix(); glTranslatef(m_camera.m_vEye.x, m_camera.m_vEye.y, m_camera.m_vEye.z); glDepthMask(GL_FALSE); m_shdSky->enable(); m_shdSky->sendUniform3f("color1", 2.0f, 2.0f, 2.0f); m_shdSky->sendUniform3f("color2", 0.5f, 0.7f, 2.0f); m_skydome.Render(); m_shdSky->disable(); //glDepthMask(GL_TRUE); glPopMatrix(); Vec3 sunPos = m_sunPos * 500.0f; glPopMatrix(); glPushMatrix(); glTranslatef(m_camera.m_vEye.x + sunPos.x, m_camera.m_vEye.y + sunPos.y, m_camera.m_vEye.z + sunPos.z); m_texSun.Activate(0); m_shdSimpleColor->enable(); m_shdSimpleColor->sendUniform3f("color", 4.0f, 4.0f, 2.0f); glEnable(GL_BLEND ); glBlendFunc(GL_SRC_COLOR, GL_ONE); RenderSprite(2000, &m_camera.m_vEye, modelViewMat); glDisable(GL_BLEND ); m_shdSimpleColor->disable(); m_texSun.Deactivate(); glDepthMask(GL_TRUE); glPopMatrix(); g_quadtree->Render(frustum, m_camera.m_vEye); /* glAlphaFunc(GL_GREATER,0.5f); glEnable(GL_ALPHA_TEST); Mat4 tmp; tmp.Identity(); tmp.Translate(Vec3(0.0f, g_heightMap->GetInterpolatedHeight(0.0f, 0.0f), 0.0f)); model.render(tmp, &frustum); tmp.Identity(); tmp.Translate(Vec3(50.0f, g_heightMap->GetInterpolatedHeight(50.0f, 0.0f), 0.0f)); model.render(tmp, &frustum); tmp.Identity(); tmp.Translate(Vec3(0.0f, g_heightMap->GetInterpolatedHeight(0.0f, 100.0f), 100.0f)); model.render(tmp, &frustum); tmp.Identity(); tmp.Translate(Vec3(-50.0f, g_heightMap->GetInterpolatedHeight(-50.0f, -200.0f), -200.0f)); model.render(tmp, &frustum); glDisable(GL_ALPHA_TEST); */ RenderWaterReflection(); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, g_texFP16.GetID(), 0); glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, g_renderBuffer[0]); g_texFP162.Bind(0); glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0,0, 0, m_width, m_height); RenderWater(); RenderWaterSpecular(); RenderUnderwaterNormalMap(); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); // No wireframe glPushAttrib(GL_POLYGON_BIT); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); if(m_camera.m_vEye.y < 0) { m_shdUnderwater->enable(); m_shdUnderwater->sendUniform1i("g_texViewport", 0); m_shdUnderwater->sendUniform1i("g_texNormalMap", 1); LARGE_INTEGER time; QueryPerformanceCounter(&time); m_shdUnderwater->sendUniform1f("g_waterTranslation", float(time.QuadPart) * 0.000000008f); g_texWaterReflect.Bind(1); } g_texFP16.Activate(0); RenderScreenCoveringQuad(); g_texFP16.Deactivate(); /* g_texWaterReflect.Activate(0); RenderScreenCoveringQuad(); g_texWaterReflect.Deactivate(); */ if(m_camera.m_vEye.y < 0) { m_shdUnderwater->disable(); } BlurHDR(); glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE); g_texVBluredHDR.Activate(0); RenderScreenCoveringQuad(); g_texVBluredHDR.Deactivate(); glDisable(GL_BLEND); m_pGui->SetViewportDim(m_width, m_height); m_pGui->Render(m_mouseX, m_mouseY, this->m_mouseButton); m_pFont->Enable(m_width, m_height); m_pFont->SetAlignment(FONT_HORIZ_ALIGN_RIGHT, FONT_VERT_ALIGN_TOP); m_pFont->Print(m_width - 10, 10, "FPS: %d", (int)m_fpsCounter.GetFPS() ); m_pFont->Print(m_width - 10, 30, "Camera eye: %f, %f, %f", m_camera.m_vEye.x, m_camera.m_vEye.y, m_camera.m_vEye.z); m_pFont->Print(m_width - 10, 50, "Camera center: %f, %f, %f", m_camera.m_vCenter.x, m_camera.m_vCenter.y, m_camera.m_vCenter.z); m_pFont->Print(m_width - 10, 70, "Triangles rendered: %d", g_quadtree->GetNumTrisLastRendered()); m_pFont->Print(m_width - 10, 90, "VBOs data size: %d bytes", g_quadtree->m_vboDataSize); //m_pFont->Print(m_width - 10, 110, "Mouse coords: (%d, %d)", m_mouseX, m_mouseY); m_pFont->Disable(); /* RenderTexDebug(3, 3, 2, g_texVBluredHDR.GetID(), "Blured HDR"); RenderTexDebug(2, 3, 2, g_texHDR.GetID(), "HDR"); RenderTexDebug(1, 3, 2, g_texFP16.GetID(), "Water refraction"); RenderTexDebug(0, 3, 2, g_texWaterReflect.GetID(), "Water reflection"); */ glPopAttrib(); SwapBuffers(m_hDC); m_fpsCounter.MarkFrameEnd(); }