15#include <glm/gtc/matrix_transform.hpp>
25#include <unordered_map>
32 struct ShadowResources
35 GLuint Directional = 0;
39 std::shared_ptr<Shader> DepthShader;
40 std::shared_ptr<Shader> SkyShader;
43 GLuint Environment = 0;
44 GLuint Irradiance = 0;
47 GLuint CaptureFBO = 0;
48 GLuint CaptureRBO = 0;
49 std::string LoadedEnvironmentPath;
50 std::uint32_t LoadedEnvironmentResolution = 0;
51 bool EnvironmentReady =
false;
53 int AllocatedShadowQuality = -1;
54 GLuint GPUQueries[3]{0,0,0};
55 std::uint32_t GPUQueryWrite = 0;
56 bool GPUQueryIssued[3]{
false,
false,
false};
57 glm::mat4 DirectionalMatrix{1.0f};
58 glm::mat4 SpotMatrix{1.0f};
59 glm::vec3 PointPosition{0.0f};
60 float PointFar = 25.0f;
61 bool HasDirectional =
false;
63 bool HasPoint =
false;
66 ShadowResources& Shadows()
68 static ShadowResources resources;
85 std::uint64_t MeshIndexCount(
const std::shared_ptr<Mesh>& mesh)
87 if (!mesh || !mesh->GetVertexArray() ||
88 !mesh->GetVertexArray()->GetIndexBuffer())
90 return mesh->GetVertexArray()->GetIndexBuffer()->GetCount();
93 void BeginGPUFrameQuery()
96 if (r.GPUQueries[0] == 0)
97 glGenQueries(3, r.GPUQueries);
101 const std::uint32_t read = (r.GPUQueryWrite + 1) % 3;
102 if (r.GPUQueryIssued[read])
104 GLint available = GL_FALSE;
106 r.GPUQueries[read], GL_QUERY_RESULT_AVAILABLE, &available);
107 if (available == GL_TRUE)
109 GLuint64 nanoseconds = 0;
110 glGetQueryObjectui64v(
111 r.GPUQueries[read], GL_QUERY_RESULT, &nanoseconds);
112 Statistics().GPUTimeMs =
113 static_cast<float>(nanoseconds) / 1000000.0f;
114 Statistics().GPUTimeValid =
true;
115 r.GPUQueryIssued[read] =
false;
118 glBeginQuery(GL_TIME_ELAPSED, r.GPUQueries[r.GPUQueryWrite]);
121 void EndGPUFrameQuery()
124 glEndQuery(GL_TIME_ELAPSED);
125 r.GPUQueryIssued[r.GPUQueryWrite] =
true;
126 r.GPUQueryWrite = (r.GPUQueryWrite + 1) % 3;
129 glm::vec3 WorldPosition(
const glm::mat4& world)
131 return glm::vec3(world[3]);
134 glm::vec3 WorldForward(
const glm::mat4& world)
136 glm::vec3 forward = -glm::vec3(world[2]);
137 const float length = glm::length(forward);
138 return length > 0.0001f ? forward / length
139 : glm::vec3(0.0f, 0.0f, -1.0f);
143 GLuint CompileEnvironmentProgram(
144 const char* vertexSource,
const char* fragmentSource)
146 auto compile=[](GLenum type,
const char* source)->GLuint
148 GLuint shader=glCreateShader(type);
149 glShaderSource(shader,1,&source,
nullptr);
150 glCompileShader(shader);
152 glGetShaderiv(shader,GL_COMPILE_STATUS,&ok);
156 glGetShaderiv(shader,GL_INFO_LOG_LENGTH,&length);
157 std::string log(
static_cast<std::size_t
>(length),
'\0');
158 glGetShaderInfoLog(shader,length,
nullptr,log.data());
159 glDeleteShader(shader);
160 throw std::runtime_error(
161 "Renderer V3 environment shader compile failed: "+log);
165 GLuint vs=compile(GL_VERTEX_SHADER,vertexSource);
166 GLuint fs=compile(GL_FRAGMENT_SHADER,fragmentSource);
167 GLuint program=glCreateProgram();
168 glAttachShader(program,vs);glAttachShader(program,fs);
169 glLinkProgram(program);
170 glDeleteShader(vs);glDeleteShader(fs);
171 GLint ok=GL_FALSE;glGetProgramiv(program,GL_LINK_STATUS,&ok);
174 GLint length=0;glGetProgramiv(program,GL_INFO_LOG_LENGTH,&length);
175 std::string log(
static_cast<std::size_t
>(length),
'\0');
176 glGetProgramInfoLog(program,length,
nullptr,log.data());
177 glDeleteProgram(program);
178 throw std::runtime_error(
179 "Renderer V3 environment shader link failed: "+log);
184 void DrawCaptureCube()
187 if(!vao) glCreateVertexArrays(1,&vao);
188 glBindVertexArray(vao);
189 glDrawArrays(GL_TRIANGLES,0,36);
192 void DeleteEnvironmentTextures(ShadowResources& r)
194 if(r.Environment) glDeleteTextures(1,&r.Environment);
195 if(r.Irradiance) glDeleteTextures(1,&r.Irradiance);
196 if(r.Prefilter) glDeleteTextures(1,&r.Prefilter);
197 if(r.BRDFLUT) glDeleteTextures(1,&r.BRDFLUT);
198 r.Environment=r.Irradiance=r.Prefilter=r.BRDFLUT=0;
199 r.EnvironmentReady=
false;
202 const char* CaptureCubeVS=R
"(
204 out vec3 v_Direction;
205 uniform mat4 u_ViewProjection;
206 const vec3 P[36]=vec3[](
207 vec3(-1,-1,-1),vec3(-1,-1, 1),vec3(-1, 1, 1),vec3(-1,-1,-1),vec3(-1, 1, 1),vec3(-1, 1,-1),
208 vec3( 1,-1, 1),vec3( 1,-1,-1),vec3( 1, 1,-1),vec3( 1,-1, 1),vec3( 1, 1,-1),vec3( 1, 1, 1),
209 vec3(-1,-1, 1),vec3( 1,-1, 1),vec3( 1, 1, 1),vec3(-1,-1, 1),vec3( 1, 1, 1),vec3(-1, 1, 1),
210 vec3( 1,-1,-1),vec3(-1,-1,-1),vec3(-1, 1,-1),vec3( 1,-1,-1),vec3(-1, 1,-1),vec3( 1, 1,-1),
211 vec3(-1, 1, 1),vec3( 1, 1, 1),vec3( 1, 1,-1),vec3(-1, 1, 1),vec3( 1, 1,-1),vec3(-1, 1,-1),
212 vec3(-1,-1,-1),vec3( 1,-1,-1),vec3( 1,-1, 1),vec3(-1,-1,-1),vec3( 1,-1, 1),vec3(-1,-1, 1));
213 void main(){v_Direction=P[gl_VertexID];gl_Position=u_ViewProjection*vec4(v_Direction,1.0);}
216 void EnsureEnvironmentResources()
219 const auto& settings=RendererSettings();
220 const std::string& configuredPath=settings.EnvironmentHDRIPath;
221 const std::filesystem::path environmentPath =
223 const std::string path = environmentPath.string();
225 if(configuredPath.empty())
227 if(r.EnvironmentReady) DeleteEnvironmentTextures(r);
228 r.LoadedEnvironmentPath.clear();
231 if(r.EnvironmentReady &&
232 r.LoadedEnvironmentPath==path &&
233 r.LoadedEnvironmentResolution==settings.EnvironmentResolution)
236 int width=0,height=0,channels=0;
237 stbi_set_flip_vertically_on_load(1);
238 float* pixels=stbi_loadf(path.c_str(),&width,&height,&channels,3);
239 stbi_set_flip_vertically_on_load(0);
242 if(r.LoadedEnvironmentPath!=path)
243 std::cerr<<
"[Renderer V3] Could not load HDRI: "<<path<<
"\n";
244 r.LoadedEnvironmentPath=path;
245 r.EnvironmentReady=
false;
249 GLint previousViewport[4]{};
250 GLint previousFramebuffer = 0;
251 glGetIntegerv(GL_VIEWPORT, previousViewport);
252 glGetIntegerv(GL_FRAMEBUFFER_BINDING, &previousFramebuffer);
254 DeleteEnvironmentTextures(r);
255 if(!r.CaptureFBO) glCreateFramebuffers(1,&r.CaptureFBO);
256 if(!r.CaptureRBO) glCreateRenderbuffers(1,&r.CaptureRBO);
259 glCreateTextures(GL_TEXTURE_2D,1,&hdr);
260 glTextureStorage2D(hdr,1,GL_RGB16F,width,height);
262 hdr,0,0,0,width,height,GL_RGB,GL_FLOAT,pixels);
263 glTextureParameteri(hdr,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
264 glTextureParameteri(hdr,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
265 glTextureParameteri(hdr,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);
266 glTextureParameteri(hdr,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
267 stbi_image_free(pixels);
269 const std::uint32_t size=
270 std::clamp(settings.EnvironmentResolution,128u,1024u);
272 for(std::uint32_t v=size;v>1;v/=2) ++mipLevels;
274 auto makeCube=[](GLuint& id,
int resolution,
int levels)
276 glCreateTextures(GL_TEXTURE_CUBE_MAP,1,&
id);
278 id,levels,GL_RGB16F,resolution,resolution);
280 id,GL_TEXTURE_MIN_FILTER,
281 levels>1?GL_LINEAR_MIPMAP_LINEAR:GL_LINEAR);
282 glTextureParameteri(
id,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
283 glTextureParameteri(
id,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);
284 glTextureParameteri(
id,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
285 glTextureParameteri(
id,GL_TEXTURE_WRAP_R,GL_CLAMP_TO_EDGE);
287 makeCube(r.Environment,size,mipLevels);
288 makeCube(r.Irradiance,32,1);
289 makeCube(r.Prefilter,128,5);
291 glCreateTextures(GL_TEXTURE_2D,1,&r.BRDFLUT);
292 glTextureStorage2D(r.BRDFLUT,1,GL_RG16F,512,512);
293 glTextureParameteri(r.BRDFLUT,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
294 glTextureParameteri(r.BRDFLUT,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
295 glTextureParameteri(r.BRDFLUT,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);
296 glTextureParameteri(r.BRDFLUT,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
298 const glm::mat4 projection=glm::perspective(
299 glm::radians(90.0f),1.0f,0.1f,10.0f);
300 const glm::mat4 views[]={
301 glm::lookAt(glm::vec3(0),glm::vec3( 1,0,0),glm::vec3(0,-1,0)),
302 glm::lookAt(glm::vec3(0),glm::vec3(-1,0,0),glm::vec3(0,-1,0)),
303 glm::lookAt(glm::vec3(0),glm::vec3(0, 1,0),glm::vec3(0,0, 1)),
304 glm::lookAt(glm::vec3(0),glm::vec3(0,-1,0),glm::vec3(0,0,-1)),
305 glm::lookAt(glm::vec3(0),glm::vec3(0,0, 1),glm::vec3(0,-1,0)),
306 glm::lookAt(glm::vec3(0),glm::vec3(0,0,-1),glm::vec3(0,-1,0))};
308 const char* equirectFS=R
"(
310 in vec3 v_Direction;out vec4 o_Color;
311 uniform sampler2D u_HDR;
312 const vec2 invAtan=vec2(0.159154943,0.318309886);
313 void main(){vec3 d=normalize(v_Direction);vec2 uv=vec2(atan(d.z,d.x),asin(d.y));uv*=invAtan;uv+=0.5;o_Color=vec4(texture(u_HDR,uv).rgb,1);}
315 GLuint program=CompileEnvironmentProgram(CaptureCubeVS,equirectFS);
316 glUseProgram(program);glBindTextureUnit(0,hdr);
317 glUniform1i(glGetUniformLocation(program,"u_HDR"),0);
318 glNamedRenderbufferStorage(
319 r.CaptureRBO,GL_DEPTH_COMPONENT24,size,size);
320 glNamedFramebufferRenderbuffer(
321 r.CaptureFBO,GL_DEPTH_ATTACHMENT,GL_RENDERBUFFER,r.CaptureRBO);
322 glBindFramebuffer(GL_FRAMEBUFFER,r.CaptureFBO);
323 glViewport(0,0,size,size);
324 for(
int face=0;face<6;++face)
326 glm::mat4 vp=projection*views[face];
328 glGetUniformLocation(program,
"u_ViewProjection"),
329 1,GL_FALSE,&vp[0][0]);
330 glNamedFramebufferTextureLayer(
331 r.CaptureFBO,GL_COLOR_ATTACHMENT0,r.Environment,0,face);
332 glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
335 glGenerateTextureMipmap(r.Environment);
336 glDeleteProgram(program);glDeleteTextures(1,&hdr);
338 const char* irradianceFS=R
"(
340 in vec3 v_Direction;out vec4 o_Color;uniform samplerCube u_Environment;
341 const float PI=3.14159265359;
342 void main(){vec3 N=normalize(v_Direction);vec3 up=vec3(0,1,0);vec3 right=normalize(cross(up,N));up=normalize(cross(N,right));vec3 irradiance=vec3(0);float samples=0;
343 for(float phi=0;phi<2*PI;phi+=0.12)for(float theta=0;theta<0.5*PI;theta+=0.12){vec3 t=vec3(sin(theta)*cos(phi),sin(theta)*sin(phi),cos(theta));vec3 s=t.x*right+t.y*up+t.z*N;irradiance+=texture(u_Environment,s).rgb*cos(theta)*sin(theta);samples++;}
344 irradiance=PI*irradiance/max(samples,1.0);o_Color=vec4(irradiance,1);}
346 program=CompileEnvironmentProgram(CaptureCubeVS,irradianceFS);
347 glUseProgram(program);glBindTextureUnit(0,r.Environment);
348 glUniform1i(glGetUniformLocation(program,"u_Environment"),0);
349 glNamedRenderbufferStorage(r.CaptureRBO,GL_DEPTH_COMPONENT24,32,32);
350 glViewport(0,0,32,32);
351 for(
int face=0;face<6;++face)
353 glm::mat4 vp=projection*views[face];
354 glUniformMatrix4fv(glGetUniformLocation(program,
"u_ViewProjection"),1,GL_FALSE,&vp[0][0]);
355 glNamedFramebufferTextureLayer(r.CaptureFBO,GL_COLOR_ATTACHMENT0,r.Irradiance,0,face);
356 glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);DrawCaptureCube();
358 glDeleteProgram(program);
360 const char* prefilterFS=R
"(
362 in vec3 v_Direction;out vec4 o_Color;uniform samplerCube u_Environment;uniform float u_Roughness;
363 const float PI=3.14159265359;
364 float RadicalInverse(uint bits){bits=(bits<<16u)|(bits>>16u);bits=((bits&0x55555555u)<<1u)|((bits&0xAAAAAAAAu)>>1u);bits=((bits&0x33333333u)<<2u)|((bits&0xCCCCCCCCu)>>2u);bits=((bits&0x0F0F0F0Fu)<<4u)|((bits&0xF0F0F0F0u)>>4u);bits=((bits&0x00FF00FFu)<<8u)|((bits&0xFF00FF00u)>>8u);return float(bits)*2.3283064365386963e-10;}
365 vec2 Hammersley(uint i,uint n){return vec2(float(i)/float(n),RadicalInverse(i));}
366 vec3 ImportanceGGX(vec2 Xi,vec3 N,float rough){float a=rough*rough;float phi=2*PI*Xi.x;float cosTheta=sqrt((1-Xi.y)/(1+(a*a-1)*Xi.y));float sinTheta=sqrt(max(0,1-cosTheta*cosTheta));vec3 H=vec3(cos(phi)*sinTheta,sin(phi)*sinTheta,cosTheta);vec3 up=abs(N.z)<0.999?vec3(0,0,1):vec3(1,0,0);vec3 tangent=normalize(cross(up,N));vec3 bitangent=cross(N,tangent);return normalize(tangent*H.x+bitangent*H.y+N*H.z);}
367 void main(){vec3 N=normalize(v_Direction),R=N,V=R;vec3 pre=vec3(0);float weight=0;const uint COUNT=256u;for(uint i=0u;i<COUNT;i++){vec3 H=ImportanceGGX(Hammersley(i,COUNT),N,u_Roughness);vec3 L=normalize(2*dot(V,H)*H-V);float NL=max(dot(N,L),0);if(NL>0){pre+=textureLod(u_Environment,L,u_Roughness*4.0).rgb*NL;weight+=NL;}}o_Color=vec4(pre/max(weight,0.001),1);}
369 program=CompileEnvironmentProgram(CaptureCubeVS,prefilterFS);
370 glUseProgram(program);glBindTextureUnit(0,r.Environment);
371 glUniform1i(glGetUniformLocation(program,"u_Environment"),0);
372 for(
int mip=0;mip<5;++mip)
374 int mipSize=128>>mip;
375 glNamedRenderbufferStorage(r.CaptureRBO,GL_DEPTH_COMPONENT24,mipSize,mipSize);
376 glViewport(0,0,mipSize,mipSize);
377 glUniform1f(glGetUniformLocation(program,
"u_Roughness"),
float(mip)/4.0f);
378 for(
int face=0;face<6;++face)
380 glm::mat4 vp=projection*views[face];
381 glUniformMatrix4fv(glGetUniformLocation(program,
"u_ViewProjection"),1,GL_FALSE,&vp[0][0]);
382 glNamedFramebufferTextureLayer(r.CaptureFBO,GL_COLOR_ATTACHMENT0,r.Prefilter,mip,face);
383 glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);DrawCaptureCube();
386 glDeleteProgram(program);
388 const char* fullscreenVS=R
"(
391 void main(){vec2 p=vec2((gl_VertexID<<1)&2,gl_VertexID&2);v_UV=p;gl_Position=vec4(p*2.0-1.0,0,1);}
393 const char* brdfFS=R
"(
395 in vec2 v_UV;out vec2 o_BRDF;const float PI=3.14159265359;
396 float RadicalInverse(uint bits){bits=(bits<<16u)|(bits>>16u);bits=((bits&0x55555555u)<<1u)|((bits&0xAAAAAAAAu)>>1u);bits=((bits&0x33333333u)<<2u)|((bits&0xCCCCCCCCu)>>2u);bits=((bits&0x0F0F0F0Fu)<<4u)|((bits&0xF0F0F0F0u)>>4u);bits=((bits&0x00FF00FFu)<<8u)|((bits&0xFF00FF00u)>>8u);return float(bits)*2.3283064365386963e-10;}
397 vec2 Hammersley(uint i,uint n){return vec2(float(i)/float(n),RadicalInverse(i));}
398 vec3 ImportanceGGX(vec2 Xi,vec3 N,float rough){float a=rough*rough;float phi=2*PI*Xi.x;float cosTheta=sqrt((1-Xi.y)/(1+(a*a-1)*Xi.y));float sinTheta=sqrt(max(0,1-cosTheta*cosTheta));vec3 H=vec3(cos(phi)*sinTheta,sin(phi)*sinTheta,cosTheta);return H;}
399 float G1(float NV,float rough){float k=(rough*rough)*0.5;return NV/(NV*(1-k)+k);}
400 vec2 Integrate(float NV,float rough){vec3 V=vec3(sqrt(max(0,1-NV*NV)),0,NV);float A=0,B=0;const uint COUNT=256u;for(uint i=0u;i<COUNT;i++){vec3 H=ImportanceGGX(Hammersley(i,COUNT),vec3(0,0,1),rough);vec3 L=normalize(2*dot(V,H)*H-V);float NL=max(L.z,0),NH=max(H.z,0),VH=max(dot(V,H),0);if(NL>0){float G=G1(NV,rough)*G1(NL,rough);float vis=(G*VH)/max(NH*NV,0.001);float Fc=pow(1-VH,5);A+=(1-Fc)*vis;B+=Fc*vis;}}return vec2(A,B)/float(COUNT);}
401 void main(){o_BRDF=Integrate(v_UV.x,v_UV.y);}
403 program=CompileEnvironmentProgram(fullscreenVS,brdfFS);
404 glUseProgram(program);
405 glNamedFramebufferTexture(r.CaptureFBO,GL_COLOR_ATTACHMENT0,r.BRDFLUT,0);
406 glNamedRenderbufferStorage(r.CaptureRBO,GL_DEPTH_COMPONENT24,512,512);
407 glViewport(0,0,512,512);glClear(GL_COLOR_BUFFER_BIT);
408 static GLuint fsVao=0;
if(!fsVao)glCreateVertexArrays(1,&fsVao);
409 glBindVertexArray(fsVao);glDrawArrays(GL_TRIANGLES,0,3);
410 glDeleteProgram(program);
413 GL_FRAMEBUFFER,
static_cast<GLuint
>(previousFramebuffer));
415 previousViewport[0], previousViewport[1],
416 previousViewport[2], previousViewport[3]);
417 r.LoadedEnvironmentPath=path;
418 r.LoadedEnvironmentResolution=size;
419 r.EnvironmentReady=
true;
420 std::cout<<
"[Renderer V3] HDRI ready: "<<path<<
"\n";
423 void EnsureShadowResources()
428 glCreateFramebuffers(1, &s.FBO);
430 const int quality = std::clamp(RendererSettings().ShadowQuality, 0, 2);
431 if (s.AllocatedShadowQuality != quality)
433 if (s.Directional) glDeleteTextures(1, &s.Directional);
434 if (s.Spot) glDeleteTextures(1, &s.Spot);
435 if (s.Point) glDeleteTextures(1, &s.Point);
436 s.Directional = s.Spot = s.Point = 0;
438 const int directionalSizes[] = {1024, 2048, 4096};
439 const int spotSizes[] = {512, 1024, 2048};
440 const int pointSizes[] = {256, 512, 1024};
442 auto createDepth2D = [](GLuint& texture,
int size)
444 glCreateTextures(GL_TEXTURE_2D, 1, &texture);
446 texture, 1, GL_DEPTH_COMPONENT32F, size, size);
448 texture, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
450 texture, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
452 texture, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
454 texture, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
455 const float border[] = {1,1,1,1};
456 glTextureParameterfv(
457 texture, GL_TEXTURE_BORDER_COLOR, border);
460 createDepth2D(s.Directional, directionalSizes[quality]);
461 createDepth2D(s.Spot, spotSizes[quality]);
463 glCreateTextures(GL_TEXTURE_CUBE_MAP, 1, &s.Point);
465 s.Point, 1, GL_DEPTH_COMPONENT32F,
466 pointSizes[quality], pointSizes[quality]);
468 s.Point, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
470 s.Point, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
472 s.Point, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
474 s.Point, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
476 s.Point, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
478 s.AllocatedShadowQuality = quality;
486 const std::string depthVS = R
"(
488 layout(location=0) in vec3 a_Position;
489 layout(location=2) in vec2 a_TexCoord;
490 layout(location=3) in vec4 a_BoneIDs;
491 layout(location=4) in vec4 a_BoneWeights;
492 uniform mat4 u_Transform;
493 uniform int u_UseSkinning;
494 uniform mat4 u_Bones[128];
495 uniform mat4 u_ViewProjection;
496 out vec3 v_WorldPosition;
499 vec4 localPosition=vec4(a_Position,1.0);
500 if(u_UseSkinning==1){
501 ivec4 ids=ivec4(a_BoneIDs);
502 mat4 skin=u_Bones[ids.x]*a_BoneWeights.x+
503 u_Bones[ids.y]*a_BoneWeights.y+
504 u_Bones[ids.z]*a_BoneWeights.z+
505 u_Bones[ids.w]*a_BoneWeights.w;
506 if(dot(a_BoneWeights,vec4(1.0))>0.0) localPosition=skin*localPosition;
508 vec4 w = u_Transform * localPosition;
509 v_WorldPosition = w.xyz;
510 v_TexCoord = a_TexCoord;
511 gl_Position = u_ViewProjection * w;
513 const std::string depthFS = R
"(
515 in vec3 v_WorldPosition;
517 uniform sampler2D u_AlphaTexture;
518 uniform int u_UseAlphaTexture;
519 uniform int u_AlphaClip;
520 uniform float u_AlphaCutoff;
521 uniform float u_BaseAlpha;
522 uniform int u_RadialDepth;
523 uniform vec3 u_LightPosition;
524 uniform float u_FarPlane;
526 float alpha=u_BaseAlpha;
527 if(u_UseAlphaTexture==1) alpha*=texture(u_AlphaTexture,v_TexCoord).a;
528 if(u_AlphaClip==1 && alpha<u_AlphaCutoff) discard;
530 gl_FragDepth = length(v_WorldPosition-u_LightPosition)/u_FarPlane;
534 const std::string skyVS = R
"(
536 const vec2 p[3]=vec2[3](vec2(-1.0,-1.0),vec2(3.0,-1.0),vec2(-1.0,3.0));
538 void main(){ v_UV=p[gl_VertexID]*0.5+0.5; gl_Position=vec4(p[gl_VertexID],1.0,1.0); })";
539 const std::string skyFS = R
"(
541 in vec2 v_UV; out vec4 o_Color;
542 uniform mat4 u_InverseViewProjection;
543 uniform vec3 u_SunDirection;
544 uniform vec3 u_SunColor;
545 uniform vec3 u_CameraPosition;
546 uniform float u_EnvironmentIntensity;
547 uniform float u_EnvironmentRotation;
548 uniform int u_HasHDRI;
549 uniform samplerCube u_EnvironmentMap;
550 vec3 RotateY(vec3 d,float angle){
551 float c=cos(angle),s=sin(angle);
552 return vec3(c*d.x+s*d.z,d.y,-s*d.x+c*d.z);
555 vec2 ndc=v_UV*2.0-1.0;
556 vec4 w=u_InverseViewProjection*vec4(ndc,1.0,1.0);
557 vec3 d=normalize(w.xyz/w.w-u_CameraPosition);
558 d=RotateY(d,u_EnvironmentRotation);
559 float h=clamp(d.y*0.5+0.5,0.0,1.0);
560 vec3 horizon=vec3(0.62,0.72,0.86);
561 vec3 zenith=vec3(0.08,0.22,0.48);
562 vec3 c=mix(horizon,zenith,pow(h,0.7));
563 float sun=pow(max(dot(d,normalize(-u_SunDirection)),0.0),512.0);
564 c+=u_SunColor*sun*3.0;
566 c=textureLod(u_EnvironmentMap,d,0.0).rgb;
567 o_Color=vec4(c*u_EnvironmentIntensity,1.0);
570 glCreateVertexArrays(1, &s.SkyVAO);
573 void UploadSkinning(
Entity entity,
const std::shared_ptr<Mesh>& mesh,
574 const std::shared_ptr<Shader>& shader)
576 constexpr std::size_t MaxBones = 128;
577 const bool canSkin = mesh && mesh->HasSkinning() &&
580 shader->SetInt(
"u_UseSkinning", canSkin ? 1 : 0);
581 if (!canSkin)
return;
584 const auto palette = animator.
Animation->EvaluatePose(
585 animator.ClipIndex, animator.TimeSeconds);
586 const std::size_t count = std::min(palette.size(), MaxBones);
587 for (std::size_t i=0;i<count;++i)
588 shader->SetMat4(
"u_Bones[" + std::to_string(i) +
"]", palette[i]);
591 void RenderDepthScene(
Scene& scene,
const glm::mat4& lightVP,
592 bool radial,
const glm::vec3& lightPos,
596 s.DepthShader->Bind();
597 s.DepthShader->SetInt(
"u_RadialDepth", radial ? 1 : 0);
598 s.DepthShader->SetFloat3(
"u_LightPosition", lightPos);
599 s.DepthShader->SetFloat(
"u_FarPlane", farPlane);
600 for (
Entity entity : scene.GetEntities())
606 if (!mesh.MeshAsset)
continue;
608 auto drawDepth = [&](
const std::shared_ptr<Material>& material,
610 std::uint32_t offset)
612 const bool clip = material &&
614 s.DepthShader->SetInt(
"u_AlphaClip", clip ? 1 : 0);
615 s.DepthShader->SetFloat(
"u_AlphaCutoff",
616 material ? material->AlphaCutoff() : 0.5f);
617 s.DepthShader->SetFloat(
"u_BaseAlpha",
618 material ? material->GetColor().a : 1.0f);
619 const bool textured = clip && material->IsUsingTexture();
620 s.DepthShader->SetInt(
"u_UseAlphaTexture", textured ? 1 : 0);
621 s.DepthShader->SetInt(
"u_AlphaTexture", 0);
622 if (textured) material->GetTexture()->Bind(0);
624 UploadSkinning(entity, mesh.MeshAsset, s.DepthShader);
625 auto& stats = Statistics();
626 ++stats.ShadowDrawCalls;
627 const std::uint64_t indexCount =
628 count ? count : MeshIndexCount(mesh.MeshAsset);
629 stats.ShadowTriangles += indexCount / 3;
632 s.DepthShader, count, offset,
633 scene.GetWorldTransform(entity), lightVP,
637 s.DepthShader, scene.GetWorldTransform(entity),
638 lightVP, glm::vec4(1.0f), 0);
641 const auto& subs = mesh.MeshAsset->GetSubmeshes();
642 if (!subs.empty() && !renderer.Materials.empty())
644 for (
const auto& sub : subs)
646 auto mat = renderer.GetMaterial(sub.MaterialIndex);
647 if (!mat) mat = renderer.MaterialAsset;
648 drawDepth(mat, sub.IndexCount, sub.IndexOffset);
651 else drawDepth(renderer.MaterialAsset, 0, 0);
655 void BuildShadowMaps(
Scene& scene)
657 EnsureShadowResources();
659 s.HasDirectional = s.HasSpot = s.HasPoint =
false;
660 if (!RendererSettings().Shadows)
664 std::clamp(RendererSettings().ShadowQuality, 0, 2);
665 const int directionalSizes[] = {1024, 2048, 4096};
666 const int spotSizes[] = {512, 1024, 2048};
667 const int pointSizes[] = {256, 512, 1024};
669 GLint oldViewport[4];
670 GLint oldFramebuffer = 0;
671 glGetIntegerv(GL_VIEWPORT, oldViewport);
672 glGetIntegerv(GL_FRAMEBUFFER_BINDING, &oldFramebuffer);
673 glBindFramebuffer(GL_FRAMEBUFFER, s.FBO);
674 glDrawBuffer(GL_NONE); glReadBuffer(GL_NONE);
675 glEnable(GL_DEPTH_TEST);
676 glCullFace(GL_FRONT);
678 for (
Entity e : scene.GetEntities())
680 const glm::mat4 world = scene.GetWorldTransform(e);
691 const glm::vec3 dir = WorldForward(world);
693 glm::vec3 boundsMin( 1.0e30f);
694 glm::vec3 boundsMax(-1.0e30f);
695 bool hasCaster =
false;
696 for (
Entity caster : scene.GetEntities())
702 const glm::mat4 casterWorld = scene.GetWorldTransform(caster);
703 const glm::vec3 p = WorldPosition(casterWorld);
706 const glm::vec3 sx = glm::vec3(casterWorld[0]);
707 const glm::vec3 sy = glm::vec3(casterWorld[1]);
708 const glm::vec3 sz = glm::vec3(casterWorld[2]);
709 const float radius = std::max({glm::length(sx), glm::length(sy), glm::length(sz), 1.0f});
710 boundsMin = glm::min(boundsMin, p - glm::vec3(radius));
711 boundsMax = glm::max(boundsMax, p + glm::vec3(radius));
715 const glm::vec3 center = hasCaster
716 ? (boundsMin + boundsMax) * 0.5f
718 const float sceneRadius = hasCaster
719 ? std::max(glm::length(boundsMax - boundsMin) * 0.5f, 5.0f)
721 const float orthoExtent = sceneRadius * 1.25f;
722 const float lightDistance = sceneRadius * 2.5f;
723 const glm::vec3 pos = center - dir * lightDistance;
724 const glm::vec3 up = std::abs(glm::dot(dir, glm::vec3(0,1,0))) > 0.95f
728 const glm::mat4 lightView = glm::lookAt(pos, center, up);
729 const glm::mat4 lightProjection = glm::ortho(
730 -orthoExtent, orthoExtent,
731 -orthoExtent, orthoExtent,
732 0.1f, lightDistance + sceneRadius * 2.0f);
733 s.DirectionalMatrix = lightProjection * lightView;
734 glNamedFramebufferTexture(s.FBO,GL_DEPTH_ATTACHMENT,s.Directional,0);
735 glViewport(0,0,directionalSizes[quality],directionalSizes[quality]); glClear(GL_DEPTH_BUFFER_BIT);
736 ++Statistics().ShadowPasses;
737 RenderDepthScene(scene,s.DirectionalMatrix,
false,pos,60.f);
738 s.HasDirectional=
true;
746 const glm::vec3 pos=WorldPosition(world), dir=WorldForward(world);
747 glm::vec3 up=std::abs(glm::dot(dir,glm::vec3(0,1,0)))>0.95f?glm::vec3(0,0,1):glm::vec3(0,1,0);
748 s.SpotMatrix=glm::perspective(glm::radians(std::min(l.OuterAngle*2.f,175.f)),1.f,0.05f,std::max(l.Range,0.1f))*glm::lookAt(pos,pos+dir,up);
749 glNamedFramebufferTexture(s.FBO,GL_DEPTH_ATTACHMENT,s.Spot,0);
750 glViewport(0,0,spotSizes[quality],spotSizes[quality]); glClear(GL_DEPTH_BUFFER_BIT);
751 ++Statistics().ShadowPasses;
752 RenderDepthScene(scene,s.SpotMatrix,
false,pos,l.Range);
761 s.PointPosition=WorldPosition(world); s.PointFar=std::max(l.Range,0.1f);
762 const glm::mat4 proj=glm::perspective(glm::radians(90.f),1.f,0.05f,s.PointFar);
763 const std::array<glm::vec3,6> dirs={glm::vec3(1,0,0),{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}};
764 const std::array<glm::vec3,6> ups={glm::vec3(0,-1,0),{0,-1,0},{0,0,1},{0,0,-1},{0,-1,0},{0,-1,0}};
765 glViewport(0,0,pointSizes[quality],pointSizes[quality]);
766 for(
int face=0;face<6;++face)
768 ++Statistics().ShadowPasses;
769 glNamedFramebufferTextureLayer(s.FBO,GL_DEPTH_ATTACHMENT,s.Point,0,face);
770 glClear(GL_DEPTH_BUFFER_BIT);
771 RenderDepthScene(scene,proj*glm::lookAt(s.PointPosition,s.PointPosition+dirs[face],ups[face]),
true,s.PointPosition,s.PointFar);
778 glBindFramebuffer(GL_FRAMEBUFFER,
static_cast<GLuint
>(oldFramebuffer));
779 glViewport(oldViewport[0],oldViewport[1],oldViewport[2],oldViewport[3]);
782 void RenderSky(
const glm::mat4& viewProjection,
const glm::vec3& cameraPosition,
Scene& scene)
785 glm::vec3 sunDir(0.2f,-1.0f,0.2f), sunColor(1.0f,0.95f,0.85f);
788 glEnable(GL_DEPTH_TEST);
789 glDepthFunc(GL_LEQUAL);
790 glDepthMask(GL_FALSE);
792 s.SkyShader->SetMat4(
"u_InverseViewProjection",glm::inverse(viewProjection));
793 s.SkyShader->SetFloat3(
"u_SunDirection",sunDir);
794 s.SkyShader->SetFloat3(
"u_SunColor",sunColor);
795 s.SkyShader->SetFloat3(
"u_CameraPosition",cameraPosition);
796 const auto& graphics = RendererSettings();
797 s.SkyShader->SetFloat(
798 "u_EnvironmentIntensity", graphics.EnvironmentIntensity);
799 s.SkyShader->SetFloat(
800 "u_EnvironmentRotation",
801 glm::radians(graphics.EnvironmentRotation));
803 "u_HasHDRI", s.EnvironmentReady ? 1 : 0);
804 s.SkyShader->SetInt(
"u_EnvironmentMap", 12);
805 if (s.EnvironmentReady)
806 glBindTextureUnit(12, s.Environment);
807 glBindVertexArray(s.SkyVAO); glDrawArrays(GL_TRIANGLES,0,3); glBindVertexArray(0);
808 glDepthMask(GL_TRUE);
809 glDepthFunc(GL_LESS);
812 void UploadLighting(
Scene& scene,
const std::shared_ptr<Shader>& shader,
813 const glm::vec3& cameraPosition)
817 shader->SetFloat3(
"u_ViewPosition",cameraPosition);
818 shader->SetFloat3(
"u_AmbientColor",{0.035f,0.045f,0.065f});
819 const auto& graphics = RendererSettings();
820 shader->SetInt(
"u_UseIBL", graphics.ImageBasedLighting ? 1 : 0);
822 "u_EnvironmentIntensity", graphics.EnvironmentIntensity);
824 "u_DiffuseIBLStrength", graphics.DiffuseIBLStrength);
826 "u_SpecularIBLStrength", graphics.SpecularIBLStrength);
828 "u_EnvironmentRotation",
829 glm::radians(graphics.EnvironmentRotation));
830 auto& environment = Shadows();
832 "u_HasHDRI", environment.EnvironmentReady ? 1 : 0);
833 shader->SetInt(
"u_IrradianceMap", 9);
834 shader->SetInt(
"u_PrefilterMap", 10);
835 shader->SetInt(
"u_BRDFLUT", 11);
836 if (environment.EnvironmentReady)
838 glBindTextureUnit(9, environment.Irradiance);
839 glBindTextureUnit(10, environment.Prefilter);
840 glBindTextureUnit(11, environment.BRDFLUT);
842 bool hasDirectional=
false;
int pointCount=0,spotCount=0;
843 for(
Entity e:scene.GetEntities())
845 const glm::mat4 world=scene.GetWorldTransform(e);
849 shader->SetInt(
"u_HasDirectionalLight",1);
850 shader->SetFloat3(
"u_DirectionalLight.direction",WorldForward(world));
851 shader->SetFloat3(
"u_DirectionalLight.color",l.Color);
852 shader->SetFloat(
"u_DirectionalLight.intensity",std::max(l.Intensity,0.f));
853 shader->SetFloat(
"u_DirectionalShadowBias",l.ShadowBias);
858 const auto& l=e.GetComponent<
PointLightComponent>();
const std::string b=
"u_PointLights["+std::to_string(pointCount)+
"]";
859 shader->SetFloat3(b+
".position",WorldPosition(world)); shader->SetFloat3(b+
".color",l.Color);
860 shader->SetFloat(b+
".intensity",std::max(l.Intensity,0.f)); shader->SetFloat(b+
".range",std::max(l.Range,0.01f));
861 shader->SetFloat(
"u_PointShadowBias",l.ShadowBias); ++pointCount;
865 const auto& l=e.GetComponent<
SpotLightComponent>();
const std::string b=
"u_SpotLights["+std::to_string(spotCount)+
"]";
866 shader->SetFloat3(b+
".position",WorldPosition(world)); shader->SetFloat3(b+
".direction",WorldForward(world)); shader->SetFloat3(b+
".color",l.Color);
867 shader->SetFloat(b+
".intensity",std::max(l.Intensity,0.f)); shader->SetFloat(b+
".range",std::max(l.Range,0.01f));
868 shader->SetFloat(b+
".innerCos",std::cos(glm::radians(l.InnerAngle))); shader->SetFloat(b+
".outerCos",std::cos(glm::radians(l.OuterAngle)));
869 shader->SetFloat(
"u_SpotShadowBias",l.ShadowBias); ++spotCount;
872 shader->SetInt(
"u_HasDirectionalLight",hasDirectional?1:0); shader->SetInt(
"u_PointLightCount",pointCount); shader->SetInt(
"u_SpotLightCount",spotCount);
873 shader->SetInt(
"u_HasDirectionalShadow",s.HasDirectional?1:0); shader->SetInt(
"u_HasPointShadow",s.HasPoint?1:0); shader->SetInt(
"u_HasSpotShadow",s.HasSpot?1:0);
874 shader->SetMat4(
"u_DirectionalLightSpace",s.DirectionalMatrix); shader->SetMat4(
"u_SpotLightSpace",s.SpotMatrix);
875 shader->SetFloat3(
"u_PointShadowPosition",s.PointPosition); shader->SetFloat(
"u_PointShadowFar",s.PointFar);
876 glBindTextureUnit(5,s.Directional); glBindTextureUnit(6,s.Point); glBindTextureUnit(7,s.Spot);
877 shader->SetInt(
"u_DirectionalShadowMap",5); shader->SetInt(
"u_PointShadowMap",6); shader->SetInt(
"u_SpotShadowMap",7);
884 struct ParticleInstanceGPU
891 struct ParticleRenderResources
895 GLuint InstanceVBO = 0;
896 std::shared_ptr<Shader> ShaderProgram;
897 std::unordered_map<std::string, std::shared_ptr<Texture2D>> Textures;
900 ParticleRenderResources& ParticleResources()
902 static ParticleRenderResources r;
906 void EnsureParticleResources()
908 auto& r = ParticleResources();
909 if (r.VAO != 0)
return;
913 const float vertices[] = {
914 -0.5f,-0.5f, 0,0, 0.5f,-0.5f, 1,0, 0.5f, 0.5f, 1,1,
915 -0.5f,-0.5f, 0,0, 0.5f, 0.5f, 1,1, -0.5f, 0.5f, 0,1
917 glGenVertexArrays(1, &r.VAO);
918 glGenBuffers(1, &r.VBO);
919 glGenBuffers(1, &r.InstanceVBO);
920 glBindVertexArray(r.VAO);
922 glBindBuffer(GL_ARRAY_BUFFER, r.VBO);
923 glBufferData(GL_ARRAY_BUFFER,
sizeof(vertices), vertices, GL_STATIC_DRAW);
924 glEnableVertexAttribArray(0);
925 glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4*
sizeof(
float),
nullptr);
926 glEnableVertexAttribArray(1);
927 glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4*
sizeof(
float),
928 reinterpret_cast<void*
>(2*
sizeof(
float)));
930 glBindBuffer(GL_ARRAY_BUFFER, r.InstanceVBO);
931 glBufferData(GL_ARRAY_BUFFER,
sizeof(ParticleInstanceGPU),
nullptr, GL_STREAM_DRAW);
932 glEnableVertexAttribArray(2);
933 glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE,
sizeof(ParticleInstanceGPU),
934 reinterpret_cast<void*
>(offsetof(ParticleInstanceGPU, Position)));
935 glVertexAttribDivisor(2, 1);
936 glEnableVertexAttribArray(3);
937 glVertexAttribPointer(3, 1, GL_FLOAT, GL_FALSE,
sizeof(ParticleInstanceGPU),
938 reinterpret_cast<void*
>(offsetof(ParticleInstanceGPU, Size)));
939 glVertexAttribDivisor(3, 1);
940 glEnableVertexAttribArray(4);
941 glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE,
sizeof(ParticleInstanceGPU),
942 reinterpret_cast<void*
>(offsetof(ParticleInstanceGPU, Color)));
943 glVertexAttribDivisor(4, 1);
944 glBindVertexArray(0);
946 const std::string vs = R
"(
948 layout(location=0) in vec2 a_Position;
949 layout(location=1) in vec2 a_UV;
950 layout(location=2) in vec3 i_WorldPosition;
951 layout(location=3) in float i_Size;
952 layout(location=4) in vec4 i_Color;
953 uniform mat4 u_ViewProjection;
954 uniform vec3 u_CameraRight;
955 uniform vec3 u_CameraUp;
959 vec3 world = i_WorldPosition +
960 u_CameraRight * a_Position.x * i_Size +
961 u_CameraUp * a_Position.y * i_Size;
962 gl_Position = u_ViewProjection * vec4(world,1.0);
966 const std::string fs = R
"(
968 layout(location=0) out vec4 o_Color;
971 uniform sampler2D u_Texture;
972 uniform int u_UseTexture;
974 vec4 texel = u_UseTexture != 0 ? texture(u_Texture, v_UV) : vec4(1.0);
975 o_Color = texel * v_Color;
976 if (o_Color.a <= 0.003) discard;
981 std::shared_ptr<Texture2D> ParticleTexture(const std::string& path)
983 if (path.empty())
return {};
984 auto& cache = ParticleResources().Textures;
985 auto it = cache.find(path);
986 if (it != cache.end())
return it->second;
990 cache[path] = texture;
993 catch (...) {
Log::Warn(
"Particle texture load failed: " + path);
return {}; }
996 void RenderParticles(
Scene& scene,
const glm::mat4& viewProjection,
999 EnsureParticleResources();
1000 auto& r = ParticleResources();
1001 if (!r.ShaderProgram)
return;
1003 const glm::mat4 inverseVP = glm::inverse(viewProjection);
1004 const glm::vec3 right = glm::normalize(glm::vec3(inverseVP[0]));
1005 const glm::vec3 up = glm::normalize(glm::vec3(inverseVP[1]));
1008 glDepthMask(GL_FALSE);
1009 r.ShaderProgram->Bind();
1010 r.ShaderProgram->SetMat4(
"u_ViewProjection", viewProjection);
1011 r.ShaderProgram->SetFloat3(
"u_CameraRight", right);
1012 r.ShaderProgram->SetFloat3(
"u_CameraUp", up);
1013 r.ShaderProgram->SetInt(
"u_Texture", 0);
1014 glBindVertexArray(r.VAO);
1016 std::vector<ParticleInstanceGPU> instances;
1017 for (
Entity entity : scene.GetEntities())
1021 const auto& particles = scene.GetParticles(entity.GetHandle());
1022 if (particles.empty())
continue;
1025 instances.reserve(particles.size());
1026 for (
const auto& p : particles)
1027 instances.push_back({p.Position, p.Size, p.Color});
1030 glBlendFunc(GL_SRC_ALPHA, GL_ONE);
1032 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1034 auto texture = ParticleTexture(settings.TexturePath);
1035 r.ShaderProgram->SetInt(
"u_UseTexture", texture ? 1 : 0);
1036 if (texture) texture->Bind(0);
1038 glBindBuffer(GL_ARRAY_BUFFER, r.InstanceVBO);
1039 glBufferData(GL_ARRAY_BUFFER,
1040 static_cast<GLsizeiptr
>(instances.size() *
sizeof(ParticleInstanceGPU)),
1041 instances.data(), GL_STREAM_DRAW);
1042 glDrawArraysInstanced(GL_TRIANGLES, 0, 6,
1043 static_cast<GLsizei
>(instances.size()));
1046 stats.Triangles +=
static_cast<std::uint64_t
>(instances.size()) * 2;
1049 glBindVertexArray(0);
1050 glDepthMask(GL_TRUE);
1051 glDisable(GL_BLEND);
1056 const glm::vec3& cameraPosition,
1057 bool rebuildShadowMaps)
1059 const auto cpuStart = std::chrono::steady_clock::now();
1060 auto& stats = Statistics();
1061 const float previousGPUTime = stats.GPUTimeMs;
1062 const bool previousGPUValid = stats.GPUTimeValid;
1064 stats.GPUTimeMs = previousGPUTime;
1065 stats.GPUTimeValid = previousGPUValid;
1066 BeginGPUFrameQuery();
1068 EnsureEnvironmentResources();
1069 if (rebuildShadowMaps)
1070 BuildShadowMaps(scene);
1071 RenderSky(viewProjection,cameraPosition,scene);
1080 if(!mesh.MeshAsset || !renderer.MaterialAsset)
continue;
1083 auto drawMaterial=[&](
const std::shared_ptr<Material>& material,
1084 std::uint32_t count,std::uint32_t offset)
1086 if(!material || !material->GetShader())
return;
1087 const auto& shader=material->GetShader();
1088 UploadLighting(scene,shader,cameraPosition);
1089 shader->SetInt(
"u_SurfaceMode",
static_cast<int>(material->SurfaceMode()));
1090 shader->SetFloat(
"u_AlphaCutoff", material->AlphaCutoff());
1092 const bool transparent =
1097 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1098 glDepthMask(GL_FALSE);
1102 glDisable(GL_BLEND);
1103 glDepthMask(GL_TRUE);
1106 shader->SetFloat(
"u_Metallic",glm::clamp(material->Metallic(),0.f,1.f));
1107 shader->SetFloat(
"u_Roughness",glm::clamp(material->Roughness(),0.04f,1.f));
1108 shader->SetFloat(
"u_AO",glm::clamp(material->AmbientOcclusion(),0.f,1.f));
1109 shader->SetFloat(
"u_NormalStrength",glm::max(material->NormalStrength(),0.f));
1110 shader->SetFloat3(
"u_EmissiveColor",material->EmissiveColor());
1111 shader->SetFloat(
"u_EmissiveStrength",glm::max(material->EmissiveStrength(),0.f));
1112 if(material->IsUsingTexture()) material->GetTexture()->Bind(0);
1113 shader->SetInt(
"u_Texture",0);
1115 const auto bindMap=[&](
const std::shared_ptr<Texture2D>& tex,
1116 const char* sampler,
const char* enabled,
int slot)
1118 shader->SetInt(enabled,tex?1:0);shader->SetInt(sampler,slot);
1119 if(tex)tex->Bind(
static_cast<std::uint32_t
>(slot));
1121 bindMap(material->GetNormalTexture(),
"u_NormalMap",
"u_UseNormalMap",1);
1122 bindMap(material->GetMetallicTexture(),
"u_MetallicMap",
"u_UseMetallicMap",2);
1123 bindMap(material->GetRoughnessTexture(),
"u_RoughnessMap",
"u_UseRoughnessMap",3);
1124 bindMap(material->GetAOTexture(),
"u_AOMap",
"u_UseAOMap",4);
1125 bindMap(material->GetEmissiveTexture(),
"u_EmissiveMap",
"u_UseEmissiveMap",8);
1127 UploadSkinning(entity, mesh.MeshAsset, shader);
1129 const std::uint64_t indexCount =
1130 count ? count : MeshIndexCount(mesh.MeshAsset);
1131 stats.Triangles += indexCount / 3;
1134 count,offset,entityWorld,viewProjection,
1135 material->GetColor(),material->IsUsingTexture()?1:0);
1138 entityWorld,viewProjection,
1139 material->GetColor(),material->IsUsingTexture()?1:0);
1143 glDepthMask(GL_TRUE);
1144 glDisable(GL_BLEND);
1148 const auto& subs=mesh.MeshAsset->GetSubmeshes();
1149 if(!subs.empty() && !renderer.Materials.empty())
1151 for(
const auto& sub:subs)
1153 auto mat=renderer.GetMaterial(sub.MaterialIndex);
1154 if(!mat)mat=renderer.MaterialAsset;
1155 drawMaterial(mat,sub.IndexCount,sub.IndexOffset);
1158 else drawMaterial(renderer.MaterialAsset,0,0);
1161 RenderParticles(scene, viewProjection, stats);
1164 const auto cpuEnd = std::chrono::steady_clock::now();
1166 std::chrono::duration<float, std::milli>(
1167 cpuEnd - cpuStart).count();
1176 auto& particles = ParticleResources();
1177 particles.ShaderProgram.reset();
1178 particles.Textures.clear();
1179 if (particles.InstanceVBO != 0)
1181 glDeleteBuffers(1, &particles.InstanceVBO);
1182 particles.InstanceVBO = 0;
1184 if (particles.VBO != 0)
1186 glDeleteBuffers(1, &particles.VBO);
1189 if (particles.VAO != 0)
1191 glDeleteVertexArrays(1, &particles.VAO);
1199 RendererSettings() = settings;
1204 return RendererSettings();
1209 return Statistics();
Animation declarations for the Animation subsystem.
AssetManager declarations for the Asset subsystem.
Buffer declarations for the Rendering subsystem.
Log declarations for the Core subsystem.
Material declarations for the Rendering subsystem.
Mesh declarations for the Rendering subsystem.
Renderer declarations for the Rendering subsystem.
Scene declarations for the Scenes and Native Scripting subsystem.
SceneRenderer declarations for the Scenes and Native Scripting subsystem.
Shader declarations for the Rendering subsystem.
Texture declarations for the Rendering subsystem.
VertexArray declarations for the Rendering subsystem.
static std::shared_ptr< Texture2D > LoadTexture(const std::filesystem::path &path)
static std::filesystem::path ResolveProjectPath(const std::filesystem::path &path)
static void Warn(std::string_view message)
static void SubmitRange(const std::shared_ptr< VertexArray > &vertexArray, const std::shared_ptr< Shader > &shader, std::uint32_t indexCount, std::uint32_t indexOffset, const glm::mat4 &transform, const glm::mat4 &viewProjection, const glm::vec4 &color, int useTexture)
static void Submit(const std::shared_ptr< VertexArray > &vertexArray, const std::shared_ptr< Shader > &shader, const glm::mat4 &transform=glm::mat4(1.0f), const glm::mat4 &viewProjection=glm::mat4(1.0f), const glm::vec4 &color=glm::vec4(1.0f))
std::vector< Entity > GetEntities()
glm::mat4 GetWorldTransform(Entity entity) const
static void Render(Scene &scene, const glm::mat4 &viewProjection, const glm::vec3 &cameraPosition=glm::vec3(0.0f), bool rebuildShadowMaps=true)
static const FramebufferSpecification & GetGraphicsSettings()
static void SetGraphicsSettings(const FramebufferSpecification &settings)
static const RendererStatistics & GetStatistics()
static std::shared_ptr< Shader > Create(const std::string &vertexSource, const std::string &fragmentSource)
std::shared_ptr< AnimationAsset > Animation