• Advertisement
  • Popular Tags

  • Popular Now

  • Advertisement
  • Similar Content

    • By racarate
      Hey everybody!
      I am trying to replicate all these cool on-screen debug visuals I see in all the SIGGRAPH and GDC talks, but I really don't know where to start.  The only resource I know of is almost 16 years old:
      http://number-none.com/product/Interactive Profiling, Part 1/index.html
      Does anybody have a more up-to-date reference?  Do people use minimal UI libraries like Dear ImgGui?  Also, If I am profiling OpenGL ES 3.0 (which doesn't have timer queries) is there really anything I can do to measure performance GPU-wise?  Or should I just chart CPU-side frame time?  I feel like this is something people re-invent for every game there has gotta be a tutorial out there... right?
    • By Achivai
      Hey, I am semi-new to 3d-programming and I've hit a snag. I have one object, let's call it Object A. This object has a long int array of 3d xyz-positions stored in it's vbo as an instanced attribute. I am using these numbers to instance object A a couple of thousand times. So far so good. 
      Now I've hit a point where I want to remove one of these instances of object A while the game is running, but I'm not quite sure how to go about it. At first my thought was to update the instanced attribute of Object A and change the positions to some dummy number that I could catch in the vertex shader and then decide there whether to draw the instance of Object A or not, but I think that would be expensive to do while the game is running, considering that it might have to be done several times every frame in some cases. 
      I'm not sure how to proceed, anyone have any tips?
    • By fleissi
      Hey guys!

      I'm new here and I recently started developing my own rendering engine. It's open source, based on OpenGL/DirectX and C++.
      The full source code is hosted on github:

      I would appreciate if people with experience in game development / engine desgin could take a look at my source code. I'm looking for honest, constructive criticism on how to improve the engine.
      I'm currently writing my master's thesis in computer science and in the recent year I've gone through all the basics about graphics programming, learned DirectX and OpenGL, read some articles on Nvidia GPU Gems, read books and integrated some of this stuff step by step into the engine.

      I know about the basics, but I feel like there is some missing link that I didn't get yet to merge all those little pieces together.

      Features I have so far:
      - Dynamic shader generation based on material properties
      - Dynamic sorting of meshes to be renderd based on shader and material
      - Rendering large amounts of static meshes
      - Hierarchical culling (detail + view frustum)
      - Limited support for dynamic (i.e. moving) meshes
      - Normal, Parallax and Relief Mapping implementations
      - Wind animations based on vertex displacement
      - A very basic integration of the Bullet physics engine
      - Procedural Grass generation
      - Some post processing effects (Depth of Field, Light Volumes, Screen Space Reflections, God Rays)
      - Caching mechanisms for textures, shaders, materials and meshes

      Features I would like to have:
      - Global illumination methods
      - Scalable physics
      - Occlusion culling
      - A nice procedural terrain generator
      - Scripting
      - Level Editing
      - Sound system
      - Optimization techniques

      Books I have so far:
      - Real-Time Rendering Third Edition
      - 3D Game Programming with DirectX 11
      - Vulkan Cookbook (not started yet)

      I hope you guys can take a look at my source code and if you're really motivated, feel free to contribute :-)
      There are some videos on youtube that demonstrate some of the features:
      Procedural grass on the GPU
      Procedural Terrain Engine
      Quadtree detail and view frustum culling

      The long term goal is to turn this into a commercial game engine. I'm aware that this is a very ambitious goal, but I'm sure it's possible if you work hard for it.


    • By tj8146
      I have attached my project in a .zip file if you wish to run it for yourself.
      I am making a simple 2d top-down game and I am trying to run my code to see if my window creation is working and to see if my timer is also working with it. Every time I run it though I get errors. And when I fix those errors, more come, then the same errors keep appearing. I end up just going round in circles.  Is there anyone who could help with this? 
      Errors when I build my code:
      1>Renderer.cpp 1>c:\users\documents\opengl\game\game\renderer.h(15): error C2039: 'string': is not a member of 'std' 1>c:\program files (x86)\windows kits\10\include\10.0.16299.0\ucrt\stddef.h(18): note: see declaration of 'std' 1>c:\users\documents\opengl\game\game\renderer.h(15): error C2061: syntax error: identifier 'string' 1>c:\users\documents\opengl\game\game\renderer.cpp(28): error C2511: 'bool Game::Rendering::initialize(int,int,bool,std::string)': overloaded member function not found in 'Game::Rendering' 1>c:\users\documents\opengl\game\game\renderer.h(9): note: see declaration of 'Game::Rendering' 1>c:\users\documents\opengl\game\game\renderer.cpp(35): error C2597: illegal reference to non-static member 'Game::Rendering::window' 1>c:\users\documents\opengl\game\game\renderer.cpp(36): error C2597: illegal reference to non-static member 'Game::Rendering::window' 1>c:\users\documents\opengl\game\game\renderer.cpp(43): error C2597: illegal reference to non-static member 'Game::Rendering::window' 1>Done building project "Game.vcxproj" -- FAILED. ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========  
      #include <GL/glew.h> #include <GLFW/glfw3.h> #include "Renderer.h" #include "Timer.h" #include <iostream> namespace Game { GLFWwindow* window; /* Initialize the library */ Rendering::Rendering() { mClock = new Clock; } Rendering::~Rendering() { shutdown(); } bool Rendering::initialize(uint width, uint height, bool fullscreen, std::string window_title) { if (!glfwInit()) { return -1; } /* Create a windowed mode window and its OpenGL context */ window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL); if (!window) { glfwTerminate(); return -1; } /* Make the window's context current */ glfwMakeContextCurrent(window); glViewport(0, 0, (GLsizei)width, (GLsizei)height); glOrtho(0, (GLsizei)width, (GLsizei)height, 0, 1, -1); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glfwSwapInterval(1); glEnable(GL_SMOOTH); glEnable(GL_DEPTH_TEST); glEnable(GL_BLEND); glDepthFunc(GL_LEQUAL); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); glEnable(GL_TEXTURE_2D); glLoadIdentity(); return true; } bool Rendering::render() { /* Loop until the user closes the window */ if (!glfwWindowShouldClose(window)) return false; /* Render here */ mClock->reset(); glfwPollEvents(); if (mClock->step()) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glfwSwapBuffers(window); mClock->update(); } return true; } void Rendering::shutdown() { glfwDestroyWindow(window); glfwTerminate(); } GLFWwindow* Rendering::getCurrentWindow() { return window; } } Renderer.h
      #pragma once namespace Game { class Clock; class Rendering { public: Rendering(); ~Rendering(); bool initialize(uint width, uint height, bool fullscreen, std::string window_title = "Rendering window"); void shutdown(); bool render(); GLFWwindow* getCurrentWindow(); private: GLFWwindow * window; Clock* mClock; }; } Timer.cpp
      #include <GL/glew.h> #include <GLFW/glfw3.h> #include <time.h> #include "Timer.h" namespace Game { Clock::Clock() : mTicksPerSecond(50), mSkipTics(1000 / mTicksPerSecond), mMaxFrameSkip(10), mLoops(0) { mLastTick = tick(); } Clock::~Clock() { } bool Clock::step() { if (tick() > mLastTick && mLoops < mMaxFrameSkip) return true; return false; } void Clock::reset() { mLoops = 0; } void Clock::update() { mLastTick += mSkipTics; mLoops++; } clock_t Clock::tick() { return clock(); } } TImer.h
      #pragma once #include "Common.h" namespace Game { class Clock { public: Clock(); ~Clock(); void update(); bool step(); void reset(); clock_t tick(); private: uint mTicksPerSecond; ufloat mSkipTics; uint mMaxFrameSkip; uint mLoops; uint mLastTick; }; } Common.h
      #pragma once #include <cstdio> #include <cstdlib> #include <ctime> #include <cstring> #include <cmath> #include <iostream> namespace Game { typedef unsigned char uchar; typedef unsigned short ushort; typedef unsigned int uint; typedef unsigned long ulong; typedef float ufloat; }  
    • By lxjk
      Hi guys,
      There are many ways to do light culling in tile-based shading. I've been playing with this idea for a while, and just want to throw it out there.
      Because tile frustums are general small compared to light radius, I tried using cone test to reduce false positives introduced by commonly used sphere-frustum test.
      On top of that, I use distance to camera rather than depth for near/far test (aka. sliced by spheres).
      This method can be naturally extended to clustered light culling as well.
      The following image shows the general ideas

      Performance-wise I get around 15% improvement over sphere-frustum test. You can also see how a single light performs as the following: from left to right (1) standard rendering of a point light; then tiles passed the test of (2) sphere-frustum test; (3) cone test; (4) spherical-sliced cone test

      I put the details in my blog post (https://lxjk.github.io/2018/03/25/Improve-Tile-based-Light-Culling-with-Spherical-sliced-Cone.html), GLSL source code included!
  • Advertisement
  • Advertisement
Sign in to follow this  

OpenGL Shadows problems

This topic is 501 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hey guys, I worked long time ago in shadows but I left it because I couldn't find the problem I still have. I've been following this tutorial and I adapted it on my project but when I render everything I'm having weird issues I don't know why. As you can see in this pic the shadow projection is well calculated from the shader etc but you also can see that the back and front faces of both cubes are getting also weird shadow and also the shadow is repeated among the "terrain". This last problem is because of GL_REPEAT but if I use others parameters to create the texture it's worst... I tried using GL_CULLFACE to remove the weird shadows in the cubes but doesn't work. I'll leave the code here:

#include "../stdafx.h"
#include "Main.h"
#include "../Renderer/Renderer.h"
#include "../GLUtils/GLUtils.h"
#include "../Camera/Camera.h"
#include "../Audio/Audio.h"
#include "../Physics/Physics.h"
#include "../Skybox/Skybox.h"
#include "../Lighting/LightManager.h"
#include "../Entity/Entity.h"
#include "../Editor/Editor.h"
#include "../NativeGeometry/NativeGeometry.h"
#include "../Textures/TextureManager.h"
#include "../RenderTargets/RenderTargets.h"
#include "../ParticleSystem/ParticleSystem.h"
#include "../CEV/CEV.h"
#include "../Timers/Timers.h"
#include "../LUA/LuaManager.h"
#include "../LUA/EventManager.h"
#include "../LUA/EventArguments.h"
#include "../ColShapes/ColShapes.h"
#include "../KeyCode/Keycode.h"

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
	//CoInitializeEx(nullptr, COINIT_MULTITHREADED);  //wtf is this xd

	Console.reset(new CConsole());

	Renderer = std::make_unique<CRenderer>();
	ColShapeManager = std::make_unique<CColShapeManager>();
	Physics = std::make_unique<CPhysics>();
	EventArguments = std::make_unique<CEventsArguments>();
	LuaManager = std::make_unique<CLuaManager>();
	EventManager = std::make_unique<CEventManager>();
	KeyCode = std::make_unique<CKeyCode>();
	RenderTargetManager = std::make_unique<CRenderTargetManager>();
	TextureManager = std::make_unique<CTextureManager>();
	EntityManager = std::make_unique<CEntityManager>();
	FogManager = std::make_unique<CFogManager>();
	LightManager = std::make_unique<CLightManager>();
	Skybox = std::make_unique<CSkybox>();
	Camera = std::make_unique<CCamera>(glm::vec3(10, 10, 10));
	CEAudio = std::make_unique<CAEngine>();
	GLUtils = std::make_unique<CGLUtils>();

	if (!Renderer->CreateGLWindow(1920 / 2 - (1280 / 3) + 200, 1080 / 2 - (800 / 2), 1600, 1200, 16, false)) 
		return 0;


	return 0;

bool first = true;

BOOL DrawGLScene()

	static GLuint depthMapFBO;
	static GLuint SHADOW_WIDTH = 2048, SHADOW_HEIGHT = 2048;
	static GLuint depthMap;
	if (first)
		glGenFramebuffers(1, &depthMapFBO);

		glGenTextures(1, &depthMap);
		glBindTexture(GL_TEXTURE_2D, depthMap);

		glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO);
		glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthMap, 0);
		glBindFramebuffer(GL_FRAMEBUFFER, 0);

		first = false;


	for (int i = 0; i < RenderTargetManager->GetRenderTargets(); i++)
		CRenderTarget* RT = RenderTargetManager->GetRenderTarget(i);
		if (RT)

	static float xx = 0, yy = 3.f, zz = 0;
	if (GetAsyncKeyState(VK_NUMPAD8))
		xx += 0.1f;
	if (GetAsyncKeyState(VK_NUMPAD2))
		xx -= 0.1f;
	if (GetAsyncKeyState(VK_NUMPAD7))
		yy += 0.1f;
	if (GetAsyncKeyState(VK_NUMPAD1))
		yy -= 0.1f;
	if (GetAsyncKeyState(VK_NUMPAD9))
		zz += 0.1f;
	if (GetAsyncKeyState(VK_NUMPAD3))
		zz -= 0.1f;
	glm::mat4 mPROJ = glm::ortho<float>(-10.0f, 10.0f, -10.0f, 10.0f, 0.05f, 50.f);
	glm::mat4 lightView = glm::lookAt(glm::vec3(5.f, 5.f, 5.f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
	glm::mat4 biasMatrix(
		0.5, 0.0, 0.0, 0.0,
		0.0, 0.5, 0.0, 0.0,
		0.0, 0.0, 0.5, 0.0,
		0.5, 0.5, 0.5, 1.0
	glm::mat4 lightSpaceMatrix = biasMatrix * mPROJ * lightView;

	Renderer->ShadowMapping.setUniform("depthMVP", lightSpaceMatrix);

	glm::mat4 mModelToCamera;
	glm::vec3 vPos = glm::vec3(xx, yy, zz);
	mModelToCamera = glm::translate(glm::mat4(1.0), vPos);
	mModelToCamera = glm::scale(mModelToCamera, glm::vec3(2.f));
	Renderer->ShadowMapping.setUniform("model", mModelToCamera);
	glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO);

	Environment::DrawCube(glm::vec3(xx, yy, zz), glm::vec3(2.f), glm::vec4(1.f), 7, true);

	vPos = glm::vec3(xx + 3.f, yy, zz);
	mModelToCamera = glm::translate(glm::mat4(1.0), vPos);
	mModelToCamera = glm::scale(mModelToCamera, glm::vec3(2.f));
	Renderer->ShadowMapping.setUniform("model", mModelToCamera);
	Environment::DrawCube(glm::vec3(xx + 3, yy, zz), glm::vec3(2.f), glm::vec4(1.f), 7, true);


	Environment::DrawPlane(glm::vec3(0, 20.f, -20.f), glm::vec3(0.f, 90.f, 90.f), glm::vec3(10.f, 1.f, 10.f), depthMap);
	Renderer->MainProgram.setUniform("EngineMatrices.DepthBiasMVP", lightSpaceMatrix);
	Renderer->MainProgram.setUniform("shadowMap", 1);
	Renderer->MainProgram.setUniform("bShadowsOn", 1);
	glBindTexture(GL_TEXTURE_2D, depthMap);
	Environment::DrawCube(glm::vec3(xx, yy, zz), glm::vec3(2.f), glm::vec4(1.f), 7, false);
	Environment::DrawCube(glm::vec3(xx + 3.f, yy, zz), glm::vec3(2.f), glm::vec4(1.f), 7, false);



	if (Renderer->IsCullFaceEnabled())

	auto RenderEntity = [](Entity* _Entity)
		if (_Entity->UpdateTransform())
		if (_Entity->ShowCollider)
			btVector3 one, two;
			_Entity->Phys->RigidBody->getAabb(one, two);
			Environment::DrawPoint(glm::vec3(one.x(), one.y(), one.z()), glm::vec3(2.f), glm::vec3(0.f, 1.f, 0.f));
			Environment::DrawPoint(glm::vec3(one.x() + (two.x() - one.x()), one.y(), one.z()), glm::vec3(2.f), glm::vec3(0.f, 1.f, 0.f));
			Environment::DrawPoint(glm::vec3(one.x(), one.y(), one.z() + (two.z() - one.z())), glm::vec3(2.f), glm::vec3(0.f, 1.f, 0.f));
			Environment::DrawPoint(glm::vec3(one.x(), one.y() + (two.y() - one.y()), one.z()), glm::vec3(2.f), glm::vec3(0.f, 1.f, 0.f));
			Environment::DrawPoint(glm::vec3(two.x() - (two.x() - one.x()), two.y(), two.z()), glm::vec3(2.f), glm::vec3(0.f, 1.f, 0.f));
			Environment::DrawPoint(glm::vec3(two.x(), two.y() - (two.y() - one.y()), two.z()), glm::vec3(2.f), glm::vec3(0.f, 1.f, 0.f));
			Environment::DrawPoint(glm::vec3(two.x(), two.y(), two.z() - (two.z() - one.z())), glm::vec3(2.f), glm::vec3(0.f, 1.f, 0.f));
			Environment::DrawPoint(glm::vec3(two.x(), two.y(), two.z()), glm::vec3(2.f), glm::vec3(0.f, 1.f, 0.f));

	for (uint i = 0; i < ColShapeManager->GetShapes(SHAPE_RECTANGLE); i++)
		RectangleCol* currentShape = ColShapeManager->GetShape<RectangleCol>(SHAPE_RECTANGLE, i);
		if (currentShape && currentShape->IsDebugEnabled())

	for (uint i = 0; i < ColShapeManager->GetShapes(SHAPE_SPHERE); i++)
		SphereCol* currentShape = ColShapeManager->GetShape<SphereCol>(SHAPE_SPHERE, i);
		if (currentShape && currentShape->IsDebugEnabled())

	std::map<float, Entity*> TransparentEntities;
	std::map<float, Entity*> FarestEntities;


	for (uint i = 0; i < EntityManager->GetEntities(); i++)
		Entity* currentEntity = EntityManager->GetEntity(i);
		float EntityToCamera = glm::distance(Camera->Position, currentEntity->Position);
		if (currentEntity && currentEntity->CanRender() && EntityToCamera <= Renderer->GetRenderMaxDistance() && currentEntity->IsVisible())
			if (currentEntity->IsDestroying())
				float _alpha = currentEntity->GetAlpha();
				if (_alpha <= 0.f)
				currentEntity->SetAlpha(_alpha - 0.01f);
			if (currentEntity->GetAlpha() < 1.f)
				TransparentEntities[EntityToCamera] = currentEntity;
				FarestEntities[EntityToCamera] = currentEntity;


	for (auto it = FarestEntities.begin(); it != FarestEntities.end(); ++it)

	for (auto it = TransparentEntities.rbegin(); it != TransparentEntities.rend(); ++it)

	Renderer->MainProgram.setUniform("bShadowsOn", 0);


	for (uint i = 0; i < ParticleSystemManager::GetParticleSystems(); i++)
		if (ParticleSystems[i] && ParticleSystems[i]->ID != INT_MAX)
			ParticleSystems[i]->SetMatrices(&Renderer->GetProjectionMatrix(), Camera->Position, Camera->vView, Camera->vUp);


	if (Renderer->IsCullFaceEnabled())


	EventManager->CallEvent(ON_RENDER, EventArguments->GetEventArguments(ON_RENDER));

	return true;

Sorry for the messed code but I use to do that when I'm testing something instead of organizing it first. Maybe I'm missing something stupid but I can't figure out lol. I appreciate any help. Thanks in advance.

Edited by Tonyx97

Share this post

Link to post
Share on other sites

show us the code of all shadowmapping shaders


i believe you are not clamping the projection. from light into the direction of light but its just a thought i don't even know if you are using directionla 'light' for that. everything that falls outside of light projection stays "not shadowed"

Edited by WiredCat

Share this post

Link to post
Share on other sites

Thanks for the reply WiredCat! It's directional light as you can see in the tutorial and also in my code where I transform the matrices using the projection matrix and the light direction matrix too. I've fixed the clamping and I know why it's repeated along the terrain because the terrain it's supposed to be a cube originally modelled with (1, 1, 1) scale and I scale it manually runtime to (100, 1, 100), I've tested with others big models and it doesn't repeat. The last problem is that I can't achieve properly the shadow for the entities that are casting the shadows. Take a look at this and this. You can see that it's not properly projected into the entities and I don't know what's happening. There is the shaders I to project:


#version 430
#extension GL_ARB_shader_storage_buffer_object : enable

smooth in vec2 texCoord;
smooth in vec3 vNormal;
smooth in vec3 vWorldPos;
smooth in vec4 vEyeSpacePos;
smooth in vec4 ShadowCoord;

uniform bool ison = false;
uniform int bShadowsOn;

uniform vec4 vColor;
uniform vec4 vAmbientColor = vec4(1.0);
uniform vec3 vEyePosition;
uniform sampler2D gSampler;
uniform sampler2D gNormalMap;
uniform sampler2D shadowMap;
uniform bool bUseOnlyColor = false;
uniform bool bSkybox = false;
uniform sampler2DShadow testt;

uniform int bEnableBumpMap; 
in mat3 vLightTangent;

#include "Directional_light.frag"
#include "Point_light.frag"
#include "Spot_light.frag"
#include "Fog.frag"
#include "Plasma.frag"
#include "Text_1.frag"
#include "Water.frag"
#include "RoomEditor.frag"

/*vec2 poissonDisk[16] = vec2[]( 
   vec2( -0.94201624, -0.39906216 ), 
   vec2( 0.94558609, -0.76890725 ), 
   vec2( -0.094184101, -0.92938870 ), 
   vec2( 0.34495938, 0.29387760 ), 
   vec2( -0.91588581, 0.45771432 ), 
   vec2( -0.81544232, -0.87912464 ), 
   vec2( -0.38277543, 0.27676845 ), 
   vec2( 0.97484398, 0.75648379 ), 
   vec2( 0.44323325, -0.97511554 ), 
   vec2( 0.53742981, -0.47373420 ), 
   vec2( -0.26496911, -0.41893023 ), 
   vec2( 0.79197514, 0.19090188 ), 
   vec2( -0.24188840, 0.99706507 ), 
   vec2( -0.81409955, 0.91437590 ), 
   vec2( 0.19984126, 0.78641367 ), 
   vec2( 0.14383161, -0.14100790 ) 

float GetVisibility()
    if (bShadowsOn == 0)
		return 1.0;

    float visibility = 1.0;
    float bias = 0.000;

    for (int i = 0; i < 4; i++)
      int index = i;
		  vec4 vShadowSmooth = vec4(ShadowCoord.x + poissonDisk[index].x/700.0, ShadowCoord.y + poissonDisk[index].y/700.0, (ShadowCoord.z-bias)/ShadowCoord.w, 1.0);
		vShadowSmooth = vShadowSmooth * 0.5 + 0.5;
		vShadowSmooth.w = 1.0;
		  float fSub = texture(shadowMap, vShadowSmooth.xy).r; 
		  visibility -= 0.25 * (1.0 - fSub);
    return visibility;

float ShadowCalculation(vec4 fragPosLightSpace)
    vec3 projCoords = fragPosLightSpace.xyz / fragPosLightSpace.w;
    projCoords = projCoords * 0.5 + 0.5;
    float closestDepth = texture(shadowMap, projCoords.xy).r; 
    float currentDepth = projCoords.z;
    float shadow = currentDepth > closestDepth ? 1.0 : 0.0;

    if (projCoords.z > 1.0)
        return 0.0;

    return shadow * 0.6;

void main()
	vec4 vTexColor = texture2D(gSampler, texCoord);
	vec3 vFragColor;
	vec3 vNormalized = normalize(vNormal);
	if (!bUseOnlyColor)
		gl_FragColor = vTexColor * vColor * vAmbientColor;				  //texture without any kind of effect applied (lights etc.)
		gl_FragColor = vColor * vAmbientColor;							  //texture without any kind of effect applied (lights etc.)

	vFragColor = gl_FragColor.xyz;

	//ENGINE SHADERS, will change gl_FragColor if the entity has the shader enabled

	PlasmaShader(texCoord);                    //Plasma.frag
	Text_1Shader(texCoord);                    //Text_1.frag
	Water_Shader(texCoord, vColor.w);          //Water.frag
	Arrow_Shader(texCoord);					   //RoomEditor.frag

	if (iDirectionalLights > 0)
		vec4 Diffuse_DirectionalLightsFinalColor = vec4(1.0);
		vec4 Specular_DirectionalLightsFinalColor = vec4(1.0);
		vec4 Normal_DirectionalLightsFinalColor = vec4(1.0);
		for (int i = 0; i < iDirectionalLights; i++)
			if (DirectionalLights.Lights[i].bEnabled == 1 && !bSkybox)
				Diffuse_DirectionalLightsFinalColor += GetDirectionalLightColor(DirectionalLights.Lights[i], vNormalized);
				Specular_DirectionalLightsFinalColor += GetDirectionalLightSpecularColor(vWorldPos, vEyePosition, DirectionalLights.Lights[i], vNormalized);
				if (bEnableBumpMap == 1)
					Normal_DirectionalLightsFinalColor += GetDirectionalLightNormalColor(DirectionalLights.Lights[i], vLightTangent, texCoord, gNormalMap);
		gl_FragColor *= Diffuse_DirectionalLightsFinalColor * Specular_DirectionalLightsFinalColor * Normal_DirectionalLightsFinalColor;
	if (iPointLights > 0)
		vec4 Diffuse_PointLightsFinalColor = vec4(1.0);
		vec4 Specular_PointLightsFinalColor = vec4(1.0);
		for (int i = 0; i < iPointLights; i++)
			if (PointLights.Lights[i].bEnabled == 1 && !bSkybox)
				Diffuse_PointLightsFinalColor += GetPointLightColor(PointLights.Lights[i], vWorldPos, vNormalized);
				Specular_PointLightsFinalColor += GetPointLightSpecularColor(vWorldPos, vEyePosition, PointLights.Lights[i], vNormalized);
		gl_FragColor *= Diffuse_PointLightsFinalColor * Specular_PointLightsFinalColor;  // vec4(pow(vFragColor, vec3(1.0/2.2)), 1.0)
	if (iSpotLights > 0)
		vec4 SpotLightsFinalColor = vec4(1.0);
		for (int i = 0; i < iSpotLights; i++)
			if (SpotLights.Lights[i].bEnabled == 1)
				SpotLightsFinalColor += GetSpotLightColor(SpotLights.Lights[i], vWorldPos);
		gl_FragColor *= SpotLightsFinalColor;

	if (bShadowsOn == 1)
		//gl_FragColor *= GetVisibility();
		gl_FragColor *= 1.0 - ShadowCalculation(ShadowCoord);
		gl_FragColor.w = 1.0;

	if (FogData.Enabled)
		gl_FragColor = mix(gl_FragColor, FogData.FogColor, GetFogFactor(abs(vEyeSpacePos.z / vEyeSpacePos.w))); 


#version 330 core

layout(location = 0) in vec3 inPous;

uniform mat4 depthMVP;
uniform mat4 model;

void main()
	gl_Position = depthMVP * model * vec4(inPous, 1.0);


#version 330 core

// Ouput data
layout(location = 0) out float fragmentdepth;

void main()
	//fragmentdepth = gl_FragCoord.z;

These are all the shaders I use and everything related to shadows it's in the first code I sent in the main post so you can compare. I think I'm missing something in my C++ main code because as you can see in the picture the shadow is applied triangle by triangle and that should be something I'm missing not sure. Also in the commented code of the MainFrag you can see GetVisibility function which I tested and it works like the one I'm using but with smooth only, the shadow it's applied to the whole entity that casts the shadow and also happens the same error that there are parts in the entity that have no shadow in the borders...

Edited by Tonyx97

Share this post

Link to post
Share on other sites

mhm lets say i didint check the code.


first image shows that maybe you have depth precision problems, that means either bias it out by adding small number to the 

tested fragment so actual_fragment_depth+0.0005 > shadow_depth_fragment then is in shadow might fix it.


but i define point light as something like. position, radius, color, direction, and i fit the frustum of the light as follows:

i define z far value for shadowmap, lets do not care for now for anything like torch lights etc. lets assume we have just directional light as sunlight. you define just light direction, color and z_far (the same one you define when you draw your shadowmap)




if fragment is in shadow frustum then

float actual_fragment_depth = distance(LightPOS, world_vertex_pos) / z_far;

after that

if (actual_fragment_depth > shadow_depth)
color = vec4(0.0, 0.0, 0.0, 1.0);
color = vec4(1.0, 1.0, 1.0, 0.0);

and second image


you need to add this code too you see there resolution precision problems, but theres an easy fix for that das dot product

if (dot( normalize( vectorAB(LightPOS, world_vertex_pos) ), VertexNormal) >= 0.0)
		color = vec4(0.0, 0.0, 0.0, 1.0);

Did i forget to mention that you need to define vertice normals too, so each polygon has its own individual normal facing outwards the box center. 



That should do, cheers/

Share this post

Link to post
Share on other sites

Thanks WiredCat! I've been the whole day working on this and struggling with the shaders and finally got it working taking into account your notes. My fear now is that maybe in the future when I use more complex models the bias I use will fuck up everything in shadows, I set the bias as 0.00005 which is pretty low but it's the one working for all models at the moment. Here's the result:


Share this post

Link to post
Share on other sites

Staying in topic, after I finished directional light I started with spot light since they are easy because they don't need a cube map like point lights. I've been programming the shadows and FBO's for it but I encounter a curious problem projection the shadow, In this pic you can see that there are some black lines but the real shadow of the cube it's properly projected, I need a way to remove those lines somehow, maybe you WiredCat know about this issue.

The shadow calculation function:

float ShadowCalculation()
    vec3 projCoords = ShadowCoord.xyz / ShadowCoord.w;
    vec2 texelSize = 1.0 / textureSize(shadowMap, 0);
    projCoords = projCoords * 0.5 + 0.5;
    float closestDepth = texture(shadowMap, projCoords.xy).r; 
    float currentDepth = projCoords.z; 
    float shadow = 1.0;

	for (int x = -1; x <= 4; x++)
		for (int y = -1; y <= 4; y++)
			shadow += currentDepth > (texture(shadowMap, projCoords.xy + vec2(x, y) * texelSize).r) ? 1.0 : 0.0;

	shadow *= 0.01;

	shadow = currentDepth > closestDepth ? shadow : 0.0;

	if (dot(normalize(vWorldPos - LightPos), normalize(vNormal)) >= 0.0)
		BackFaceShadow = true;
		return 0.0;

	if (projCoords.z <= 0.0 || projCoords.z >= 1.0 || projCoords.x >= 1.0 || projCoords.y >= 1.0 || projCoords.x <= 0.0 || projCoords.y <= 0.0)
		return 0.0;
	BackFaceShadow = false;
    return shadow * 0.8;

I added the 

if (projCoords.z <= 0.0 || projCoords.z >= 1.0 || projCoords.x >= 1.0 || projCoords.y >= 1.0 || projCoords.x <= 0.0 || projCoords.y <= 0.0)

to remove the shadow outside of the perpective projection by the spot light. And where I call it:

if (bShadowsOn == 1)
	ShadowFactor = 1.0 - ShadowCalculation();
	if (BackFaceShadow)
		FinalColor *= vec4(vec3(length(cross(normalize(vWorldPos - LightPos), vNormal))), 1.0);
		FinalColor *= vec4(vec3(ShadowFactor), 1.0);

I also added the line when BackFaceShadow it's true to make progressive color changing to avoid faces change directly from shadow to light.

Edited by Tonyx97

Share this post

Link to post
Share on other sites

You're right I added some bias to remove the acne and now it works, do you know any article or website to fix the peter-panning without having to render the front faces? I'm modelling something and it doesn't have front faces due to remove useless geometry, the model is this and from this is from other perspective. At the moment I have no idea if this is possible to achieve but many games do that, for example GTA5 has a terrain with no front faces and the shadows of the hills are perfect, maybe this is more complex but I want to at least try or read how it's achieved.

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement