Line data Source code
1 : /**
2 : * @file renderlights.cpp
3 : * @brief render lights to deferred buffers
4 : *
5 : * light entities and sunlight in the game is rendered to deferred buffers
6 : * "g-buffers" which are used to compose a scene
7 : * lights are cached using a shadow map to allow rendering less than once per
8 : * frame, improving performance and light count allowed
9 : */
10 : #include "../libprimis-headers/cube.h"
11 : #include "../../shared/geomexts.h"
12 : #include "../../shared/glemu.h"
13 : #include "../../shared/glexts.h"
14 :
15 : #include "aa.h"
16 : #include "ao.h"
17 : #include "csm.h"
18 : #include "hdr.h"
19 : #include "lightsphere.h"
20 : #include "octarender.h"
21 : #include "postfx.h"
22 : #include "radiancehints.h"
23 : #include "rendergl.h"
24 : #include "renderlights.h"
25 : #include "rendermodel.h"
26 : #include "rendersky.h"
27 : #include "rendertimers.h"
28 : #include "renderva.h"
29 : #include "renderwindow.h"
30 : #include "shader.h"
31 : #include "shaderparam.h"
32 : #include "stain.h"
33 : #include "texture.h"
34 :
35 : #include "interface/control.h"
36 : #include "interface/console.h"
37 :
38 : #include "world/dynlight.h"
39 : #include "world/light.h"
40 : #include "world/material.h"
41 : #include "world/octaedit.h"
42 : #include "world/octaworld.h"
43 : #include "world/world.h"
44 :
45 : int vieww = -1,
46 : viewh = -1;
47 :
48 : int gw = -1,
49 : gh = -1;
50 :
51 : GBuffer gbuf;
52 :
53 : int hdrclear = 0;
54 :
55 : int spotlights = 0,
56 : volumetriclights = 0,
57 : nospeclights = 0;
58 : std::vector<vec2> msaapositions;
59 :
60 : //`g`-buffer `scale`
61 0 : static VARFP(gscale, 25, 100, 100, gbuf.cleanupgbuffer()); //size of g buffer, approximately correlates to g buffer linear dimensions
62 0 : static VARFP(gscalecubic, 0, 0, 1, gbuf.cleanupgbuffer()); //g-buffer scale cubic: use cubic interpolation for g buffer upscaling to screen output
63 0 : static VARFP(gscalenearest, 0, 0, 1, gbuf.cleanupgbuffer()); //g buffer nearest neighbor interpolation
64 :
65 : matrix4 worldmatrix, screenmatrix;
66 :
67 : static std::array<Shader *, 2> bilateralshader = { nullptr, nullptr };
68 :
69 0 : static Shader *loadbilateralshader(int pass)
70 : {
71 0 : if(!aobilateral)
72 : {
73 0 : return nullshader;
74 : }
75 0 : std::string opts;
76 0 : bool linear = aoreducedepth && (aoreduce || aoreducedepth > 1),
77 0 : upscale = aoreduce && aobilateralupscale,
78 0 : reduce = aoreduce && (upscale || (!linear && !aopackdepth));
79 0 : if(reduce)
80 : {
81 0 : opts.push_back('r');
82 0 : opts.push_back('0' + aoreduce);
83 : }
84 0 : if(upscale)
85 : {
86 0 : opts.push_back('u');
87 : }
88 0 : else if(linear)
89 : {
90 0 : opts.push_back('l');
91 :
92 : }
93 0 : if(aopackdepth)
94 : {
95 0 : opts.push_back('p');
96 : }
97 :
98 0 : DEF_FORMAT_STRING(name, "bilateral%c%s%d", 'x' + pass, opts.c_str(), aobilateral);
99 0 : return generateshader(name, "bilateralshader \"%s\" %d %d", opts.c_str(), aobilateral, reduce ? aoreduce : 0);
100 0 : }
101 :
102 0 : void loadbilateralshaders()
103 : {
104 0 : for(int k = 0; k < 2; ++k)
105 : {
106 0 : bilateralshader[k] = loadbilateralshader(k);
107 : }
108 0 : }
109 :
110 0 : void clearbilateralshaders()
111 : {
112 0 : bilateralshader.fill(nullptr);
113 0 : }
114 :
115 0 : static void setbilateralparams(int radius, float depth)
116 : {
117 0 : float sigma = blursigma*2*radius;
118 0 : LOCALPARAMF(bilateralparams, 1.0f/(M_LN2*2*sigma*sigma), 1.0f/(M_LN2*depth*depth));
119 0 : }
120 :
121 0 : void setbilateralshader(int radius, int pass, float depth)
122 : {
123 0 : bilateralshader[pass]->set();
124 0 : setbilateralparams(radius, depth);
125 0 : }
126 :
127 : //debug commands
128 : //for individual debug commands, see respective functions lower in the file
129 : VAR(debugfullscreen, 0, 0, 1); //used in header
130 :
131 0 : void GBuffer::cleanupscale()
132 : {
133 0 : for(GLuint &i : scalefbo)
134 : {
135 0 : if(i)
136 : {
137 0 : glDeleteFramebuffers(1, &i);
138 0 : i = 0;
139 : }
140 : }
141 0 : for(GLuint &i : scaletex)
142 : {
143 0 : if(i)
144 : {
145 0 : glDeleteTextures(1, &i);
146 0 : i = 0;
147 : }
148 : }
149 0 : scalew = scaleh = -1;
150 0 : }
151 :
152 0 : void GBuffer::setupscale(int sw, int sh, int w, int h)
153 : {
154 0 : scalew = w;
155 0 : scaleh = h;
156 :
157 0 : for(int i = 0; i < (gscalecubic ? 2 : 1); ++i)
158 : {
159 0 : if(!scaletex[i])
160 : {
161 0 : glGenTextures(1, &scaletex[i]);
162 : }
163 0 : if(!scalefbo[i])
164 : {
165 0 : glGenFramebuffers(1, &scalefbo[i]);
166 : }
167 0 : glBindFramebuffer(GL_FRAMEBUFFER, scalefbo[i]);
168 :
169 0 : createtexture(scaletex[i], sw, i ? h : sh, nullptr, 3, gscalecubic || !gscalenearest ? 1 : 0, GL_RGB, GL_TEXTURE_2D);
170 :
171 0 : glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, scaletex[i], 0);
172 0 : if(!i)
173 : {
174 0 : bindgdepth();
175 : }
176 0 : if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
177 : {
178 0 : fatal("failed allocating scale buffer!");
179 : }
180 : }
181 :
182 0 : glBindFramebuffer(GL_FRAMEBUFFER, 0);
183 :
184 0 : if(gscalecubic)
185 : {
186 0 : useshaderbyname("scalecubicx");
187 0 : useshaderbyname("scalecubicy");
188 : }
189 0 : }
190 :
191 0 : GLuint GBuffer::shouldscale() const
192 : {
193 0 : return scalefbo[0];
194 : }
195 :
196 0 : void GBuffer::doscale(GLuint outfbo) const
197 : {
198 0 : if(!scaletex[0])
199 : {
200 0 : return;
201 : }
202 0 : timer *scaletimer = begintimer("scaling");
203 0 : if(gscalecubic)
204 : {
205 0 : glBindFramebuffer(GL_FRAMEBUFFER, scalefbo[1]);
206 0 : glViewport(0, 0, gw, hudh());
207 0 : glBindTexture(GL_TEXTURE_2D, scaletex[0]);
208 0 : SETSHADER(scalecubicy);
209 0 : screenquad(1, 1);
210 0 : glBindFramebuffer(GL_FRAMEBUFFER, outfbo);
211 0 : glViewport(0, 0, hudw(), hudh());
212 0 : glBindTexture(GL_TEXTURE_2D, scaletex[1]);
213 0 : SETSHADER(scalecubicx);
214 0 : screenquad(1, 1);
215 : }
216 : else
217 : {
218 0 : glBindFramebuffer(GL_FRAMEBUFFER, outfbo);
219 0 : glViewport(0, 0, hudw(), hudh());
220 0 : glBindTexture(GL_TEXTURE_2D, scaletex[0]);
221 0 : SETSHADER(scalelinear);
222 0 : screenquad(1, 1);
223 : }
224 :
225 0 : endtimer(scaletimer);
226 : }
227 :
228 0 : VARFP(glineardepth, 0, 0, 3, initwarning("g-buffer setup", Init_Load, Change_Shaders)); // g-buffer linear depth buffer
229 : VAR(gdepthformat, 1, 0, 0); // g-buffer depth buffer format
230 0 : VARF(gstencil, 0, 0, 1, initwarning("g-buffer setup", Init_Load, Change_Shaders)); // g-buffer stenciling
231 0 : VARF(gdepthstencil, 0, 2, 2, initwarning("g-buffer setup", Init_Load, Change_Shaders)); // g-buffer depth buffer stenciling
232 : VAR(ghasstencil, 1, 0, 0); // g buffer has stencil
233 0 : static VARFP(msaa, 0, 0, 16, initwarning("MSAA setup", Init_Load, Change_Shaders)); // multi-sample antialiasing
234 0 : static VARF(msaadepthstencil, 0, 2, 2, initwarning("MSAA setup", Init_Load, Change_Shaders)); // multi-sample antialiasing depth buffer stenciling
235 0 : static VARF(msaastencil, 0, 0, 1, initwarning("MSAA setup", Init_Load, Change_Shaders)); // multi-sample antialiasing stenciling
236 0 : VARF(msaaedgedetect, 0, 1, 1, gbuf.cleanupgbuffer()); // multi-sample antialiasing edge detection
237 0 : VARFP(msaalineardepth, -1, -1, 3, initwarning("MSAA setup", Init_Load, Change_Shaders)); // multi-sample antialiasing linear depth
238 0 : VARFP(msaatonemap, 0, 0, 1, gbuf.cleanupgbuffer()); // multi-sample antialiasing tone mapping
239 : static VAR(msaamaxsamples, 1, 0, 0); // multi-sample antialiasing maximum samples
240 : static VAR(msaamaxdepthtexsamples, 1, 0, 0); // multi-sample antialiasing maximum depth buffer texture sample count
241 : static VAR(msaamaxcolortexsamples, 1, 0, 0); // multi-sample antialiasing maximum color buffer texture sample count
242 : static VAR(msaaminsamples, 1, 0, 0); // multi-sample antialiasing minimum sample count
243 : VAR(msaasamples, 1, 0, 0); // multi-sample antialiasing sampling
244 : VAR(msaalight, 1, 0, 0); // multi-sample antialias lights
245 0 : static VARF(msaapreserve, -1, 0, 1, initwarning("MSAA setup", Init_Load, Change_Shaders)); // preserve multi-sample antialiasing
246 :
247 0 : static void checkmsaasamples()
248 : {
249 : GLuint tex;
250 0 : glGenTextures(1, &tex);
251 0 : glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, tex);
252 :
253 : GLint samples;
254 0 : glTexImage2DMultisample_(GL_TEXTURE_2D_MULTISAMPLE, msaaminsamples, GL_RGBA8, 1, 1, GL_TRUE);
255 0 : glGetTexLevelParameteriv(GL_TEXTURE_2D_MULTISAMPLE, 0, GL_TEXTURE_SAMPLES, &samples);
256 0 : msaasamples = samples;
257 :
258 0 : glDeleteTextures(1, &tex);
259 0 : }
260 :
261 0 : void initgbuffer()
262 : {
263 0 : msaamaxsamples = msaamaxdepthtexsamples = msaamaxcolortexsamples = msaaminsamples = msaasamples = msaalight = 0;
264 0 : msaapositions.clear();
265 :
266 : GLint val;
267 0 : glGetIntegerv(GL_MAX_SAMPLES, &val);
268 0 : msaamaxsamples = val;
269 0 : glGetIntegerv(GL_MAX_DEPTH_TEXTURE_SAMPLES, &val);
270 0 : msaamaxdepthtexsamples = val;
271 0 : glGetIntegerv(GL_MAX_COLOR_TEXTURE_SAMPLES, &val);
272 0 : msaamaxcolortexsamples = val;
273 :
274 0 : int maxsamples = std::min(msaamaxsamples, msaamaxcolortexsamples),
275 0 : reqsamples = std::min(msaa, maxsamples);
276 0 : if(reqsamples >= 2)
277 : {
278 0 : msaaminsamples = 2;
279 0 : while(msaaminsamples*2 <= reqsamples)
280 : {
281 0 : msaaminsamples *= 2;
282 : }
283 : }
284 :
285 0 : int lineardepth = glineardepth;
286 0 : if(msaaminsamples)
287 : {
288 0 : if(msaamaxdepthtexsamples < msaaminsamples)
289 : {
290 0 : if(msaalineardepth > 0)
291 : {
292 0 : lineardepth = msaalineardepth;
293 : }
294 0 : else if(!lineardepth)
295 : {
296 0 : lineardepth = 1;
297 : }
298 : }
299 0 : else if(msaalineardepth >= 0)
300 : {
301 0 : lineardepth = msaalineardepth;
302 : }
303 : }
304 0 : gdepthformat = lineardepth;
305 0 : if(msaaminsamples)
306 : {
307 0 : ghasstencil = (msaadepthstencil > 1 || (msaadepthstencil && gdepthformat)) ? 2 : (msaastencil ? 1 : 0);
308 0 : checkmsaasamples();
309 0 : if(msaapreserve >= 0)
310 : {
311 0 : msaalight = 3;
312 : }
313 : }
314 : else
315 : {
316 0 : ghasstencil = (gdepthstencil > 1 || (gdepthstencil && gdepthformat)) ? 2 : (gstencil ? 1 : 0);
317 : }
318 0 : initao();
319 0 : }
320 :
321 0 : static VARF(forcepacknorm, 0, 0, 1, initwarning("g-buffer setup", Init_Load, Change_Shaders));
322 :
323 : static bool useavatarmask();
324 :
325 1 : bool usepacknorm()
326 : {
327 1 : return forcepacknorm || msaasamples || !useavatarmask();
328 : }
329 :
330 0 : void maskgbuffer(const char *mask)
331 : {
332 : std::array<GLenum, 4> drawbufs;
333 0 : int numbufs = 0;
334 0 : while(*mask)
335 : {
336 0 : switch(*mask++)
337 : {
338 0 : case 'c':
339 : {
340 0 : drawbufs[numbufs++] = GL_COLOR_ATTACHMENT0;
341 0 : break;
342 : }
343 0 : case 'n':
344 : {
345 0 : drawbufs[numbufs++] = GL_COLOR_ATTACHMENT1;
346 0 : break;
347 : }
348 0 : case 'd':
349 : {
350 0 : if(gdepthformat)
351 : {
352 0 : drawbufs[numbufs++] = GL_COLOR_ATTACHMENT3;
353 : }
354 0 : break;
355 : }
356 0 : case 'g':
357 : {
358 0 : drawbufs[numbufs++] = GL_COLOR_ATTACHMENT2;
359 0 : break;
360 : }
361 : }
362 : }
363 0 : glDrawBuffers(numbufs, drawbufs.data());
364 0 : }
365 :
366 0 : void GBuffer::cleanupmsbuffer()
367 : {
368 0 : if(msfbo) { glDeleteFramebuffers(1, &msfbo); msfbo = 0; }
369 0 : if(msdepthtex) { glDeleteTextures(1, &msdepthtex); msdepthtex = 0; }
370 0 : if(mscolortex) { glDeleteTextures(1, &mscolortex); mscolortex = 0; }
371 0 : if(msnormaltex) { glDeleteTextures(1, &msnormaltex); msnormaltex = 0; }
372 0 : if(msglowtex) { glDeleteTextures(1, &msglowtex); msglowtex = 0; }
373 0 : if(msstencilrb) { glDeleteRenderbuffers(1, &msstencilrb); msstencilrb = 0; }
374 0 : if(msdepthrb) { glDeleteRenderbuffers(1, &msdepthrb); msdepthrb = 0; }
375 0 : if(mshdrfbo) { glDeleteFramebuffers(1, &mshdrfbo); mshdrfbo = 0; }
376 0 : if(mshdrtex) { glDeleteTextures(1, &mshdrtex); mshdrtex = 0; }
377 0 : if(msrefractfbo) { glDeleteFramebuffers(1, &msrefractfbo); msrefractfbo = 0; }
378 0 : if(msrefracttex) { glDeleteTextures(1, &msrefracttex); msrefracttex = 0; }
379 0 : }
380 :
381 0 : void GBuffer::bindmsdepth() const
382 : {
383 0 : if(gdepthformat)
384 : {
385 0 : glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, msdepthrb);
386 0 : if(ghasstencil > 1)
387 : {
388 0 : glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, msdepthrb);
389 : }
390 0 : else if(msaalight && ghasstencil)
391 : {
392 0 : glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, msstencilrb);
393 : }
394 : }
395 : else
396 : {
397 0 : glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D_MULTISAMPLE, msdepthtex, 0);
398 0 : if(ghasstencil > 1)
399 : {
400 0 : glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D_MULTISAMPLE, msdepthtex, 0);
401 : }
402 0 : else if(msaalight && ghasstencil)
403 : {
404 0 : glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, msstencilrb);
405 : }
406 : }
407 0 : }
408 :
409 0 : void GBuffer::setupmsbuffer(int w, int h)
410 : {
411 0 : if(!msfbo)
412 : {
413 0 : glGenFramebuffers(1, &msfbo);
414 : }
415 :
416 0 : glBindFramebuffer(GL_FRAMEBUFFER, msfbo);
417 :
418 0 : stencilformat = ghasstencil > 1 ? GL_DEPTH24_STENCIL8 : (ghasstencil ? GL_STENCIL_INDEX8 : 0);
419 :
420 0 : if(gdepthformat)
421 : {
422 0 : if(!msdepthrb)
423 : {
424 0 : glGenRenderbuffers(1, &msdepthrb);
425 : }
426 0 : glBindRenderbuffer(GL_RENDERBUFFER, msdepthrb);
427 0 : glRenderbufferStorageMultisample_(GL_RENDERBUFFER, msaasamples, ghasstencil > 1 ? stencilformat : GL_DEPTH_COMPONENT24, w, h);
428 0 : glBindRenderbuffer(GL_RENDERBUFFER, 0);
429 : }
430 0 : if(msaalight && ghasstencil == 1)
431 : {
432 0 : if(!msstencilrb)
433 : {
434 0 : glGenRenderbuffers(1, &msstencilrb);
435 : }
436 0 : glBindRenderbuffer(GL_RENDERBUFFER, msstencilrb);
437 0 : glRenderbufferStorageMultisample_(GL_RENDERBUFFER, msaasamples, GL_STENCIL_INDEX8, w, h);
438 0 : glBindRenderbuffer(GL_RENDERBUFFER, 0);
439 : }
440 :
441 0 : if(!msdepthtex)
442 : {
443 0 : glGenTextures(1, &msdepthtex);
444 : }
445 0 : if(!mscolortex)
446 : {
447 0 : glGenTextures(1, &mscolortex);
448 : }
449 0 : if(!msnormaltex)
450 : {
451 0 : glGenTextures(1, &msnormaltex);
452 : }
453 :
454 0 : maskgbuffer(msaalight ? "cndg" : "cnd");
455 :
456 : static const GLenum depthformats[] = { GL_RGBA8, GL_R16F, GL_R32F };
457 0 : GLenum depthformat = gdepthformat ? depthformats[gdepthformat-1] : (ghasstencil > 1 ? stencilformat : GL_DEPTH_COMPONENT24);
458 0 : glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, msdepthtex);
459 0 : glTexImage2DMultisample_(GL_TEXTURE_2D_MULTISAMPLE, msaasamples, depthformat, w, h, GL_TRUE);
460 :
461 0 : glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, mscolortex);
462 0 : glTexImage2DMultisample_(GL_TEXTURE_2D_MULTISAMPLE, msaasamples, GL_RGBA8, w, h, GL_TRUE);
463 0 : glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, msnormaltex);
464 0 : glTexImage2DMultisample_(GL_TEXTURE_2D_MULTISAMPLE, msaasamples, GL_RGBA8, w, h, GL_TRUE);
465 0 : if(msaalight)
466 : {
467 0 : if(!msglowtex)
468 : {
469 0 : glGenTextures(1, &msglowtex);
470 : }
471 0 : glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, msglowtex);
472 0 : glTexImage2DMultisample_(GL_TEXTURE_2D_MULTISAMPLE, msaasamples, hdrformat, w, h, GL_TRUE);
473 : }
474 :
475 0 : bindmsdepth();
476 0 : glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, mscolortex, 0);
477 0 : glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D_MULTISAMPLE, msnormaltex, 0);
478 0 : if(msaalight)
479 : {
480 0 : glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D_MULTISAMPLE, msglowtex, 0);
481 : }
482 0 : if(gdepthformat)
483 : {
484 0 : glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3, GL_TEXTURE_2D_MULTISAMPLE, msdepthtex, 0);
485 : }
486 :
487 0 : if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
488 : {
489 0 : if(msaalight)
490 : {
491 0 : glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, msglowtex);
492 0 : glTexImage2DMultisample_(GL_TEXTURE_2D_MULTISAMPLE, msaasamples, GL_RGBA8, w, h, GL_TRUE);
493 0 : glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D_MULTISAMPLE, msglowtex, 0);
494 0 : if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
495 : {
496 0 : fatal("failed allocating MSAA g-buffer!");
497 : }
498 : }
499 : else
500 : {
501 0 : fatal("failed allocating MSAA g-buffer!");
502 : }
503 : }
504 :
505 0 : glClearColor(0, 0, 0, 0);
506 0 : glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | (ghasstencil ? GL_STENCIL_BUFFER_BIT : 0));
507 :
508 0 : msaapositions.clear();
509 0 : for(int i = 0; i < msaasamples; ++i)
510 : {
511 : GLfloat vals[2];
512 0 : glGetMultisamplefv(GL_SAMPLE_POSITION, i, vals);
513 0 : msaapositions.emplace_back(vec2(vals[0], vals[1]));
514 : }
515 :
516 0 : if(msaalight)
517 : {
518 0 : if(!mshdrtex)
519 : {
520 0 : glGenTextures(1, &mshdrtex);
521 : }
522 0 : if(!mshdrfbo)
523 : {
524 0 : glGenFramebuffers(1, &mshdrfbo);
525 : }
526 0 : glBindFramebuffer(GL_FRAMEBUFFER, mshdrfbo);
527 0 : bindmsdepth();
528 0 : hdrformat = 0;
529 0 : for(int prec = hdrprec; prec >= 0; prec--)
530 : {
531 0 : GLenum format = gethdrformat(prec);
532 0 : glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, mshdrtex);
533 0 : glGetError();
534 0 : glTexImage2DMultisample_(GL_TEXTURE_2D_MULTISAMPLE, msaasamples, format, w, h, GL_TRUE);
535 0 : if(glGetError() == GL_NO_ERROR)
536 : {
537 0 : glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, mshdrtex, 0);
538 0 : if(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE)
539 : {
540 0 : hdrformat = format;
541 0 : break;
542 : }
543 : }
544 : }
545 :
546 0 : if(!hdrformat || glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
547 : {
548 0 : fatal("failed allocating MSAA HDR buffer!");
549 : }
550 0 : if(!msrefracttex)
551 : {
552 0 : glGenTextures(1, &msrefracttex);
553 : }
554 0 : if(!msrefractfbo)
555 : {
556 0 : glGenFramebuffers(1, &msrefractfbo);
557 : }
558 0 : glBindFramebuffer(GL_FRAMEBUFFER, msrefractfbo);
559 :
560 0 : glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, msrefracttex);
561 0 : glTexImage2DMultisample_(GL_TEXTURE_2D_MULTISAMPLE, msaasamples, GL_RGB, w, h, GL_TRUE);
562 :
563 0 : glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, msrefracttex, 0);
564 0 : bindmsdepth();
565 :
566 0 : if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
567 : {
568 0 : fatal("failed allocating MSAA refraction buffer!");
569 : }
570 : }
571 :
572 0 : glBindFramebuffer(GL_FRAMEBUFFER, 0);
573 :
574 0 : useshaderbyname("msaaedgedetect");
575 0 : useshaderbyname("msaaresolve");
576 0 : useshaderbyname("msaareducew");
577 0 : useshaderbyname("msaareduce");
578 0 : if(!msaalight)
579 : {
580 0 : useshaderbyname("msaaresolvedepth");
581 : }
582 0 : if(msaalight > 1 && msaatonemap)
583 : {
584 0 : useshaderbyname("msaatonemap");
585 0 : if(msaalight > 2)
586 : {
587 0 : useshaderbyname("msaatonemapsample");
588 : }
589 : }
590 0 : }
591 :
592 0 : void GBuffer::bindgdepth() const
593 : {
594 0 : if(gdepthformat || msaalight)
595 : {
596 0 : glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, gdepthrb);
597 0 : if(ghasstencil > 1)
598 : {
599 0 : glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, gdepthrb);
600 : }
601 0 : else if(!msaalight || ghasstencil)
602 : {
603 0 : glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, gstencilrb);
604 : }
605 : }
606 : else
607 : {
608 0 : glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_RECTANGLE, gdepthtex, 0);
609 0 : if(ghasstencil > 1)
610 : {
611 0 : glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_RECTANGLE, gdepthtex, 0);
612 : }
613 0 : else if(ghasstencil)
614 : {
615 0 : glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, gstencilrb);
616 : }
617 : }
618 0 : }
619 :
620 0 : void GBuffer::setupgbuffer()
621 : {
622 : //start with screen resolution
623 0 : int sw = renderw(),
624 0 : sh = renderh();
625 : //scale sw and sh if gscale (g-buffer scale) is not 100%
626 0 : if(gscale != 100)
627 : {
628 0 : sw = std::max((renderw()*gscale + 99)/100, 1);
629 0 : sh = std::max((renderh()*gscale + 99)/100, 1);
630 : }
631 :
632 0 : if(gw == sw && gh == sh && ((sw >= hudw() && sh >= hudh() && !scalefbo[0]) || (scalew == hudw() && scaleh == hudh())))
633 : {
634 0 : return;
635 : }
636 : //clean up various buffers & info with them
637 0 : cleanupscale();
638 0 : cleanupbloom();
639 0 : cleanupao();
640 0 : cleanupvolumetric();
641 0 : cleanupaa();
642 0 : cleanuppostfx();
643 :
644 0 : gw = sw;
645 0 : gh = sh;
646 :
647 0 : hdrformat = gethdrformat(hdrprec);
648 0 : stencilformat = ghasstencil > 1 ? GL_DEPTH24_STENCIL8 : (ghasstencil ? GL_STENCIL_INDEX8 : 0);
649 :
650 0 : if(msaasamples)
651 : {
652 0 : setupmsbuffer(gw, gh);
653 : }
654 0 : hdrfloat = floatformat(hdrformat);
655 0 : hdrclear = 3;
656 0 : gdepthinit = false;
657 :
658 0 : if(gdepthformat || msaalight)
659 : {
660 0 : if(!gdepthrb)
661 : {
662 0 : glGenRenderbuffers(1, &gdepthrb);
663 : }
664 0 : glBindRenderbuffer(GL_RENDERBUFFER, gdepthrb);
665 0 : glRenderbufferStorage(GL_RENDERBUFFER, ghasstencil > 1 ? stencilformat : GL_DEPTH_COMPONENT24, gw, gh);
666 0 : glBindRenderbuffer(GL_RENDERBUFFER, 0);
667 : }
668 0 : if(!msaalight && ghasstencil == 1)
669 : {
670 0 : if(!gstencilrb)
671 : {
672 0 : glGenRenderbuffers(1, &gstencilrb);
673 : }
674 0 : glBindRenderbuffer(GL_RENDERBUFFER, gstencilrb);
675 0 : glRenderbufferStorage(GL_RENDERBUFFER, GL_STENCIL_INDEX8, gw, gh);
676 0 : glBindRenderbuffer(GL_RENDERBUFFER, 0);
677 : }
678 :
679 0 : if(!msaalight)
680 : {
681 0 : if(!gdepthtex)
682 : {
683 0 : glGenTextures(1, &gdepthtex);
684 : }
685 0 : if(!gcolortex)
686 : {
687 0 : glGenTextures(1, &gcolortex);
688 : }
689 0 : if(!gnormaltex)
690 : {
691 0 : glGenTextures(1, &gnormaltex);
692 : }
693 0 : if(!gglowtex)
694 : {
695 0 : glGenTextures(1, &gglowtex);
696 : }
697 0 : if(!gfbo)
698 : {
699 0 : glGenFramebuffers(1, &gfbo);
700 : }
701 :
702 0 : glBindFramebuffer(GL_FRAMEBUFFER, gfbo);
703 :
704 0 : maskgbuffer("cndg");
705 :
706 : static const GLenum depthformats[] = { GL_RGBA8, GL_R16F, GL_R32F };
707 0 : GLenum depthformat = gdepthformat ? depthformats[gdepthformat-1] : (ghasstencil > 1 ? stencilformat : GL_DEPTH_COMPONENT24);
708 0 : createtexture(gdepthtex, gw, gh, nullptr, 3, 0, depthformat, GL_TEXTURE_RECTANGLE);
709 :
710 0 : createtexture(gcolortex, gw, gh, nullptr, 3, 0, GL_RGBA8, GL_TEXTURE_RECTANGLE);
711 0 : createtexture(gnormaltex, gw, gh, nullptr, 3, 0, GL_RGBA8, GL_TEXTURE_RECTANGLE);
712 0 : createtexture(gglowtex, gw, gh, nullptr, 3, 0, hdrformat, GL_TEXTURE_RECTANGLE);
713 :
714 0 : bindgdepth();
715 0 : glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_RECTANGLE, gcolortex, 0);
716 0 : glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_RECTANGLE, gnormaltex, 0);
717 0 : glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_RECTANGLE, gglowtex, 0);
718 0 : if(gdepthformat)
719 : {
720 0 : glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3, GL_TEXTURE_RECTANGLE, gdepthtex, 0);
721 : }
722 0 : if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
723 : {
724 0 : createtexture(gglowtex, gw, gh, nullptr, 3, 0, GL_RGBA8, GL_TEXTURE_RECTANGLE);
725 0 : glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_RECTANGLE, gglowtex, 0);
726 0 : if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
727 : {
728 0 : fatal("failed allocating g-buffer!");
729 : }
730 : }
731 :
732 0 : glClearColor(0, 0, 0, 0);
733 0 : glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | (ghasstencil ? GL_STENCIL_BUFFER_BIT : 0));
734 : }
735 :
736 0 : if(!hdrtex)
737 : {
738 0 : glGenTextures(1, &hdrtex);
739 : }
740 0 : if(!hdrfbo)
741 : {
742 0 : glGenFramebuffers(1, &hdrfbo);
743 : }
744 :
745 0 : glBindFramebuffer(GL_FRAMEBUFFER, hdrfbo);
746 :
747 0 : createtexture(hdrtex, gw, gh, nullptr, 3, 1, hdrformat, GL_TEXTURE_RECTANGLE);
748 :
749 0 : glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_RECTANGLE, hdrtex, 0);
750 0 : bindgdepth();
751 :
752 0 : if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
753 : {
754 0 : fatal("failed allocating HDR buffer!");
755 : }
756 :
757 0 : if(!msaalight || (msaalight > 2 && msaatonemap && msaatonemapblit))
758 : {
759 0 : if(!refracttex)
760 : {
761 0 : glGenTextures(1, &refracttex);
762 : }
763 0 : if(!refractfbo)
764 : {
765 0 : glGenFramebuffers(1, &refractfbo);
766 : }
767 0 : glBindFramebuffer(GL_FRAMEBUFFER, refractfbo);
768 0 : createtexture(refracttex, gw, gh, nullptr, 3, 0, GL_RGB, GL_TEXTURE_RECTANGLE);
769 :
770 0 : glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_RECTANGLE, refracttex, 0);
771 0 : bindgdepth();
772 :
773 0 : if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
774 : {
775 0 : fatal("failed allocating refraction buffer!");
776 : }
777 : }
778 :
779 0 : glBindFramebuffer(GL_FRAMEBUFFER, 0);
780 :
781 0 : if(gw < hudw() || gh < hudh())
782 : {
783 0 : setupscale(gw, gh, hudw(), hudh());
784 : }
785 : }
786 :
787 0 : void GBuffer::cleanupgbuffer()
788 : {
789 0 : if(gfbo) { glDeleteFramebuffers(1, &gfbo); gfbo = 0; }
790 0 : if(gdepthtex) { glDeleteTextures(1, &gdepthtex); gdepthtex = 0; }
791 0 : if(gcolortex) { glDeleteTextures(1, &gcolortex); gcolortex = 0; }
792 0 : if(gnormaltex) { glDeleteTextures(1, &gnormaltex); gnormaltex = 0; }
793 0 : if(gglowtex) { glDeleteTextures(1, &gglowtex); gglowtex = 0; }
794 0 : if(gstencilrb) { glDeleteRenderbuffers(1, &gstencilrb); gstencilrb = 0; }
795 0 : if(gdepthrb) { glDeleteRenderbuffers(1, &gdepthrb); gdepthrb = 0; }
796 0 : if(hdrfbo) { glDeleteFramebuffers(1, &hdrfbo); hdrfbo = 0; }
797 0 : if(hdrtex) { glDeleteTextures(1, &hdrtex); hdrtex = 0; }
798 0 : if(refractfbo) { glDeleteFramebuffers(1, &refractfbo); refractfbo = 0; }
799 0 : if(refracttex) { glDeleteTextures(1, &refracttex); refracttex = 0; }
800 0 : gw = gh = -1;
801 0 : cleanupscale();
802 0 : cleanupmsbuffer();
803 0 : cleardeferredlightshaders();
804 0 : }
805 :
806 0 : void GBuffer::resolvemsaadepth(int w, int h) const
807 : {
808 0 : if(!msaasamples || msaalight)
809 : {
810 0 : return;
811 : }
812 :
813 0 : timer *resolvetimer = drawtex ? nullptr : begintimer("msaa depth resolve");
814 :
815 0 : if(gdepthformat)
816 : {
817 0 : glBindFramebuffer(GL_FRAMEBUFFER, gfbo);
818 0 : glViewport(0, 0, w, h);
819 0 : maskgbuffer("d");
820 :
821 0 : if(ghasstencil)
822 : {
823 0 : glStencilFunc(GL_ALWAYS, 0, ~0);
824 0 : glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
825 0 : glEnable(GL_STENCIL_TEST);
826 : }
827 0 : glDepthFunc(GL_ALWAYS);
828 0 : SETSHADER(msaaresolvedepth);
829 :
830 :
831 0 : glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, msdepthtex);
832 0 : screenquad();
833 0 : maskgbuffer("cnd");
834 0 : if(ghasstencil)
835 : {
836 0 : glDisable(GL_STENCIL_TEST);
837 : }
838 0 : glDepthFunc(GL_LESS);
839 : }
840 :
841 0 : endtimer(resolvetimer);
842 : }
843 :
844 0 : void GBuffer::resolvemsaacolor(int w, int h)
845 : {
846 0 : if(!msaalight)
847 : {
848 0 : return;
849 : }
850 0 : timer *resolvetimer = drawtex ? nullptr : begintimer("msaa resolve");
851 :
852 0 : glBindFramebuffer(GL_READ_FRAMEBUFFER, mshdrfbo);
853 0 : glBindFramebuffer(GL_DRAW_FRAMEBUFFER, hdrfbo);
854 0 : glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_COLOR_BUFFER_BIT, GL_NEAREST);
855 :
856 0 : glBindFramebuffer(GL_FRAMEBUFFER, hdrfbo);
857 :
858 0 : endtimer(resolvetimer);
859 : }
860 :
861 : float ldrscale = 1.0f;
862 :
863 0 : float ldrscaleb()
864 : {
865 0 : return ldrscale/255;
866 : }
867 :
868 : static VAR(debugdepth, 0, 0, 1); //toggles showing depth buffer onscreen
869 :
870 0 : void GBuffer::viewdepth() const
871 : {
872 0 : int w = (debugfullscreen) ? hudw() : std::min(hudw(), hudh())/2, //if debugfullscreen, set to hudw/hudh size; if not, do small size
873 0 : h = (debugfullscreen) ? hudh() : (w*hudh())/hudw();
874 0 : SETSHADER(hudrect);
875 0 : gle::colorf(1, 1, 1);
876 0 : glBindTexture(GL_TEXTURE_RECTANGLE, gdepthtex);
877 0 : debugquad(0, 0, w, h, 0, 0, gw, gh);
878 0 : }
879 :
880 : static VAR(debugstencil, 0, 0, 0xFF);
881 :
882 0 : void viewstencil()
883 : {
884 0 : if(!ghasstencil || !hdrfbo)
885 : {
886 0 : return;
887 : }
888 0 : glBindFramebuffer(GL_FRAMEBUFFER, hdrfbo);
889 0 : glViewport(0, 0, gw, gh);
890 :
891 0 : glClearColor(0, 0, 0, 0);
892 0 : glClear(GL_COLOR_BUFFER_BIT);
893 :
894 0 : glStencilFunc(GL_NOTEQUAL, 0, debugstencil);
895 0 : glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
896 0 : glEnable(GL_STENCIL_TEST);
897 0 : SETSHADER(hudnotexture);
898 0 : gle::colorf(1, 1, 1);
899 0 : debugquad(0, 0, hudw(), hudh(), 0, 0, gw, gh);
900 0 : glDisable(GL_STENCIL_TEST);
901 :
902 0 : glBindFramebuffer(GL_FRAMEBUFFER, 0);
903 0 : glViewport(0, 0, hudw(), hudh());
904 :
905 0 : int w = debugfullscreen ? hudw() : std::min(hudw(), hudh())/2, //if debugfullscreen, set to hudw/hudh size; if not, do small size
906 0 : h = debugfullscreen ? hudh() : (w*hudh())/hudw();
907 0 : SETSHADER(hudrect);
908 0 : gle::colorf(1, 1, 1);
909 0 : glBindTexture(GL_TEXTURE_RECTANGLE, hdrtex);
910 0 : debugquad(0, 0, w, h, 0, 0, gw, gh);
911 : }
912 :
913 : static VAR(debugrefract, 0, 0, 1);
914 :
915 0 : void GBuffer::viewrefract()
916 : {
917 0 : int w = debugfullscreen ? hudw() : std::min(hudw(), hudh())/2, //if debugfullscreen, set to hudw/hudh size; if not, do small size
918 0 : h = debugfullscreen ? hudh() : (w*hudh())/hudw();
919 0 : SETSHADER(hudrect);
920 0 : gle::colorf(1, 1, 1);
921 0 : glBindTexture(GL_TEXTURE_RECTANGLE, refracttex);
922 0 : debugquad(0, 0, w, h, 0, 0, gw, gh);
923 0 : }
924 :
925 : PackNode shadowatlaspacker(0, 0, shadowatlassize, shadowatlassize);
926 :
927 : VAR(smminradius, 0, 16, 10000);
928 :
929 : class lightinfo final
930 : {
931 : public:
932 : int ent, shadowmap, flags;
933 : vec o, color;
934 : float radius, dist;
935 : vec dir, spotx, spoty;
936 : int spot;
937 : float sx1, sy1, sx2, sy2, sz1, sz2;
938 : occludequery *query;
939 :
940 : lightinfo() : query(nullptr)
941 : {
942 : }
943 :
944 0 : lightinfo(const vec &o, const vec &color, float radius, int flags = 0, const vec &dir = vec(0, 0, 0), int spot = 0)
945 0 : : ent(-1), shadowmap(-1), flags(flags),
946 0 : o(o), color(color), radius(radius), dist(camera1->o.dist(o)),
947 0 : dir(dir), spot(spot), query(nullptr)
948 : {
949 0 : if(spot > 0)
950 : {
951 0 : calcspot();
952 : }
953 0 : calcscissor();
954 0 : }
955 :
956 0 : lightinfo(int i, const extentity &e)
957 0 : : ent(i), shadowmap(-1), flags(e.attr5),
958 0 : o(e.o), color(vec(e.attr2, e.attr3, e.attr4).max(0)), radius(e.attr1), dist(camera1->o.dist(e.o)),
959 0 : dir(0, 0, 0), spot(0), query(nullptr)
960 : {
961 0 : if(e.attached && e.attached->type == EngineEnt_Spotlight)
962 : {
963 0 : dir = vec(e.attached->o).sub(e.o).normalize();
964 0 : spot = std::clamp(static_cast<int>(e.attached->attr1), 1, 89);
965 0 : calcspot();
966 : }
967 0 : calcscissor();
968 0 : }
969 :
970 : /**
971 : * @brief Returns whether this lightinfo should have shadows enabled.
972 : *
973 : * Checks the flags field against the LightEnt_NoShadow bitfield. Also checks
974 : * if the radius of the light is below the shadow map minimum radius. If
975 : * the light has noshadow enabled or the radius of the light is too low,
976 : * returns true.
977 : *
978 : * @return true if noshadow should be enabled.
979 : */
980 0 : bool noshadow() const
981 : {
982 0 : return flags&LightEnt_NoShadow || radius <= smminradius;
983 : }
984 :
985 : /**
986 : * @brief Returns whether this lightinfo has the specular flag set.
987 : *
988 : * Checks the flags field against the LightEnt_NoSpecular bitfield.
989 : *
990 : * @return true if the nospecular field is present, false otherwise
991 : */
992 0 : bool nospec() const
993 : {
994 0 : return (flags&LightEnt_NoSpecular) != 0;
995 : }
996 :
997 : /**
998 : * @brief Returns whether this lightinfo has the volumetric flag set.
999 : *
1000 : * Checks the flags field against the LightEnt_Volumetric bitfield.
1001 : *
1002 : * @return true if the volumetric field is present, false otherwise
1003 : */
1004 0 : bool volumetric() const
1005 : {
1006 0 : return (flags&LightEnt_Volumetric) != 0;
1007 : }
1008 :
1009 0 : void addscissor(float &dx1, float &dy1, float &dx2, float &dy2) const
1010 : {
1011 0 : dx1 = std::min(dx1, sx1);
1012 0 : dy1 = std::min(dy1, sy1);
1013 0 : dx2 = std::max(dx2, sx2);
1014 0 : dy2 = std::max(dy2, sy2);
1015 0 : }
1016 :
1017 0 : void addscissor(float &dx1, float &dy1, float &dx2, float &dy2, float &dz1, float &dz2) const
1018 : {
1019 0 : addscissor(dx1, dy1, dx2, dy2);
1020 0 : dz1 = std::min(dz1, sz1);
1021 0 : dz2 = std::max(dz2, sz2);
1022 0 : }
1023 :
1024 0 : bool validscissor() const
1025 : {
1026 0 : return sx1 < sx2 && sy1 < sy2 && sz1 < sz2;
1027 : }
1028 :
1029 0 : bool checkquery() const
1030 : {
1031 0 : return query && query->owner == this && occlusionengine.checkquery(query);
1032 : }
1033 :
1034 0 : void calcbb(vec &bbmin, vec &bbmax) const
1035 : {
1036 0 : if(spot > 0)
1037 : {
1038 0 : float spotscale = radius * tan360(spot);
1039 0 : vec up = vec(spotx).mul(spotscale).abs(),
1040 0 : right = vec(spoty).mul(spotscale).abs(),
1041 0 : center = vec(dir).mul(radius).add(o);
1042 0 : bbmin = bbmax = center;
1043 0 : bbmin.sub(up).sub(right);
1044 0 : bbmax.add(up).add(right);
1045 0 : bbmin.min(o);
1046 0 : bbmax.max(o);
1047 : }
1048 : else
1049 : {
1050 0 : bbmin = vec(o).sub(radius);
1051 0 : bbmax = vec(o).add(radius);
1052 : }
1053 0 : }
1054 :
1055 : private:
1056 0 : void calcspot()
1057 : {
1058 0 : quat orient(dir, vec(0, 0, dir.z < 0 ? -1 : 1));
1059 0 : spotx = orient.invertedrotate(vec(1, 0, 0));
1060 0 : spoty = orient.invertedrotate(vec(0, 1, 0));
1061 0 : }
1062 :
1063 0 : void calcscissor()
1064 : {
1065 0 : sx1 = sy1 = sz1 = -1;
1066 0 : sx2 = sy2 = sz2 = 1;
1067 0 : if(spot > 0)
1068 : {
1069 0 : calcspotscissor(o, radius, dir, spot, spotx, spoty, sx1, sy1, sx2, sy2, sz1, sz2);
1070 : }
1071 : else
1072 : {
1073 0 : calcspherescissor(o, radius, sx1, sy1, sx2, sy2, sz1, sz2);
1074 : }
1075 0 : }
1076 : };
1077 :
1078 : struct ShadowCacheKey final
1079 : {
1080 : vec o;
1081 : float radius;
1082 : vec dir;
1083 : int spot;
1084 :
1085 0 : bool operator==(const ShadowCacheKey &y) const
1086 : {
1087 0 : return o == y.o && radius == y.radius && dir == y.dir && spot == y.spot;
1088 : }
1089 :
1090 : ShadowCacheKey() {}
1091 0 : ShadowCacheKey(const lightinfo &l) : o(l.o), radius(l.radius), dir(l.dir), spot(l.spot) {}
1092 : };
1093 :
1094 : template <>
1095 : struct std::hash<ShadowCacheKey>
1096 : {
1097 0 : size_t operator()(const ShadowCacheKey &k) const
1098 : {
1099 : auto vechash = std::hash<vec>();
1100 0 : return vechash(k.o);
1101 : }
1102 : };
1103 :
1104 : struct shadowcacheval final
1105 : {
1106 : ushort x, y, size, sidemask;
1107 :
1108 :
1109 : static inline bool htcmp(const ShadowCacheKey &x, const ShadowCacheKey &y)
1110 : {
1111 : return x.o == y.o && x.radius == y.radius && x.dir == y.dir && x.spot == y.spot;
1112 : }
1113 :
1114 0 : shadowcacheval() {}
1115 0 : shadowcacheval(const ShadowMapInfo &sm) : x(sm.x), y(sm.y), size(sm.size), sidemask(sm.sidemask) {}
1116 : };
1117 :
1118 : class ShadowAtlas final
1119 : {
1120 : public:
1121 : GLuint fbo = 0;
1122 : std::unordered_map<ShadowCacheKey, shadowcacheval> cache;
1123 : bool full = false;
1124 :
1125 : void cleanup();
1126 : void view();
1127 : void setup();
1128 : void setcomparemode(); //will call one of setsm(non)comparemode()
1129 : void bind();
1130 :
1131 : private:
1132 : GLuint tex = 0;
1133 : GLenum target = GL_NONE;
1134 :
1135 : void setsmnoncomparemode();
1136 : void setsmcomparemode();
1137 : bool usesmcomparemode();
1138 :
1139 : };
1140 :
1141 0 : void ShadowAtlas::cleanup()
1142 : {
1143 0 : if(tex)
1144 : {
1145 0 : glDeleteTextures(1, &tex);
1146 0 : tex = 0;
1147 : }
1148 0 : if(fbo)
1149 : {
1150 0 : glDeleteFramebuffers(1, &fbo);
1151 0 : fbo = 0;
1152 : }
1153 0 : clearshadowcache();
1154 0 : }
1155 :
1156 0 : void ShadowAtlas::bind()
1157 : {
1158 0 : glBindTexture(target, tex);
1159 0 : }
1160 :
1161 : ShadowAtlas shadowatlas;
1162 :
1163 : //`s`hadow `m`ap vars
1164 : static FVAR(smpolyfactor, -1e3f, 1, 1e3f);
1165 : static FVAR(smpolyoffset, -1e3f, 0, 1e3f);
1166 : static FVAR(smbias, -1e6f, 0.01f, 1e6f);
1167 : static FVAR(smpolyfactor2, -1e3f, 1.5f, 1e3f);
1168 : static FVAR(smpolyoffset2, -1e3f, 0, 1e3f);
1169 : static FVAR(smbias2, -1e6f, 0.02f, 1e6f);
1170 : static FVAR(smprec, 1e-3f, 1, 1e3f);
1171 : static FVAR(smcubeprec, 1e-3f, 1, 1e3f);
1172 : static FVAR(smspotprec, 1e-3f, 1, 1e3f);
1173 :
1174 0 : VARFP(smsize, 10, 12, 14, shadowatlas.cleanup()); //size of shadow map: 2^size = x,y dimensions (1024x1024 at 10, 16384x16384 at 14)
1175 0 : VARFP(smdepthprec, 0, 0, 2, shadowatlas.cleanup()); //bit depth of sm depth map: 16bpp, 24bpp, or 32bpp respectively
1176 : VAR(smsidecull, 0, 1, 1); //`s`hadow `m`ap `side` `cull`: toggles culling lights outside the view frustum (outside the fov)
1177 : VAR(smviscull, 0, 1, 1); //`s`hadow `m`ap `vis`ibility `cull`ing: toggles visibility culling based of distance
1178 : VAR(smborder, 0, 3, 16); //`s`hadow `m`ap border
1179 : VAR(smborder2, 0, 4, 16); //smborder if smfilter > 2, for filter bleed reasons
1180 : VAR(smminsize, 1, 96, 1024); //min size for individual sm, not whole buffer
1181 : VAR(smmaxsize, 1, 384, 1024); //max size for individual sm, not whole buffer
1182 : //VAR(smmaxsize, 1, 4096, 4096);
1183 : VAR(smused, 1, 0, 0); //read only: shadow map area used
1184 : VAR(smquery, 0, 1, 1); // `s`hadow `m`ap `query1: whether to occlusion query lights
1185 0 : VARF(smcullside, 0, 1, 1, shadowatlas.cleanup());
1186 0 : VARF(smcache, 0, 1, 2, shadowatlas.cleanup());
1187 0 : VARFP(smfilter, 0, 2, 3, { cleardeferredlightshaders(); shadowatlas.cleanup(); cleanupvolumetric(); });
1188 0 : VARFP(smgather, 0, 0, 1, { cleardeferredlightshaders(); shadowatlas.cleanup(); cleanupvolumetric(); });
1189 : VAR(smnoshadow, 0, 0, 1);
1190 : VAR(smdynshadow, 0, 1, 1); //`s`hadow `m`ap `dyn`amic `shadow`
1191 :
1192 0 : void ShadowAtlas::setsmnoncomparemode() // use texture gather
1193 : {
1194 0 : glTexParameteri(target, GL_TEXTURE_COMPARE_MODE, GL_NONE);
1195 0 : glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1196 0 : glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1197 0 : }
1198 :
1199 0 : void ShadowAtlas::setsmcomparemode() // use embedded shadow cmp
1200 : {
1201 0 : glTexParameteri(target, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
1202 0 : glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1203 0 : glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1204 0 : }
1205 :
1206 0 : void ShadowAtlas::setcomparemode()
1207 : {
1208 0 : if(usesmcomparemode())
1209 : {
1210 0 : setsmcomparemode();
1211 : }
1212 : else
1213 : {
1214 0 : setsmnoncomparemode();
1215 : }
1216 0 : }
1217 :
1218 0 : static bool usegatherforsm()
1219 : {
1220 0 : return smfilter > 1 && smgather;
1221 : }
1222 :
1223 0 : bool ShadowAtlas::usesmcomparemode()
1224 : {
1225 0 : return !usegatherforsm() || (usetexgather > 1);
1226 : }
1227 :
1228 0 : void ShadowAtlas::view()
1229 : {
1230 0 : int w = std::min(hudw(), hudh())/2,
1231 0 : h = (w*hudh())/hudw(),
1232 0 : x = hudw()-w,
1233 0 : y = hudh()-h;
1234 0 : float tw = 1,
1235 0 : th = 1;
1236 0 : if(target == GL_TEXTURE_RECTANGLE)
1237 : {
1238 0 : vec2 sasize = shadowatlaspacker.dimensions();
1239 0 : tw = sasize.x;
1240 0 : th = sasize.y;
1241 0 : SETSHADER(hudrect);
1242 : }
1243 : else
1244 : {
1245 0 : hudshader->set();
1246 : }
1247 0 : gle::colorf(1, 1, 1);
1248 0 : glBindTexture(target, tex);
1249 0 : if(usesmcomparemode())
1250 : {
1251 0 : setsmnoncomparemode();
1252 : }
1253 0 : debugquad(x, y, w, h, 0, 0, tw, th);
1254 0 : if(usesmcomparemode())
1255 : {
1256 0 : setsmcomparemode();
1257 : }
1258 0 : }
1259 :
1260 : static VAR(debugshadowatlas, 0, 0, 1);
1261 :
1262 0 : void ShadowAtlas::setup()
1263 : {
1264 0 : int size = std::min((1<<smsize), hwtexsize);
1265 0 : shadowatlaspacker.resize(size, size);
1266 :
1267 0 : if(!tex)
1268 : {
1269 0 : glGenTextures(1, &tex);
1270 : }
1271 0 : vec2 sasize = shadowatlaspacker.dimensions();
1272 0 : target = usegatherforsm() ? GL_TEXTURE_2D : GL_TEXTURE_RECTANGLE;
1273 0 : createtexture(tex, sasize.x, sasize.y, nullptr, 3, 1, smdepthprec > 1 ? GL_DEPTH_COMPONENT32 : (smdepthprec ? GL_DEPTH_COMPONENT24 : GL_DEPTH_COMPONENT16), target);
1274 0 : glTexParameteri(target, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
1275 0 : glTexParameteri(target, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
1276 :
1277 0 : if(!fbo)
1278 : {
1279 0 : glGenFramebuffers(1, &fbo);
1280 : }
1281 0 : glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1282 0 : glDrawBuffer(GL_NONE);
1283 0 : glReadBuffer(GL_NONE);
1284 0 : glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, target, tex, 0);
1285 0 : if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
1286 : {
1287 0 : fatal("failed allocating shadow atlas!");
1288 : }
1289 0 : glBindFramebuffer(GL_FRAMEBUFFER, 0);
1290 0 : }
1291 :
1292 : const std::array<matrix4, 6> cubeshadowviewmatrix =
1293 : {{
1294 : // sign-preserving cubemap projections
1295 : matrix4(vec(0, 0, 1), vec(0, 1, 0), vec(-1, 0, 0)), // +X
1296 : matrix4(vec(0, 0, 1), vec(0, 1, 0), vec( 1, 0, 0)), // -X
1297 : matrix4(vec(1, 0, 0), vec(0, 0, 1), vec(0, -1, 0)), // +Y
1298 : matrix4(vec(1, 0, 0), vec(0, 0, 1), vec(0, 1, 0)), // -Y
1299 : matrix4(vec(1, 0, 0), vec(0, 1, 0), vec(0, 0, -1)), // +Z
1300 : matrix4(vec(1, 0, 0), vec(0, 1, 0), vec(0, 0, 1)) // -Z
1301 : }};
1302 :
1303 : static constexpr int LightTile_MaxBatch = 8; //also used in lightbatchkey below
1304 :
1305 0 : static VARF(lighttilebatch, 0, LightTile_MaxBatch, LightTile_MaxBatch, cleardeferredlightshaders());
1306 0 : VARF(batchsunlight, 0, 2, 2, cleardeferredlightshaders());
1307 :
1308 : int shadowmapping = 0;
1309 :
1310 : //not final: batchstack/batchrect derived
1311 : class LightRect
1312 : {
1313 : public:
1314 : uchar x1, y1, x2, y2;
1315 :
1316 : LightRect() {}
1317 0 : LightRect(const lightinfo &l)
1318 0 : {
1319 0 : calctilebounds(l.sx1, l.sy1, l.sx2, l.sy2, x1, y1, x2, y2);
1320 0 : }
1321 :
1322 0 : bool outside(const LightRect &o) const
1323 : {
1324 0 : return x1 >= o.x2 || x2 <= o.x1 || y1 >= o.y2 || y2 <= o.y1;
1325 : }
1326 :
1327 0 : bool inside(const LightRect &o) const
1328 : {
1329 0 : return x1 >= o.x1 && x2 <= o.x2 && y1 >= o.y1 && y2 <= o.y2;
1330 : }
1331 :
1332 0 : void intersect(const LightRect &o)
1333 : {
1334 0 : x1 = std::max(x1, o.x1);
1335 0 : y1 = std::max(y1, o.y1);
1336 0 : x2 = std::min(x2, o.x2);
1337 0 : y2 = std::min(y2, o.y2);
1338 0 : }
1339 :
1340 0 : bool overlaps(int tx1, int ty1, int tx2, int ty2, const uint *tilemask) const
1341 : {
1342 0 : if(static_cast<int>(x2) <= tx1 || static_cast<int>(x1) >= tx2 || static_cast<int>(y2) <= ty1 || static_cast<int>(y1) >= ty2)
1343 : {
1344 0 : return false;
1345 : }
1346 0 : if(!tilemask)
1347 : {
1348 0 : return true;
1349 : }
1350 0 : uint xmask = (1<<x2) - (1<<x1);
1351 0 : for(int y = std::max(static_cast<int>(y1), ty1), end = std::min(static_cast<int>(y2), ty2); y < end; y++)
1352 : {
1353 0 : if(tilemask[y] & xmask)
1354 : {
1355 0 : return true;
1356 : }
1357 : }
1358 0 : return false;
1359 : }
1360 : protected:
1361 : //only called by child batchstack object
1362 0 : LightRect(uchar x1, uchar y1, uchar x2, uchar y2) : x1(x1), y1(y1), x2(x2), y2(y2) {}
1363 : };
1364 :
1365 : //batchflag enum is local to this file
1366 : enum
1367 : {
1368 : BatchFlag_Spotlight = 1<<0,
1369 : BatchFlag_NoShadow = 1<<1,
1370 : BatchFlag_NoSun = 1<<2
1371 : };
1372 :
1373 : struct LightBatch
1374 : {
1375 : uchar flags, numlights;
1376 : ushort lights[LightTile_MaxBatch];
1377 :
1378 : std::vector<LightRect> rects;
1379 :
1380 : void reset()
1381 : {
1382 : rects.clear();
1383 : }
1384 :
1385 0 : bool overlaps(int tx1, int ty1, int tx2, int ty2, const uint *tilemask) const
1386 : {
1387 0 : if(!tx1 && !ty1 && tx2 >= lighttilew && ty2 >= lighttileh && !tilemask)
1388 : {
1389 0 : return true;
1390 : }
1391 0 : for(size_t i = 0; i < rects.size(); i++)
1392 : {
1393 0 : if(rects[i].overlaps(tx1, ty1, tx2, ty2, tilemask))
1394 : {
1395 0 : return true;
1396 : }
1397 : }
1398 0 : return false;
1399 : }
1400 : };
1401 :
1402 : static std::vector<lightinfo> lights;
1403 : static std::vector<int> lightorder;
1404 : static std::vector<LightBatch> lightbatches;
1405 : std::vector<ShadowMapInfo> shadowmaps;
1406 :
1407 1 : void clearshadowcache()
1408 : {
1409 1 : shadowmaps.clear();
1410 :
1411 1 : clearradiancehintscache();
1412 1 : clearshadowmeshes();
1413 1 : }
1414 :
1415 0 : void addshadowmap(ushort x, ushort y, int size, int &idx, int light, const shadowcacheval *cached)
1416 : {
1417 0 : idx = shadowmaps.size();
1418 : ShadowMapInfo sm;
1419 0 : sm.x = x;
1420 0 : sm.y = y;
1421 0 : sm.size = size;
1422 0 : sm.light = light;
1423 0 : sm.sidemask = 0;
1424 0 : sm.cached = cached;
1425 0 : shadowmaps.push_back(sm);
1426 0 : }
1427 :
1428 : //calculate bouunding box reflective shadow map splits
1429 0 : int calcbbrsmsplits(const ivec &bbmin, const ivec &bbmax)
1430 : {
1431 0 : if(!rsmcull)
1432 : {
1433 0 : return 1;
1434 : }
1435 0 : for(int k = 0; k < 4; ++k)
1436 : {
1437 0 : const plane &p = rsm.cull[k];
1438 0 : ivec omin, omax;
1439 0 : if(p.x > 0)
1440 : {
1441 0 : omin.x = bbmin.x;
1442 0 : omax.x = bbmax.x;
1443 : }
1444 : else
1445 : {
1446 0 : omin.x = bbmax.x;
1447 0 : omax.x = bbmin.x;
1448 : }
1449 0 : if(p.y > 0)
1450 : {
1451 0 : omin.y = bbmin.y;
1452 0 : omax.y = bbmax.y;
1453 : }
1454 : else
1455 : {
1456 0 : omin.y = bbmax.y;
1457 0 : omax.y = bbmin.y;
1458 : }
1459 0 : if(p.z > 0)
1460 : {
1461 0 : omin.z = bbmin.z;
1462 0 : omax.z = bbmax.z;
1463 : }
1464 : else
1465 : {
1466 0 : omin.z = bbmax.z;
1467 0 : omax.z = bbmin.z;
1468 : }
1469 0 : if(omax.dist(p) < 0)
1470 : {
1471 0 : return 0;
1472 : }
1473 0 : if(omin.dist(p) < 0)
1474 : {
1475 0 : while(++k < 4)
1476 : {
1477 0 : const plane &p = rsm.cull[k];
1478 0 : ivec omax(p.x > 0 ? bbmax.x : bbmin.x, p.y > 0 ? bbmax.y : bbmin.y, p.z > 0 ? bbmax.z : bbmin.z);
1479 0 : if(omax.dist(p) < 0)
1480 : {
1481 0 : return 0;
1482 : }
1483 : }
1484 : }
1485 : }
1486 0 : return 1;
1487 : }
1488 :
1489 0 : int calcspherersmsplits(const vec ¢er, float radius)
1490 : {
1491 0 : if(!rsmcull)
1492 : {
1493 0 : return 1;
1494 : }
1495 0 : for(int k = 0; k < 4; ++k)
1496 : {
1497 0 : const plane &p = rsm.cull[k];
1498 0 : float dist = p.dist(center);
1499 0 : if(dist < -radius)
1500 : {
1501 0 : return 0;
1502 : }
1503 0 : if(dist < radius)
1504 : {
1505 0 : while(++k < 4)
1506 : {
1507 0 : const plane &p = rsm.cull[k];
1508 0 : if(p.dist(center) < -radius)
1509 : {
1510 0 : return 0;
1511 : }
1512 : }
1513 : }
1514 : }
1515 0 : return 1;
1516 : }
1517 :
1518 0 : bool sphereinsidespot(const vec &dir, int spot, const vec ¢er, float radius)
1519 : {
1520 0 : const vec2 &sc = sincos360[spot];
1521 0 : float cdist = dir.dot(center),
1522 0 : cradius = radius + sc.y*cdist;
1523 0 : return sc.x*sc.x*(center.dot(center) - cdist*cdist) <= cradius*cradius;
1524 : }
1525 :
1526 0 : bool bbinsidespot(const vec &origin, const vec &dir, int spot, const ivec &bbmin, const ivec &bbmax)
1527 : {
1528 0 : vec radius = vec(ivec(bbmax).sub(bbmin)).mul(0.5f),
1529 0 : center = vec(bbmin).add(radius);
1530 0 : return sphereinsidespot(dir, spot, center.sub(origin), radius.magnitude());
1531 : }
1532 :
1533 : static FVAR(avatarshadowdist, 0, 12, 100);
1534 : static FVAR(avatarshadowbias, 0, 8, 100);
1535 0 : static VARF(avatarshadowstencil, 0, 1, 2, initwarning("g-buffer setup", Init_Load, Change_Shaders));
1536 :
1537 : int avatarmask = 0;
1538 :
1539 1 : static bool useavatarmask()
1540 : {
1541 1 : return avatarshadowstencil && ghasstencil && (!msaasamples || (msaalight && avatarshadowstencil > 1));
1542 : }
1543 :
1544 0 : void enableavatarmask()
1545 : {
1546 0 : if(useavatarmask())
1547 : {
1548 0 : avatarmask = 0x40;
1549 0 : glStencilFunc(GL_ALWAYS, avatarmask, ~0);
1550 0 : glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
1551 0 : glEnable(GL_STENCIL_TEST);
1552 : }
1553 0 : }
1554 :
1555 0 : void disableavatarmask()
1556 : {
1557 0 : if(avatarmask)
1558 : {
1559 0 : avatarmask = 0;
1560 0 : glDisable(GL_STENCIL_TEST);
1561 : }
1562 0 : }
1563 :
1564 : static VAR(forcespotlights, 1, 0, 0);
1565 :
1566 : static Shader *volumetricshader = nullptr;
1567 : std::array<Shader *, 2> volumetricbilateralshader = { nullptr, nullptr };
1568 :
1569 0 : void clearvolumetricshaders()
1570 : {
1571 0 : volumetricshader = nullptr;
1572 0 : volumetricbilateralshader.fill(nullptr);
1573 0 : }
1574 :
1575 0 : static VARFP(volumetric, 0, 1, 1, cleanupvolumetric()); //toggles displaying volumetric lights
1576 0 : static VARFP(volreduce, 0, 1, 2, cleanupvolumetric()); //size reduction factor for volumetric tex: 1 is 1/4, 2 is 1/16
1577 0 : static VARFP(volbilateral, 0, 1, 3, cleanupvolumetric()); //toggles bilateral filtering
1578 : static FVAR(volbilateraldepth, 0, 4, 1e3f); //bilateral filtering depth
1579 0 : static VARFP(volblur, 0, 1, 3, cleanupvolumetric());
1580 0 : static VARFP(volsteps, 1, 32, 128, cleanupvolumetric()); //iterations to run for volumetric algorithm
1581 : static FVAR(volminstep, 0, 0.0625f, 1e3f);
1582 : static FVAR(volprefilter, 0, 0.1, 1e3f);
1583 : static FVAR(voldistclamp, 0, 0.99f, 2);
1584 0 : static CVAR1R(volcolor, 0x808080);
1585 : static FVARR(volscale, 0, 1, 16);
1586 :
1587 0 : Shader *loadvolumetricshader()
1588 : {
1589 0 : std::string common, shadow;
1590 :
1591 0 : if(usegatherforsm())
1592 : {
1593 0 : common.push_back(smfilter > 2 ? 'G' : 'g');
1594 : }
1595 0 : else if(smfilter)
1596 : {
1597 0 : common.push_back(smfilter > 2 ? 'E' : (smfilter > 1 ? 'F' : 'f'));
1598 : }
1599 0 : if(spotlights || forcespotlights)
1600 : {
1601 0 : common.push_back('s');
1602 : }
1603 :
1604 0 : shadow.push_back('p');
1605 :
1606 0 : DEF_FORMAT_STRING(name, "volumetric%s%s%d", common.c_str(), shadow.c_str(), volsteps);
1607 0 : return generateshader(name, "volumetricshader \"%s\" \"%s\" %d", common.c_str(), shadow.c_str(), volsteps);
1608 0 : }
1609 :
1610 0 : static void loadvolumetricshaders()
1611 : {
1612 0 : volumetricshader = loadvolumetricshader();
1613 :
1614 0 : if(volbilateral)
1615 : {
1616 0 : for(int i = 0; i < 2; ++i)
1617 : {
1618 0 : DEF_FORMAT_STRING(name, "volumetricbilateral%c%d%d", 'x' + i, volbilateral, volreduce);
1619 0 : volumetricbilateralshader[i] = generateshader(name, "volumetricbilateralshader %d %d", volbilateral, volreduce);
1620 : }
1621 : }
1622 0 : }
1623 :
1624 : static int volw = -1,
1625 : volh = -1;
1626 : static std::array<GLuint, 2> volfbo = { 0, 0 },
1627 : voltex = { 0, 0 };
1628 :
1629 0 : static void setupvolumetric(int w, int h)
1630 : {
1631 0 : volw = w>>volreduce;
1632 0 : volh = h>>volreduce;
1633 :
1634 0 : for(int i = 0; i < (volbilateral || volblur ? 2 : 1); ++i)
1635 : {
1636 0 : if(!voltex[i])
1637 : {
1638 0 : glGenTextures(1, &voltex[i]);
1639 : }
1640 0 : if(!volfbo[i])
1641 : {
1642 0 : glGenFramebuffers(1, &volfbo[i]);
1643 : }
1644 :
1645 0 : glBindFramebuffer(GL_FRAMEBUFFER, volfbo[i]);
1646 :
1647 0 : createtexture(voltex[i], volw, volh, nullptr, 3, 1, hdrformat, GL_TEXTURE_RECTANGLE);
1648 :
1649 0 : glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_RECTANGLE, voltex[i], 0);
1650 :
1651 0 : if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
1652 : {
1653 0 : fatal("failed allocating volumetric buffer!");
1654 : }
1655 : }
1656 :
1657 0 : glBindFramebuffer(GL_FRAMEBUFFER, 0);
1658 :
1659 0 : loadvolumetricshaders();
1660 0 : }
1661 :
1662 0 : void cleanupvolumetric()
1663 : {
1664 0 : for(GLuint &i : volfbo)
1665 : {
1666 0 : if(i)
1667 : {
1668 0 : glDeleteFramebuffers(1, &i);
1669 0 : i = 0;
1670 : }
1671 : }
1672 0 : for(GLuint &i : voltex)
1673 : {
1674 0 : if(i)
1675 : {
1676 0 : glDeleteTextures(1, &i);
1677 0 : i = 0;
1678 : }
1679 : }
1680 0 : volw = volh = -1;
1681 :
1682 0 : clearvolumetricshaders();
1683 0 : }
1684 :
1685 : static Shader *deferredlightshader = nullptr,
1686 : *deferredminimapshader = nullptr,
1687 : *deferredmsaapixelshader = nullptr,
1688 : *deferredmsaasampleshader = nullptr;
1689 :
1690 0 : void cleardeferredlightshaders()
1691 : {
1692 0 : deferredlightshader = nullptr;
1693 0 : deferredminimapshader = nullptr;
1694 0 : deferredmsaapixelshader = nullptr;
1695 0 : deferredmsaasampleshader = nullptr;
1696 0 : }
1697 :
1698 0 : Shader *loaddeferredlightshader(const char *type = nullptr)
1699 : {
1700 : string common, shadow, sun;
1701 0 : int commonlen = 0,
1702 0 : shadowlen = 0,
1703 0 : sunlen = 0;
1704 :
1705 0 : bool minimap = false,
1706 0 : multisample = false,
1707 0 : avatar = true;
1708 0 : if(type)
1709 : {
1710 0 : if(std::strchr(type, 'm'))
1711 : {
1712 0 : minimap = true;
1713 : }
1714 0 : if(std::strchr(type, 'M'))
1715 : {
1716 0 : multisample = true;
1717 : }
1718 0 : if(std::strchr(type, 'D'))
1719 : {
1720 0 : avatar = false;
1721 : }
1722 0 : copystring(common, type);
1723 0 : commonlen = std::strlen(common);
1724 : }
1725 0 : if(!minimap)
1726 : {
1727 0 : if(!multisample || msaalight)
1728 : {
1729 0 : common[commonlen++] = 't';
1730 : }
1731 0 : if(avatar && useavatarmask())
1732 : {
1733 0 : common[commonlen++] = 'd';
1734 : }
1735 0 : if(lighttilebatch)
1736 : {
1737 0 : common[commonlen++] = 'n';
1738 0 : common[commonlen++] = '0' + lighttilebatch;
1739 : }
1740 : }
1741 0 : if(usegatherforsm())
1742 : {
1743 0 : common[commonlen++] = smfilter > 2 ? 'G' : 'g';
1744 : }
1745 0 : else if(smfilter)
1746 : {
1747 0 : common[commonlen++] = smfilter > 2 ? 'E' : (smfilter > 1 ? 'F' : 'f');
1748 : }
1749 0 : if(spotlights || forcespotlights)
1750 : {
1751 0 : common[commonlen++] = 's';
1752 : }
1753 0 : if(nospeclights)
1754 : {
1755 0 : common[commonlen++] = 'z';
1756 : }
1757 0 : common[commonlen] = '\0';
1758 :
1759 0 : shadow[shadowlen++] = 'p';
1760 0 : shadow[shadowlen] = '\0';
1761 :
1762 0 : int usecsm = 0,
1763 0 : userh = 0;
1764 0 : if(!sunlight.iszero() && csm.getcsmproperty(CascadedShadowMap::ShadowMap))
1765 : {
1766 0 : usecsm = csm.getcsmproperty(CascadedShadowMap::Splits);
1767 0 : sun[sunlen++] = 'c';
1768 0 : sun[sunlen++] = '0' + usecsm;
1769 0 : if(!minimap)
1770 : {
1771 0 : if(avatar && ao && aosun)
1772 : {
1773 0 : sun[sunlen++] = 'A';
1774 : }
1775 0 : if(gi && giscale && gidist)
1776 : {
1777 0 : userh = rhsplits;
1778 0 : sun[sunlen++] = 'r';
1779 0 : sun[sunlen++] = '0' + rhsplits;
1780 : }
1781 : }
1782 : }
1783 0 : if(!minimap)
1784 : {
1785 0 : if(avatar && ao)
1786 : {
1787 0 : sun[sunlen++] = 'a';
1788 : }
1789 0 : if(lighttilebatch && (!usecsm || batchsunlight > (userh ? 1 : 0)))
1790 : {
1791 0 : sun[sunlen++] = 'b';
1792 : }
1793 : }
1794 0 : sun[sunlen] = '\0';
1795 :
1796 0 : DEF_FORMAT_STRING(name, "deferredlight%s%s%s", common, shadow, sun);
1797 0 : return generateshader(name, "deferredlightshader \"%s\" \"%s\" \"%s\" %d %d %d", common, shadow, sun, usecsm, userh, !minimap ? lighttilebatch : 0);
1798 : }
1799 :
1800 0 : void loaddeferredlightshaders()
1801 : {
1802 0 : if(msaasamples)
1803 : {
1804 : string opts;
1805 0 : if(msaalight > 2)
1806 : {
1807 0 : copystring(opts, "MS");
1808 : }
1809 0 : else if(msaalight==2)
1810 : {
1811 0 : copystring(opts, ghasstencil || !msaaedgedetect ? "MO" : "MOT");
1812 : }
1813 : else
1814 : {
1815 0 : formatstring(opts, ghasstencil || !msaaedgedetect ? "MR%d" : "MRT%d", msaasamples);
1816 : }
1817 0 : deferredmsaasampleshader = loaddeferredlightshader(opts);
1818 0 : deferredmsaapixelshader = loaddeferredlightshader("M");
1819 0 : deferredlightshader = msaalight ? deferredmsaapixelshader : loaddeferredlightshader("D");
1820 : }
1821 : else
1822 : {
1823 0 : deferredlightshader = loaddeferredlightshader();
1824 : }
1825 0 : }
1826 :
1827 0 : static bool sortlights(int x, int y)
1828 : {
1829 0 : const lightinfo &xl = lights[x],
1830 0 : &yl = lights[y];
1831 0 : if(!xl.spot)
1832 : {
1833 0 : if(yl.spot)
1834 : {
1835 0 : return true;
1836 : }
1837 : }
1838 0 : else if(!yl.spot)
1839 : {
1840 0 : return false;
1841 : }
1842 0 : if(!xl.noshadow())
1843 : {
1844 0 : if(yl.noshadow())
1845 : {
1846 0 : return true;
1847 : }
1848 : }
1849 0 : else if(!yl.noshadow())
1850 : {
1851 0 : return false;
1852 : }
1853 0 : if(xl.sz1 < yl.sz1)
1854 : {
1855 0 : return true;
1856 : }
1857 0 : else if(xl.sz1 > yl.sz1)
1858 : {
1859 0 : return false;
1860 : }
1861 0 : return xl.dist - xl.radius < yl.dist - yl.radius;
1862 : }
1863 :
1864 : VAR(lighttilealignw, 1, 16, 256); // x tiling size for lights inside the shadow cache (pixel grid size to snap to)
1865 : VAR(lighttilealignh, 1, 16, 256); // y tiling size for lights
1866 : int lighttilemaxw = variable("lighttilew", 1, 10, lighttilemaxwidth, &lighttilemaxw, nullptr, 0);
1867 : int lighttilemaxh = variable("lighttileh", 1, 10, lighttilemaxheight, &lighttilemaxh, nullptr, 0);
1868 :
1869 : int lighttilew = 0,
1870 : lighttileh = 0,
1871 : lighttilevieww = 0,
1872 : lighttileviewh = 0;
1873 :
1874 0 : void calctilesize()
1875 : {
1876 0 : lighttilevieww = (vieww + lighttilealignw - 1)/lighttilealignw;
1877 0 : lighttileviewh = (viewh + lighttilealignh - 1)/lighttilealignh;
1878 0 : lighttilew = std::min(lighttilevieww, lighttilemaxw);
1879 0 : lighttileh = std::min(lighttileviewh, lighttilemaxh);
1880 0 : }
1881 :
1882 0 : void resetlights()
1883 : {
1884 : static constexpr int shadowcacheevict = 2;
1885 : static int evictshadowcache = 0;
1886 0 : shadowatlas.cache.clear();
1887 0 : if(smcache)
1888 : {
1889 0 : vec2 sasize = shadowatlaspacker.dimensions();
1890 0 : int evictx = ((evictshadowcache%shadowcacheevict)*sasize.x)/shadowcacheevict,
1891 0 : evicty = ((evictshadowcache/shadowcacheevict)*sasize.y)/shadowcacheevict,
1892 0 : evictx2 = (((evictshadowcache%shadowcacheevict)+1)*sasize.x)/shadowcacheevict,
1893 0 : evicty2 = (((evictshadowcache/shadowcacheevict)+1)*sasize.y)/shadowcacheevict;
1894 0 : for(const ShadowMapInfo &sm : shadowmaps)
1895 : {
1896 0 : if(sm.light < 0)
1897 : {
1898 0 : continue;
1899 : }
1900 0 : lightinfo &l = lights[sm.light];
1901 0 : if(sm.cached && shadowatlas.full)
1902 : {
1903 0 : int w = l.spot ? sm.size : sm.size*3,
1904 0 : h = l.spot ? sm.size : sm.size*2;
1905 0 : if(sm.x < evictx2 && sm.x + w > evictx && sm.y < evicty2 && sm.y + h > evicty)
1906 : {
1907 0 : continue;
1908 : }
1909 : }
1910 0 : shadowatlas.cache[l] = sm;
1911 : }
1912 0 : if(shadowatlas.full)
1913 : {
1914 0 : evictshadowcache = (evictshadowcache + 1)%(shadowcacheevict*shadowcacheevict);
1915 0 : shadowatlas.full = false;
1916 : }
1917 : }
1918 :
1919 0 : lights.clear();
1920 0 : lightorder.clear();
1921 :
1922 0 : shadowmaps.clear();
1923 0 : shadowatlaspacker.reset();
1924 :
1925 0 : calctilesize();
1926 0 : }
1927 :
1928 : static VAR(depthtestlights, 0, 2, 2);
1929 : static FVAR(depthtestlightsclamp, 0, 0.999995f, 1); //z margin for light depth testing at depthtestlights = 2
1930 : static VAR(depthfaillights, 0, 1, 1);
1931 :
1932 0 : static void lightquads(float z, const vec2 &s1, const vec2 &s2)
1933 : {
1934 0 : gle::attribf(s1.x, s1.y, z);
1935 0 : gle::attribf(s1.x, s2.y, z);
1936 0 : gle::attribf(s2.x, s2.y, z);
1937 0 : gle::attribf(s1.x, s1.y, z);
1938 0 : gle::attribf(s2.x, s2.y, z);
1939 0 : gle::attribf(s2.x, s1.y, z);
1940 :
1941 0 : }
1942 :
1943 0 : static void lightquads(float z, const vec2 &s1, const vec2 &s2, const ivec2 &t1, const ivec2 &t2)
1944 : {
1945 0 : int vx1 = std::max(static_cast<int>(std::floor((s1.x*0.5f+0.5f)*vieww)), ((t1.x()*lighttilevieww)/lighttilew)*lighttilealignw),
1946 0 : vy1 = std::max(static_cast<int>(std::floor((s1.y*0.5f+0.5f)*viewh)), ((t1.y()*lighttileviewh)/lighttileh)*lighttilealignh),
1947 0 : vx2 = std::min(static_cast<int>(std::ceil((s2.x*0.5f+0.5f)*vieww)), std::min(((t2.x()*lighttilevieww)/lighttilew)*lighttilealignw, vieww)),
1948 0 : vy2 = std::min(static_cast<int>(std::ceil((s2.y*0.5f+0.5f)*viewh)), std::min(((t2.y()*lighttileviewh)/lighttileh)*lighttilealignh, viewh));
1949 0 : lightquads(z, {(vx1*2.0f)/vieww-1.0f, (vy1*2.0f)/viewh-1.0f}, {(vx2*2.0f)/vieww-1.0f, (vy2*2.0f)/viewh-1.0f});
1950 0 : }
1951 :
1952 0 : static void lightquads(float z, vec2 s1, vec2 s2, int x1, int y1, int x2, int y2, const uint *tilemask)
1953 : {
1954 0 : if(!tilemask)
1955 : {
1956 0 : lightquads(z, s1, s2, {x1, y1}, {x2, y2});
1957 : }
1958 : else
1959 : {
1960 0 : for(int y = y1; y < y2;)
1961 : {
1962 0 : int starty = y;
1963 0 : uint xmask = (1<<x2) - (1<<x1),
1964 0 : startmask = tilemask[y] & xmask;
1965 : do
1966 : {
1967 0 : ++y;
1968 0 : } while(y < y2 && (tilemask[y]&xmask) == startmask);
1969 0 : for(int x = x1; x < x2;)
1970 : {
1971 0 : while(x < x2 && !(startmask&(1<<x)))
1972 : {
1973 0 : ++x;
1974 : }
1975 0 : if(x >= x2)
1976 : {
1977 0 : break;
1978 : }
1979 0 : int startx = x;
1980 : do
1981 : {
1982 0 : ++x;
1983 0 : } while(x < x2 && startmask&(1<<x));
1984 0 : lightquads(z, s1, s2, {startx, starty}, {x, y});
1985 : }
1986 : }
1987 : }
1988 0 : }
1989 :
1990 0 : static void lightquad(float sz1, float bsx1, float bsy1, float bsx2, float bsy2, const uint *tilemask)
1991 : {
1992 : int btx1, bty1, btx2, bty2;
1993 0 : calctilebounds(bsx1, bsy1, bsx2, bsy2, btx1, bty1, btx2, bty2);
1994 :
1995 0 : gle::begin(GL_TRIANGLES);
1996 0 : lightquads(sz1, {bsx1, bsy1}, {bsx2, bsy2}, btx1, bty1, btx2, bty2, tilemask);
1997 0 : gle::end();
1998 0 : }
1999 :
2000 : static VAR(fullbright, 0, 0, 1); //toggles rendering at fullbrightlevel light
2001 : static VAR(fullbrightlevel, 0, 160, 255); //grayscale shade for lighting when at fullbright
2002 :
2003 0 : void GBuffer::bindlighttexs(int msaapass, bool transparent) const
2004 : {
2005 0 : if(msaapass)
2006 : {
2007 0 : glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, mscolortex);
2008 : }
2009 : else
2010 : {
2011 0 : glBindTexture(GL_TEXTURE_RECTANGLE, gcolortex);
2012 : }
2013 0 : glActiveTexture(GL_TEXTURE1);
2014 0 : if(msaapass)
2015 : {
2016 0 : glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, msnormaltex);
2017 : }
2018 : else
2019 : {
2020 0 : glBindTexture(GL_TEXTURE_RECTANGLE, gnormaltex);
2021 : }
2022 0 : if(transparent)
2023 : {
2024 0 : glActiveTexture(GL_TEXTURE2);
2025 0 : if(msaapass)
2026 : {
2027 0 : glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, msglowtex);
2028 : }
2029 : else
2030 : {
2031 0 : glBindTexture(GL_TEXTURE_RECTANGLE, gglowtex);
2032 : }
2033 : }
2034 0 : glActiveTexture(GL_TEXTURE3);
2035 0 : if(msaapass)
2036 : {
2037 0 : glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, msdepthtex);
2038 : }
2039 : else
2040 : {
2041 0 : glBindTexture(GL_TEXTURE_RECTANGLE, gdepthtex);
2042 : }
2043 0 : glActiveTexture(GL_TEXTURE4);
2044 0 : shadowatlas.bind();
2045 0 : shadowatlas.setcomparemode();
2046 0 : if(ao)
2047 : {
2048 0 : glActiveTexture(GL_TEXTURE5);
2049 0 : glBindTexture(GL_TEXTURE_RECTANGLE, aotex[2] ? aotex[2] : aotex[0]);
2050 : }
2051 0 : if(useradiancehints())
2052 : {
2053 0 : for(int i = 0; i < 4; ++i)
2054 : {
2055 0 : glActiveTexture(GL_TEXTURE6 + i);
2056 0 : glBindTexture(GL_TEXTURE_3D, rhtex[i]);
2057 : }
2058 : }
2059 0 : glActiveTexture(GL_TEXTURE0);
2060 0 : }
2061 :
2062 0 : static void setlightglobals(bool transparent = false)
2063 : {
2064 0 : vec2 sasize = shadowatlaspacker.dimensions();
2065 0 : GLOBALPARAMF(shadowatlasscale, 1.0f/sasize.x, 1.0f/sasize.y);
2066 0 : if(ao)
2067 : {
2068 0 : if(transparent || drawtex || (editmode && fullbright))
2069 : {
2070 0 : GLOBALPARAMF(aoscale, 0.0f, 0.0f);
2071 0 : GLOBALPARAMF(aoparams, 1.0f, 0.0f, 1.0f, 0.0f);
2072 0 : }
2073 : else
2074 : {
2075 0 : GLOBALPARAM(aoscale, aotex[2] ? vec2(1, 1) : vec2(static_cast<float>(aow)/vieww, static_cast<float>(aoh)/viewh));
2076 0 : GLOBALPARAMF(aoparams, aomin, 1.0f-aomin, aosunmin, 1.0f-aosunmin);
2077 : }
2078 : }
2079 0 : float lightscale = 2.0f*ldrscaleb();
2080 0 : if(!drawtex && editmode && fullbright)
2081 : {
2082 0 : GLOBALPARAMF(lightscale, fullbrightlevel*lightscale, fullbrightlevel*lightscale, fullbrightlevel*lightscale, 255*lightscale);
2083 0 : }
2084 : else
2085 : {
2086 0 : GLOBALPARAMF(lightscale, ambient.x*lightscale*ambientscale, ambient.y*lightscale*ambientscale, ambient.z*lightscale*ambientscale, 255*lightscale);
2087 : }
2088 0 : if(!sunlight.iszero() && csm.getcsmproperty(CascadedShadowMap::ShadowMap))
2089 : {
2090 0 : csm.bindparams();
2091 0 : rh.bindparams();
2092 0 : if(!drawtex && editmode && fullbright)
2093 : {
2094 0 : GLOBALPARAMF(sunlightdir, 0, 0, 0);
2095 0 : GLOBALPARAMF(sunlightcolor, 0, 0, 0);
2096 0 : GLOBALPARAMF(giscale, 0);
2097 0 : GLOBALPARAMF(skylightcolor, 0, 0, 0);
2098 0 : }
2099 : else
2100 : {
2101 0 : GLOBALPARAM(sunlightdir, sunlightdir);
2102 0 : GLOBALPARAMF(sunlightcolor, sunlight.x*lightscale*sunlightscale, sunlight.y*lightscale*sunlightscale, sunlight.z*lightscale*sunlightscale);
2103 0 : GLOBALPARAMF(giscale, 2*giscale);
2104 0 : GLOBALPARAMF(skylightcolor, 2*giaoscale*skylight.x*lightscale*skylightscale, 2*giaoscale*skylight.y*lightscale*skylightscale, 2*giaoscale*skylight.z*lightscale*skylightscale);
2105 : }
2106 : }
2107 :
2108 0 : matrix4 lightmatrix;
2109 0 : lightmatrix.identity();
2110 0 : GLOBALPARAM(lightmatrix, lightmatrix);
2111 0 : }
2112 :
2113 : //values only for interaction between setlightparams() and setlightshader()
2114 : struct LightParamInfo
2115 : {
2116 : std::array<vec4<float>, 8> lightposv, lightcolorv, spotparamsv, shadowparamsv;
2117 : std::array<vec2, 8> shadowoffsetv;
2118 : };
2119 :
2120 : //sets the ith element of lightposv, lightcolorv, spotparamsv, shadowparamsv, shadowoffsetv
2121 : //UB if i > 7
2122 : //
2123 0 : static void setlightparams(int i, const lightinfo &l, LightParamInfo &li)
2124 : {
2125 0 : li.lightposv[i] = vec4<float>(l.o, 1).div(l.radius);
2126 0 : li.lightcolorv[i] = vec4<float>(vec(l.color).mul(2*ldrscaleb()), l.nospec() ? 0 : 1);
2127 0 : if(l.spot > 0)
2128 : {
2129 0 : li.spotparamsv[i] = vec4<float>(vec(l.dir).neg(), 1/(1 - cos360(l.spot)));
2130 : }
2131 0 : if(l.shadowmap >= 0)
2132 : {
2133 0 : const ShadowMapInfo &sm = shadowmaps[l.shadowmap];
2134 0 : float smnearclip = SQRT3 / l.radius, smfarclip = SQRT3,
2135 0 : bias = (smfilter > 2 || shadowatlaspacker.dimensions().x > shadowatlassize ? smbias2 : smbias) * (smcullside ? 1 : -1) * smnearclip * (1024.0f / sm.size);
2136 0 : int border = smfilter > 2 ? smborder2 : smborder;
2137 0 : if(l.spot > 0)
2138 : {
2139 0 : li.shadowparamsv[i] = vec4<float>(
2140 0 : -0.5f * sm.size * cotan360(l.spot),
2141 0 : (-smnearclip * smfarclip / (smfarclip - smnearclip) - 0.5f*bias),
2142 0 : 1 / (1 + std::fabs(l.dir.z)),
2143 0 : 0.5f + 0.5f * (smfarclip + smnearclip) / (smfarclip - smnearclip));
2144 : }
2145 : else
2146 : {
2147 0 : li.shadowparamsv[i] = vec4<float>(
2148 0 : -0.5f * (sm.size - border),
2149 0 : -smnearclip * smfarclip / (smfarclip - smnearclip) - 0.5f*bias,
2150 0 : sm.size,
2151 0 : 0.5f + 0.5f * (smfarclip + smnearclip) / (smfarclip - smnearclip));
2152 : }
2153 0 : li.shadowoffsetv[i] = vec2(sm.x + 0.5f*sm.size, sm.y + 0.5f*sm.size);
2154 : }
2155 0 : }
2156 :
2157 0 : static void setlightshader(Shader *s, const LightParamInfo &li, int n, bool baselight, bool shadowmap, bool spotlight, bool transparent = false, bool avatar = false)
2158 : {
2159 0 : static const LocalShaderParam lightpos("lightpos"),
2160 0 : lightcolor("lightcolor"),
2161 0 : spotparams("spotparams"),
2162 0 : shadowparams("shadowparams"),
2163 0 : shadowoffset("shadowoffset");
2164 0 : s->setvariant(n-1, (shadowmap ? 1 : 0) + (baselight ? 0 : 2) + (spotlight ? 4 : 0) + (transparent ? 8 : 0) + (avatar ? 24 : 0));
2165 0 : lightpos.setv(li.lightposv.data(), n);
2166 0 : lightcolor.setv(li.lightcolorv.data(), n);
2167 0 : if(spotlight)
2168 : {
2169 0 : spotparams.setv(li.spotparamsv.data(), n);
2170 : }
2171 0 : if(shadowmap)
2172 : {
2173 0 : shadowparams.setv(li.shadowparamsv.data(), n);
2174 0 : shadowoffset.setv(li.shadowoffsetv.data(), n);
2175 : }
2176 0 : }
2177 :
2178 0 : static void setavatarstencil(int stencilref, bool on)
2179 : {
2180 0 : glStencilFunc(GL_EQUAL, (on ? 0x40 : 0) | stencilref, !(stencilref&0x08) && msaalight==2 ? 0x47 : 0x4F);
2181 0 : }
2182 :
2183 0 : void GBuffer::rendersunpass(Shader *s, int stencilref, bool transparent, float bsx1, float bsy1, float bsx2, float bsy2, const uint *tilemask)
2184 : {
2185 0 : if(hasDBT && depthtestlights > 1)
2186 : {
2187 0 : glDepthBounds_(0, depthtestlightsclamp);
2188 : }
2189 0 : int tx1 = std::max(static_cast<int>(std::floor((bsx1*0.5f+0.5f)*vieww)), 0),
2190 0 : ty1 = std::max(static_cast<int>(std::floor((bsy1*0.5f+0.5f)*viewh)), 0),
2191 0 : tx2 = std::min(static_cast<int>(std::ceil((bsx2*0.5f+0.5f)*vieww)), vieww),
2192 0 : ty2 = std::min(static_cast<int>(std::ceil((bsy2*0.5f+0.5f)*viewh)), viewh);
2193 0 : s->setvariant(transparent ? 0 : -1, 16);
2194 0 : lightquad(-1, (tx1*2.0f)/vieww-1.0f, (ty1*2.0f)/viewh-1.0f, (tx2*2.0f)/vieww-1.0f, (ty2*2.0f)/viewh-1.0f, tilemask);
2195 0 : lightpassesused++;
2196 :
2197 0 : if(stencilref >= 0)
2198 : {
2199 0 : setavatarstencil(stencilref, true);
2200 :
2201 0 : s->setvariant(0, 17);
2202 0 : lightquad(-1, (tx1*2.0f)/vieww-1.0f, (ty1*2.0f)/viewh-1.0f, (tx2*2.0f)/vieww-1.0f, (ty2*2.0f)/viewh-1.0f, tilemask);
2203 0 : lightpassesused++;
2204 :
2205 0 : setavatarstencil(stencilref, false);
2206 : }
2207 0 : }
2208 :
2209 0 : void GBuffer::renderlightsnobatch(Shader *s, int stencilref, bool transparent, float bsx1, float bsy1, float bsx2, float bsy2)
2210 : {
2211 0 : lightsphere::enable();
2212 :
2213 0 : glEnable(GL_SCISSOR_TEST);
2214 :
2215 0 : bool outside = true;
2216 0 : static LightParamInfo li;
2217 0 : for(int avatarpass = 0; avatarpass < (stencilref >= 0 ? 2 : 1); ++avatarpass)
2218 : {
2219 0 : if(avatarpass)
2220 : {
2221 0 : setavatarstencil(stencilref, true);
2222 : }
2223 :
2224 0 : for(size_t i = 0; i < lightorder.size(); i++)
2225 : {
2226 0 : const lightinfo &l = lights[lightorder[i]];
2227 0 : float sx1 = std::max(bsx1, l.sx1),
2228 0 : sy1 = std::max(bsy1, l.sy1),
2229 0 : sx2 = std::min(bsx2, l.sx2),
2230 0 : sy2 = std::min(bsy2, l.sy2);
2231 0 : if(sx1 >= sx2 || sy1 >= sy2 || l.sz1 >= l.sz2 || (avatarpass && l.dist - l.radius > avatarshadowdist))
2232 : {
2233 0 : continue;
2234 : }
2235 0 : matrix4 lightmatrix = camprojmatrix;
2236 0 : lightmatrix.translate(l.o);
2237 0 : lightmatrix.scale(l.radius);
2238 0 : GLOBALPARAM(lightmatrix, lightmatrix);
2239 :
2240 0 : setlightparams(0, l, li);
2241 0 : setlightshader(s, li, 1, false, l.shadowmap >= 0, l.spot > 0, transparent, avatarpass > 0);
2242 :
2243 0 : int tx1 = static_cast<int>(std::floor((sx1*0.5f+0.5f)*vieww)),
2244 0 : ty1 = static_cast<int>(std::floor((sy1*0.5f+0.5f)*viewh)),
2245 0 : tx2 = static_cast<int>(std::ceil((sx2*0.5f+0.5f)*vieww)),
2246 0 : ty2 = static_cast<int>(std::ceil((sy2*0.5f+0.5f)*viewh));
2247 0 : glScissor(tx1, ty1, tx2-tx1, ty2-ty1);
2248 :
2249 0 : if(hasDBT && depthtestlights > 1)
2250 : {
2251 0 : glDepthBounds_(l.sz1*0.5f + 0.5f, std::min(l.sz2*0.5f + 0.5f, depthtestlightsclamp));
2252 : }
2253 :
2254 0 : if(camera1->o.dist(l.o) <= l.radius + nearplane + 1 && depthfaillights)
2255 : {
2256 0 : if(outside)
2257 : {
2258 0 : outside = false;
2259 0 : glDepthFunc(GL_GEQUAL);
2260 0 : glCullFace(GL_FRONT);
2261 : }
2262 : }
2263 0 : else if(!outside)
2264 : {
2265 0 : outside = true;
2266 0 : glDepthFunc(GL_LESS);
2267 0 : glCullFace(GL_BACK);
2268 : }
2269 :
2270 0 : lightsphere::draw();
2271 :
2272 0 : lightpassesused++;
2273 : }
2274 :
2275 0 : if(avatarpass)
2276 : {
2277 0 : setavatarstencil(stencilref, false);
2278 : }
2279 : }
2280 :
2281 0 : if(!outside)
2282 : {
2283 0 : outside = true;
2284 0 : glDepthFunc(GL_LESS);
2285 0 : glCullFace(GL_BACK);
2286 : }
2287 :
2288 0 : glDisable(GL_SCISSOR_TEST);
2289 :
2290 0 : lightsphere::disable();
2291 0 : }
2292 :
2293 0 : void GBuffer::renderlightbatches(Shader &s, int stencilref, bool transparent, float bsx1, float bsy1, float bsx2, float bsy2, const uint *tilemask)
2294 : {
2295 0 : bool sunpass = !sunlight.iszero() && csm.getcsmproperty(CascadedShadowMap::ShadowMap) && batchsunlight <= (gi && giscale && gidist ? 1 : 0);
2296 : int btx1, bty1, btx2, bty2;
2297 0 : calctilebounds(bsx1, bsy1, bsx2, bsy2, btx1, bty1, btx2, bty2);
2298 0 : static LightParamInfo li;
2299 0 : for(size_t i = 0; i < lightbatches.size(); i++)
2300 : {
2301 0 : const LightBatch &batch = lightbatches[i];
2302 0 : if(!batch.overlaps(btx1, bty1, btx2, bty2, tilemask))
2303 : {
2304 0 : continue;
2305 : }
2306 :
2307 0 : int n = batch.numlights;
2308 0 : float sx1 = 1,
2309 0 : sy1 = 1,
2310 0 : sx2 = -1,
2311 0 : sy2 = -1,
2312 0 : sz1 = 1,
2313 0 : sz2 = -1;
2314 0 : for(int j = 0; j < n; ++j)
2315 : {
2316 0 : const lightinfo &l = lights[batch.lights[j]];
2317 0 : setlightparams(j, l, li); //set 0...batch.numlights
2318 0 : l.addscissor(sx1, sy1, sx2, sy2, sz1, sz2);
2319 : }
2320 :
2321 0 : bool baselight = !(batch.flags & BatchFlag_NoSun) && !sunpass;
2322 0 : if(baselight)
2323 : {
2324 0 : sx1 = bsx1;
2325 0 : sy1 = bsy1;
2326 0 : sx2 = bsx2;
2327 0 : sy2 = bsy2;
2328 0 : sz1 = -1;
2329 0 : sz2 = 1;
2330 : }
2331 : else
2332 : {
2333 0 : sx1 = std::max(sx1, bsx1);
2334 0 : sy1 = std::max(sy1, bsy1);
2335 0 : sx2 = std::min(sx2, bsx2);
2336 0 : sy2 = std::min(sy2, bsy2);
2337 0 : if(sx1 >= sx2 || sy1 >= sy2 || sz1 >= sz2)
2338 : {
2339 0 : continue;
2340 : }
2341 : }
2342 :
2343 0 : if(n)
2344 : {
2345 0 : bool shadowmap = !(batch.flags & BatchFlag_NoShadow),
2346 0 : spotlight = (batch.flags & BatchFlag_Spotlight) != 0;
2347 0 : setlightshader(&s, li, n, baselight, shadowmap, spotlight, transparent);
2348 : }
2349 : else
2350 : {
2351 0 : s.setvariant(transparent ? 0 : -1, 16);
2352 : }
2353 :
2354 0 : lightpassesused++;
2355 :
2356 0 : if(hasDBT && depthtestlights > 1)
2357 : {
2358 0 : glDepthBounds_(sz1*0.5f + 0.5f, std::min(sz2*0.5f + 0.5f, depthtestlightsclamp));
2359 : }
2360 0 : gle::begin(GL_TRIANGLES);
2361 0 : for(size_t j = 0; j < batch.rects.size(); j++)
2362 : {
2363 0 : const LightRect &r = batch.rects[j];
2364 0 : int x1 = std::max(static_cast<int>(r.x1), btx1),
2365 0 : y1 = std::max(static_cast<int>(r.y1), bty1),
2366 0 : x2 = std::min(static_cast<int>(r.x2), btx2),
2367 0 : y2 = std::min(static_cast<int>(r.y2), bty2);
2368 0 : if(x1 < x2 && y1 < y2)
2369 : {
2370 0 : lightquads(sz1, {sx1, sy1}, {sx2, sy2}, x1, y1, x2, y2, tilemask);
2371 : }
2372 : }
2373 0 : gle::end();
2374 : }
2375 :
2376 0 : if(stencilref >= 0)
2377 : {
2378 0 : setavatarstencil(stencilref, true);
2379 :
2380 0 : bool baselight = !sunpass;
2381 0 : for(int offset = 0; baselight || offset < static_cast<int>(lightorder.size()); baselight = false)
2382 : {
2383 0 : int n = 0;
2384 0 : bool shadowmap = false,
2385 0 : spotlight = false;
2386 0 : float sx1 = 1,
2387 0 : sy1 = 1,
2388 0 : sx2 = -1,
2389 0 : sy2 = -1,
2390 0 : sz1 = 1,
2391 0 : sz2 = -1;
2392 0 : for(; offset < static_cast<int>(lightorder.size()); offset++)
2393 : {
2394 0 : const lightinfo &l = lights[lightorder[offset]];
2395 0 : if(l.dist - l.radius > avatarshadowdist)
2396 : {
2397 0 : continue;
2398 : }
2399 0 : if(!n)
2400 : {
2401 0 : shadowmap = l.shadowmap >= 0;
2402 0 : spotlight = l.spot > 0;
2403 : }
2404 0 : else if(n >= lighttilebatch || (l.shadowmap >= 0) != shadowmap || (l.spot > 0) != spotlight)
2405 : {
2406 : break;
2407 : }
2408 0 : setlightparams(n++, l, li);
2409 0 : l.addscissor(sx1, sy1, sx2, sy2, sz1, sz2);
2410 : }
2411 0 : if(baselight)
2412 : {
2413 0 : sx1 = bsx1;
2414 0 : sy1 = bsy1;
2415 0 : sx2 = bsx2;
2416 0 : sy2 = bsy2;
2417 0 : sz1 = -1;
2418 0 : sz2 = 1;
2419 : }
2420 : else
2421 : {
2422 0 : if(!n)
2423 : {
2424 0 : break;
2425 : }
2426 0 : sx1 = std::max(sx1, bsx1);
2427 0 : sy1 = std::max(sy1, bsy1);
2428 0 : sx2 = std::min(sx2, bsx2);
2429 0 : sy2 = std::min(sy2, bsy2);
2430 0 : if(sx1 >= sx2 || sy1 >= sy2 || sz1 >= sz2)
2431 : {
2432 0 : continue;
2433 : }
2434 : }
2435 :
2436 0 : if(n)
2437 : {
2438 0 : setlightshader(&s, li, n, baselight, shadowmap, spotlight, false, true);
2439 : }
2440 : else
2441 : {
2442 0 : s.setvariant(0, 17);
2443 : }
2444 0 : if(hasDBT && depthtestlights > 1)
2445 : {
2446 0 : glDepthBounds_(sz1*0.5f + 0.5f, std::min(sz2*0.5f + 0.5f, depthtestlightsclamp));
2447 : }
2448 0 : lightquad(sz1, sx1, sy1, sx2, sy2, tilemask);
2449 0 : lightpassesused++;
2450 : }
2451 :
2452 0 : setavatarstencil(stencilref, false);
2453 : }
2454 0 : }
2455 :
2456 0 : void GBuffer::renderlights(float bsx1, float bsy1, float bsx2, float bsy2, const uint *tilemask, int stencilmask, int msaapass, bool transparent)
2457 : {
2458 0 : Shader *s = drawtex == Draw_TexMinimap ? deferredminimapshader : (msaapass <= 0 ? deferredlightshader : (msaapass > 1 ? deferredmsaasampleshader : deferredmsaapixelshader));
2459 0 : if(!s || s == nullshader)
2460 : {
2461 0 : return;
2462 : }
2463 :
2464 0 : bool depth = true;
2465 0 : if(!depthtestlights)
2466 : {
2467 0 : glDisable(GL_DEPTH_TEST);
2468 0 : depth = false;
2469 : }
2470 : else
2471 : {
2472 0 : glDepthMask(GL_FALSE);
2473 : }
2474 :
2475 0 : bindlighttexs(msaapass, transparent);
2476 0 : setlightglobals(transparent);
2477 :
2478 0 : gle::defvertex(3);
2479 :
2480 0 : bool avatar = useavatarmask() && !transparent && !drawtex;
2481 0 : int stencilref = -1;
2482 0 : if(msaapass == 1 && ghasstencil)
2483 : {
2484 0 : int tx1 = std::max(static_cast<int>(std::floor((bsx1*0.5f+0.5f)*vieww)), 0),
2485 0 : ty1 = std::max(static_cast<int>(std::floor((bsy1*0.5f+0.5f)*viewh)), 0),
2486 0 : tx2 = std::min(static_cast<int>(std::ceil((bsx2*0.5f+0.5f)*vieww)), vieww),
2487 0 : ty2 = std::min(static_cast<int>(std::ceil((bsy2*0.5f+0.5f)*viewh)), viewh);
2488 0 : glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
2489 0 : if(stencilmask)
2490 : {
2491 0 : glStencilFunc(GL_EQUAL, stencilmask|0x08, 0x07);
2492 : }
2493 : else
2494 : {
2495 0 : glStencilFunc(GL_ALWAYS, 0x08, ~0);
2496 0 : glEnable(GL_STENCIL_TEST);
2497 : }
2498 0 : if(avatar)
2499 : {
2500 0 : glStencilMask(~0x40);
2501 : }
2502 0 : if(depthtestlights && depth)
2503 : {
2504 0 : glDisable(GL_DEPTH_TEST);
2505 0 : depth = false;
2506 : }
2507 0 : glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
2508 0 : SETSHADER(msaaedgedetect);
2509 0 : lightquad(-1, (tx1*2.0f)/vieww-1.0f, (ty1*2.0f)/viewh-1.0f, (tx2*2.0f)/vieww-1.0f, (ty2*2.0f)/viewh-1.0f, tilemask);
2510 0 : glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
2511 0 : glStencilFunc(GL_EQUAL, stencilref = stencilmask, (avatar ? 0x40 : 0) | (msaalight==2 ? 0x07 : 0x0F));
2512 0 : glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
2513 0 : if(avatar)
2514 : {
2515 0 : glStencilMask(~0);
2516 : }
2517 0 : else if(msaalight==2 && !stencilmask)
2518 : {
2519 0 : glDisable(GL_STENCIL_TEST);
2520 : }
2521 0 : }
2522 0 : else if(msaapass == 2)
2523 : {
2524 0 : if(ghasstencil)
2525 : {
2526 0 : glStencilFunc(GL_EQUAL, stencilref = stencilmask|0x08, avatar ? 0x4F : 0x0F);
2527 : }
2528 0 : if(msaalight==2)
2529 : {
2530 0 : glSampleMaski(0, 2); glEnable(GL_SAMPLE_MASK);
2531 : }
2532 : }
2533 0 : else if(ghasstencil && (stencilmask || avatar))
2534 : {
2535 0 : if(!stencilmask)
2536 : {
2537 0 : glEnable(GL_STENCIL_TEST);
2538 : }
2539 0 : glStencilFunc(GL_EQUAL, stencilref = stencilmask, avatar ? 0x4F : 0x0F);
2540 0 : glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
2541 : }
2542 :
2543 0 : if(!avatar)
2544 : {
2545 0 : stencilref = -1;
2546 : }
2547 :
2548 0 : glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
2549 0 : glEnable(GL_BLEND);
2550 :
2551 0 : if(hasDBT && depthtestlights > 1)
2552 : {
2553 0 : glEnable(GL_DEPTH_BOUNDS_TEST_EXT);
2554 : }
2555 :
2556 0 : bool sunpass = !lighttilebatch || drawtex == Draw_TexMinimap || (!sunlight.iszero() && csm.getcsmproperty(CascadedShadowMap::ShadowMap) && batchsunlight <= (gi && giscale && gidist ? 1 : 0));
2557 0 : if(sunpass)
2558 : {
2559 0 : if(depthtestlights && depth)
2560 : {
2561 0 : glDisable(GL_DEPTH_TEST);
2562 0 : depth = false;
2563 : }
2564 0 : rendersunpass(s, stencilref, transparent, bsx1, bsy1, bsx2, bsy2, tilemask);
2565 : }
2566 :
2567 0 : if(depthtestlights && !depth)
2568 : {
2569 0 : glEnable(GL_DEPTH_TEST);
2570 0 : depth = true;
2571 : }
2572 :
2573 0 : if(!lighttilebatch || drawtex == Draw_TexMinimap)
2574 : {
2575 0 : renderlightsnobatch(s, stencilref, transparent, bsx1, bsy1, bsx2, bsy2);
2576 : }
2577 : else
2578 : {
2579 0 : renderlightbatches(*s, stencilref, transparent, bsx1, bsy1, bsx2, bsy2, tilemask);
2580 : }
2581 :
2582 0 : if(msaapass == 1 && ghasstencil)
2583 : {
2584 0 : if(msaalight==2 && !stencilmask && !avatar)
2585 : {
2586 0 : glEnable(GL_STENCIL_TEST);
2587 : }
2588 : }
2589 0 : else if(msaapass == 2)
2590 : {
2591 0 : if(ghasstencil && !stencilmask)
2592 : {
2593 0 : glDisable(GL_STENCIL_TEST);
2594 : }
2595 0 : if(msaalight==2)
2596 : {
2597 0 : glDisable(GL_SAMPLE_MASK);
2598 : }
2599 : }
2600 0 : else if(avatar && !stencilmask)
2601 : {
2602 0 : glDisable(GL_STENCIL_TEST);
2603 : }
2604 :
2605 0 : glDisable(GL_BLEND);
2606 :
2607 0 : if(!depthtestlights)
2608 : {
2609 0 : glEnable(GL_DEPTH_TEST);
2610 : }
2611 : else
2612 : {
2613 0 : glDepthMask(GL_TRUE);
2614 0 : if(hasDBT && depthtestlights > 1)
2615 : {
2616 0 : glDisable(GL_DEPTH_BOUNDS_TEST_EXT);
2617 : }
2618 : }
2619 : }
2620 :
2621 0 : void GBuffer::rendervolumetric()
2622 : {
2623 0 : if(!volumetric || !volumetriclights || !volscale)
2624 : {
2625 0 : return;
2626 : }
2627 0 : float bsx1 = 1,
2628 0 : bsy1 = 1,
2629 0 : bsx2 = -1,
2630 0 : bsy2 = -1;
2631 0 : for(size_t i = 0; i < lightorder.size(); i++)
2632 : {
2633 0 : const lightinfo &l = lights[lightorder[i]];
2634 0 : if(!l.volumetric() || l.checkquery())
2635 : {
2636 0 : continue;
2637 : }
2638 :
2639 0 : l.addscissor(bsx1, bsy1, bsx2, bsy2);
2640 : }
2641 0 : if(bsx1 >= bsx2 || bsy1 >= bsy2)
2642 : {
2643 0 : return;
2644 : }
2645 :
2646 0 : timer *voltimer = begintimer("volumetric lights");
2647 :
2648 0 : glBindFramebuffer(GL_FRAMEBUFFER, volfbo[0]);
2649 0 : glViewport(0, 0, volw, volh);
2650 :
2651 0 : glClearColor(0, 0, 0, 0);
2652 0 : glClear(GL_COLOR_BUFFER_BIT);
2653 :
2654 0 : glActiveTexture(GL_TEXTURE3);
2655 0 : if(msaalight)
2656 : {
2657 0 : glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, msdepthtex);
2658 : }
2659 : else
2660 : {
2661 0 : glBindTexture(GL_TEXTURE_RECTANGLE, gdepthtex);
2662 : }
2663 0 : glActiveTexture(GL_TEXTURE4);
2664 0 : shadowatlas.bind();
2665 0 : shadowatlas.setcomparemode();
2666 0 : glActiveTexture(GL_TEXTURE0);
2667 0 : vec2 sasize = shadowatlaspacker.dimensions();
2668 0 : GLOBALPARAMF(shadowatlasscale, 1.0f/sasize.x, 1.0f/sasize.y);
2669 0 : GLOBALPARAMF(volscale, static_cast<float>(vieww)/volw, static_cast<float>(viewh)/volh, static_cast<float>(volw)/vieww, static_cast<float>(volh)/viewh);
2670 0 : GLOBALPARAMF(volminstep, volminstep);
2671 0 : GLOBALPARAMF(volprefilter, volprefilter);
2672 0 : GLOBALPARAMF(voldistclamp, farplane*voldistclamp);
2673 :
2674 0 : glBlendFunc(GL_ONE, GL_ONE);
2675 0 : glEnable(GL_BLEND);
2676 :
2677 0 : if(!depthtestlights)
2678 : {
2679 0 : glDisable(GL_DEPTH_TEST);
2680 : }
2681 : else
2682 : {
2683 0 : glDepthMask(GL_FALSE);
2684 : }
2685 :
2686 0 : lightsphere::enable();
2687 :
2688 0 : glEnable(GL_SCISSOR_TEST);
2689 :
2690 0 : bool outside = true;
2691 0 : for(size_t i = 0; i < lightorder.size(); i++)
2692 : {
2693 0 : const lightinfo &l = lights[lightorder[i]];
2694 0 : if(!l.volumetric() || l.checkquery())
2695 : {
2696 0 : continue;
2697 : }
2698 :
2699 0 : matrix4 lightmatrix = camprojmatrix;
2700 0 : lightmatrix.translate(l.o);
2701 0 : lightmatrix.scale(l.radius);
2702 0 : GLOBALPARAM(lightmatrix, lightmatrix);
2703 :
2704 0 : if(l.spot > 0)
2705 : {
2706 0 : volumetricshader->setvariant(0, l.shadowmap >= 0 ? 2 : 1);
2707 0 : LOCALPARAM(spotparams, vec4<float>(l.dir, 1/(1 - cos360(l.spot))));
2708 : }
2709 0 : else if(l.shadowmap >= 0)
2710 : {
2711 0 : volumetricshader->setvariant(0, 0);
2712 : }
2713 : else
2714 : {
2715 0 : volumetricshader->set();
2716 : }
2717 :
2718 0 : LOCALPARAM(lightpos, vec4<float>(l.o, 1).div(l.radius));
2719 0 : vec color = vec(l.color).mul(ldrscaleb()).mul(volcolor.tocolor().mul(volscale));
2720 0 : LOCALPARAM(lightcolor, color);
2721 :
2722 0 : if(l.shadowmap >= 0)
2723 : {
2724 0 : ShadowMapInfo &sm = shadowmaps[l.shadowmap];
2725 0 : float smnearclip = SQRT3 / l.radius,
2726 0 : smfarclip = SQRT3,
2727 0 : bias = (smfilter > 2 ? smbias2 : smbias) * (smcullside ? 1 : -1) * smnearclip * (1024.0f / sm.size);
2728 0 : int border = smfilter > 2 ? smborder2 : smborder;
2729 0 : if(l.spot > 0)
2730 : {
2731 0 : LOCALPARAMF(shadowparams,
2732 : 0.5f * sm.size * cotan360(l.spot),
2733 : (-smnearclip * smfarclip / (smfarclip - smnearclip) - 0.5f*bias),
2734 : 1 / (1 + std::fabs(l.dir.z)),
2735 : 0.5f + 0.5f * (smfarclip + smnearclip) / (smfarclip - smnearclip));
2736 : }
2737 : else
2738 : {
2739 0 : LOCALPARAMF(shadowparams,
2740 : 0.5f * (sm.size - border),
2741 : -smnearclip * smfarclip / (smfarclip - smnearclip) - 0.5f*bias,
2742 : sm.size,
2743 : 0.5f + 0.5f * (smfarclip + smnearclip) / (smfarclip - smnearclip));
2744 : }
2745 0 : LOCALPARAMF(shadowoffset, sm.x + 0.5f*sm.size, sm.y + 0.5f*sm.size);
2746 : }
2747 :
2748 0 : int tx1 = static_cast<int>(std::floor((l.sx1*0.5f+0.5f)*volw)),
2749 0 : ty1 = static_cast<int>(std::floor((l.sy1*0.5f+0.5f)*volh)),
2750 0 : tx2 = static_cast<int>(std::ceil((l.sx2*0.5f+0.5f)*volw)),
2751 0 : ty2 = static_cast<int>(std::ceil((l.sy2*0.5f+0.5f)*volh));
2752 0 : glScissor(tx1, ty1, tx2-tx1, ty2-ty1);
2753 :
2754 0 : if(camera1->o.dist(l.o) <= l.radius + nearplane + 1 && depthfaillights)
2755 : {
2756 0 : if(outside)
2757 : {
2758 0 : outside = false;
2759 0 : if(depthtestlights)
2760 : {
2761 0 : glDisable(GL_DEPTH_TEST);
2762 : }
2763 0 : glCullFace(GL_FRONT);
2764 : }
2765 : }
2766 0 : else if(!outside)
2767 : {
2768 0 : outside = true;
2769 0 : if(depthtestlights)
2770 : {
2771 0 : glEnable(GL_DEPTH_TEST);
2772 : }
2773 0 : glCullFace(GL_BACK);
2774 : }
2775 :
2776 0 : lightsphere::draw();
2777 : }
2778 :
2779 0 : if(!outside)
2780 : {
2781 0 : outside = true;
2782 0 : glCullFace(GL_BACK);
2783 : }
2784 :
2785 0 : lightsphere::disable();
2786 :
2787 0 : if(depthtestlights)
2788 : {
2789 0 : glDepthMask(GL_TRUE);
2790 :
2791 0 : glDisable(GL_DEPTH_TEST);
2792 : }
2793 :
2794 0 : int cx1 = static_cast<int>(std::floor((bsx1*0.5f+0.5f)*volw))&~1,
2795 0 : cy1 = static_cast<int>(std::floor((bsy1*0.5f+0.5f)*volh))&~1,
2796 0 : cx2 = (static_cast<int>(std::ceil((bsx2*0.5f+0.5f)*volw))&~1) + 2,
2797 0 : cy2 = (static_cast<int>(std::ceil((bsy2*0.5f+0.5f)*volh))&~1) + 2;
2798 0 : if(volbilateral || volblur)
2799 : {
2800 0 : int radius = (volbilateral ? volbilateral : volblur)*2;
2801 0 : cx1 = std::max(cx1 - radius, 0);
2802 0 : cy1 = std::max(cy1 - radius, 0);
2803 0 : cx2 = std::min(cx2 + radius, volw);
2804 0 : cy2 = std::min(cy2 + radius, volh);
2805 0 : glScissor(cx1, cy1, cx2-cx1, cy2-cy1);
2806 :
2807 0 : glDisable(GL_BLEND);
2808 :
2809 0 : if(volbilateral)
2810 : {
2811 0 : for(int i = 0; i < 2; ++i)
2812 : {
2813 0 : glBindFramebuffer(GL_FRAMEBUFFER, volfbo[(i+1)%2]);
2814 0 : glViewport(0, 0, volw, volh);
2815 0 : volumetricbilateralshader[i]->set();
2816 0 : setbilateralparams(volbilateral, volbilateraldepth);
2817 0 : glBindTexture(GL_TEXTURE_RECTANGLE, voltex[i%2]);
2818 0 : screenquadoffset(0.25f, 0.25f, vieww, viewh);
2819 : }
2820 : }
2821 : else
2822 : {
2823 : std::array<float, maxblurradius+1> blurweights,
2824 : bluroffsets;
2825 0 : setupblurkernel(volblur, blurweights, bluroffsets);
2826 0 : for(int i = 0; i < 2; ++i)
2827 : {
2828 0 : glBindFramebuffer(GL_FRAMEBUFFER, volfbo[(i+1)%2]);
2829 0 : glViewport(0, 0, volw, volh);
2830 0 : setblurshader(i%2, 1, volblur, blurweights, bluroffsets, GL_TEXTURE_RECTANGLE);
2831 0 : glBindTexture(GL_TEXTURE_RECTANGLE, voltex[i%2]);
2832 0 : screenquad(volw, volh);
2833 : }
2834 : }
2835 :
2836 0 : glEnable(GL_BLEND);
2837 : }
2838 :
2839 0 : glBindFramebuffer(GL_FRAMEBUFFER, msaalight ? mshdrfbo : hdrfbo);
2840 0 : glViewport(0, 0, vieww, viewh);
2841 :
2842 0 : int margin = (1<<volreduce) - 1;
2843 0 : cx1 = std::max((cx1 * vieww) / volw - margin, 0);
2844 0 : cy1 = std::max((cy1 * viewh) / volh - margin, 0);
2845 0 : cx2 = std::min((cx2 * vieww + margin + volw - 1) / volw, vieww);
2846 0 : cy2 = std::min((cy2 * viewh + margin + volh - 1) / volh, viewh);
2847 0 : glScissor(cx1, cy1, cx2-cx1, cy2-cy1);
2848 :
2849 0 : bool avatar = useavatarmask();
2850 0 : if(avatar)
2851 : {
2852 0 : glStencilFunc(GL_EQUAL, 0, 0x40);
2853 0 : glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
2854 0 : glEnable(GL_STENCIL_TEST);
2855 : }
2856 :
2857 0 : SETSHADER(scalelinear);
2858 0 : glBindTexture(GL_TEXTURE_RECTANGLE, voltex[0]);
2859 0 : screenquad(volw, volh);
2860 :
2861 0 : if(volbilateral || volblur)
2862 : {
2863 0 : std::swap(volfbo[0], volfbo[1]);
2864 0 : std::swap(voltex[0], voltex[1]);
2865 : }
2866 :
2867 0 : if(avatar)
2868 : {
2869 0 : glDisable(GL_STENCIL_TEST);
2870 : }
2871 :
2872 0 : glDisable(GL_SCISSOR_TEST);
2873 :
2874 0 : glEnable(GL_DEPTH_TEST);
2875 :
2876 0 : glDisable(GL_BLEND);
2877 :
2878 0 : endtimer(voltimer);
2879 : }
2880 :
2881 : static VAR(oqvol, 0, 1, 1); //`o`cclusion `q`uery `vol`umetrics: toggles occlusion queries of volumetric lights
2882 : static VAR(oqlights, 0, 1, 1); //`o`cclusion `q`uery `lights: toggles occlusion queries of lights behind geometry
2883 : static VAR(debuglightscissor, 0, 0, 1); //displays the light scissor map in the corner of the screen
2884 :
2885 0 : static void viewlightscissor()
2886 : {
2887 0 : std::vector<extentity *> &ents = entities::getents();
2888 0 : gle::defvertex(2);
2889 0 : for(size_t i = 0; i < entgroup.size(); i++)
2890 : {
2891 0 : size_t idx = entgroup[i];
2892 0 : if((ents.size() > idx) && ents[idx]->type == EngineEnt_Light)
2893 : {
2894 0 : const extentity &e = *ents[idx];
2895 0 : for(size_t j = 0; j < lights.size(); j++)
2896 : {
2897 0 : if(lights[j].o == e.o)
2898 : {
2899 0 : const lightinfo &l = lights[j];
2900 0 : if(!l.validscissor())
2901 : {
2902 0 : break;
2903 : }
2904 0 : gle::colorf(l.color.x/255, l.color.y/255, l.color.z/255);
2905 0 : float x1 = (l.sx1+1)/2*hudw(),
2906 0 : x2 = (l.sx2+1)/2*hudw(),
2907 0 : y1 = (1-l.sy1)/2*hudh(),
2908 0 : y2 = (1-l.sy2)/2*hudh();
2909 0 : gle::begin(GL_TRIANGLE_STRIP);
2910 0 : gle::attribf(x1, y1);
2911 0 : gle::attribf(x2, y1);
2912 0 : gle::attribf(x1, y2);
2913 0 : gle::attribf(x2, y2);
2914 0 : gle::end();
2915 : }
2916 : }
2917 : }
2918 : }
2919 0 : }
2920 :
2921 0 : void collectlights()
2922 : {
2923 0 : if(lights.size())
2924 : {
2925 0 : return;
2926 : }
2927 :
2928 : // point lights processed here
2929 0 : const std::vector<extentity *> &ents = entities::getents();
2930 0 : if(!editmode || !fullbright)
2931 : {
2932 0 : for(size_t i = 0; i < ents.size(); i++)
2933 : {
2934 0 : const extentity *e = ents[i];
2935 0 : if(e->type != EngineEnt_Light || e->attr1 <= 0)
2936 : {
2937 0 : continue;
2938 : }
2939 0 : if(smviscull && view.isfoggedsphere(e->attr1, e->o))
2940 : {
2941 0 : continue;
2942 : }
2943 0 : lightinfo l = lightinfo(i, *e);
2944 0 : lights.push_back(l);
2945 0 : if(l.validscissor())
2946 : {
2947 0 : lightorder.emplace_back(lights.size()-1);
2948 : }
2949 : }
2950 : }
2951 :
2952 0 : size_t numdynlights = 0;
2953 0 : if(!drawtex)
2954 : {
2955 0 : updatedynlights();
2956 0 : numdynlights = finddynlights();
2957 : }
2958 0 : for(size_t i = 0; i < numdynlights; ++i)
2959 : {
2960 0 : vec o, color, dir;
2961 : float radius;
2962 : int spot, flags;
2963 0 : if(!getdynlight(i, o, radius, color, dir, spot, flags))
2964 : {
2965 0 : continue;
2966 : }
2967 0 : const lightinfo &l = lights.emplace_back(lightinfo(o, vec(color).mul(255).max(0), radius, flags, dir, spot));
2968 0 : if(l.validscissor())
2969 : {
2970 0 : lightorder.emplace_back(lights.size()-1);
2971 : }
2972 : }
2973 :
2974 0 : std::sort(lightorder.begin(), lightorder.end(), sortlights);
2975 :
2976 0 : bool queried = false;
2977 0 : if(!drawtex && smquery && oqfrags && oqlights)
2978 : {
2979 0 : for(size_t i = 0; i < lightorder.size(); i++)
2980 : {
2981 0 : int idx = lightorder[i];
2982 0 : lightinfo &l = lights[idx];
2983 0 : if((l.noshadow() && (!oqvol || !l.volumetric())) || l.radius >= rootworld.mapsize())
2984 : {
2985 0 : continue;
2986 : }
2987 0 : vec bbmin, bbmax;
2988 0 : l.calcbb(bbmin, bbmax);
2989 0 : if(!camera1->o.insidebb(bbmin, bbmax, 2))
2990 : {
2991 0 : l.query = occlusionengine.newquery(&l);
2992 0 : if(l.query)
2993 : {
2994 0 : if(!queried)
2995 : {
2996 0 : startbb(false);
2997 0 : queried = true;
2998 : }
2999 0 : l.query->startquery();
3000 0 : ivec bo(bbmin),
3001 0 : br = ivec(bbmax).sub(bo).add(1);
3002 0 : drawbb(bo, br);
3003 0 : occlusionengine.endquery();
3004 : }
3005 : }
3006 : }
3007 : }
3008 0 : if(queried)
3009 : {
3010 0 : endbb(false);
3011 0 : glFlush();
3012 : }
3013 :
3014 0 : smused = 0;
3015 :
3016 0 : if(smcache && !smnoshadow && shadowatlas.cache.size())
3017 : {
3018 0 : for(int mismatched = 0; mismatched < 2; ++mismatched)
3019 : {
3020 0 : for(size_t i = 0; i < lightorder.size(); i++)
3021 : {
3022 0 : int idx = lightorder[i];
3023 0 : lightinfo &l = lights[idx];
3024 0 : if(l.noshadow())
3025 : {
3026 0 : continue;
3027 : }
3028 0 : auto itr = shadowatlas.cache.find(l);
3029 0 : if(itr == shadowatlas.cache.end())
3030 : {
3031 0 : continue;
3032 : }
3033 0 : float prec = smprec,
3034 : lod;
3035 : int w, h;
3036 0 : if(l.spot)
3037 : {
3038 0 : w = 1;
3039 0 : h = 1;
3040 0 : prec *= tan360(l.spot);
3041 0 : lod = smspotprec;
3042 : }
3043 : else
3044 : {
3045 0 : w = 3;
3046 0 : h = 2;
3047 0 : lod = smcubeprec;
3048 : }
3049 0 : lod *= std::clamp(l.radius * prec / sqrtf(std::max(1.0f, l.dist/l.radius)), static_cast<float>(smminsize), static_cast<float>(smmaxsize));
3050 0 : const float sasizex = shadowatlaspacker.dimensions().x;
3051 0 : int size = std::clamp(static_cast<int>(std::ceil((lod * sasizex) / shadowatlassize)), 1, static_cast<int>(sasizex) / w);
3052 0 : w *= size;
3053 0 : h *= size;
3054 0 : const shadowcacheval &cached = (*itr).second;
3055 0 : if(mismatched)
3056 : {
3057 0 : if(cached.size == size)
3058 : {
3059 0 : continue;
3060 : }
3061 0 : ushort x = USHRT_MAX,
3062 0 : y = USHRT_MAX;
3063 0 : if(!shadowatlaspacker.insert(x, y, w, h))
3064 : {
3065 0 : continue;
3066 : }
3067 0 : addshadowmap(x, y, size, l.shadowmap, idx);
3068 : }
3069 : else
3070 : {
3071 0 : if(cached.size != size)
3072 : {
3073 0 : continue;
3074 : }
3075 0 : ushort x = cached.x,
3076 0 : y = cached.y;
3077 0 : shadowatlaspacker.reserve(x, y, w, h);
3078 0 : addshadowmap(x, y, size, l.shadowmap, idx, &cached);
3079 : }
3080 0 : smused += w*h;
3081 : }
3082 : }
3083 : }
3084 : }
3085 :
3086 : static VAR(csminoq, 0, 1, 1); //cascaded shadow maps in occlusion queries
3087 : static VAR(sminoq, 0, 1, 1); //shadow maps in occlusion queries
3088 : VAR(rhinoq, 0, 1, 1); //radiance hints in occlusion queries
3089 :
3090 0 : bool shouldworkinoq()
3091 : {
3092 0 : return !drawtex && oqfrags && (!wireframe || !editmode);
3093 : }
3094 :
3095 : struct BatchRect final : LightRect
3096 : {
3097 : uchar group;
3098 : ushort idx;
3099 :
3100 : BatchRect() {}
3101 0 : BatchRect(const lightinfo &l, ushort idx)
3102 0 : : LightRect(l),
3103 0 : group((l.shadowmap < 0 ? BatchFlag_NoShadow : 0) | (l.spot > 0 ? BatchFlag_Spotlight : 0)),
3104 0 : idx(idx)
3105 0 : {}
3106 : };
3107 :
3108 : struct BatchStack final : LightRect
3109 : {
3110 : ushort offset, numrects;
3111 : uchar flags;
3112 :
3113 : BatchStack() {}
3114 0 : BatchStack(uchar x1, uchar y1, uchar x2, uchar y2, ushort offset, ushort numrects, uchar flags = 0) : LightRect(x1, y1, x2, y2), offset(offset), numrects(numrects), flags(flags) {}
3115 : };
3116 :
3117 0 : static void batchlights(const BatchStack &initstack, std::vector<BatchRect> &batchrects, int &lightbatchstacksused, int &lightbatchrectsused)
3118 : {
3119 0 : constexpr size_t stacksize = 32;
3120 0 : std::stack<BatchStack> stack;
3121 0 : stack.push(initstack);
3122 :
3123 0 : while(stack.size() > 0)
3124 : {
3125 0 : const BatchStack s = stack.top();
3126 0 : stack.pop();
3127 0 : if(stack.size() + 5 > stacksize)
3128 : {
3129 0 : batchlights(s, batchrects, lightbatchstacksused, lightbatchrectsused);
3130 0 : continue;
3131 : }
3132 0 : ++lightbatchstacksused;
3133 0 : int groups[BatchFlag_NoSun] = { 0 };
3134 0 : LightRect split(s);
3135 0 : ushort splitidx = USHRT_MAX;
3136 0 : int outside = s.offset,
3137 0 : inside = s.offset + s.numrects;
3138 0 : for(int i = outside; i < inside; ++i)
3139 : {
3140 0 : const BatchRect &r = batchrects[i];
3141 0 : if(r.outside(s))
3142 : {
3143 0 : if(i != outside)
3144 : {
3145 0 : std::swap(batchrects[i], batchrects[outside]);
3146 : }
3147 0 : ++outside;
3148 : }
3149 0 : else if(s.inside(r))
3150 : {
3151 0 : ++groups[r.group];
3152 0 : std::swap(batchrects[i--], batchrects[--inside]);
3153 : }
3154 0 : else if(r.idx < splitidx)
3155 : {
3156 0 : split = r;
3157 0 : splitidx = r.idx;
3158 : }
3159 : }
3160 :
3161 0 : uchar flags = s.flags;
3162 0 : int batched = s.offset + s.numrects;
3163 0 : for(int g = 0; g < BatchFlag_NoShadow; ++g)
3164 : {
3165 0 : while(groups[g] >= lighttilebatch || (inside == outside && (groups[g] || !(flags & BatchFlag_NoSun))))
3166 : {
3167 0 : LightBatch key;
3168 0 : key.flags = flags | g;
3169 0 : flags |= BatchFlag_NoSun;
3170 :
3171 0 : int n = std::min(groups[g], lighttilebatch);
3172 0 : groups[g] -= n;
3173 0 : key.numlights = n;
3174 0 : for(int i = 0; i < n; ++i)
3175 : {
3176 0 : int best = -1;
3177 0 : ushort bestidx = USHRT_MAX;
3178 0 : for(int j = inside; j < batched; ++j)
3179 : {
3180 0 : const BatchRect &r = batchrects[j];
3181 : {
3182 0 : if(r.group == g && r.idx < bestidx)
3183 : {
3184 0 : best = j;
3185 0 : bestidx = r.idx;
3186 : }
3187 : }
3188 : }
3189 0 : key.lights[i] = lightorder[bestidx];
3190 0 : std::swap(batchrects[best], batchrects[--batched]);
3191 : }
3192 :
3193 0 : key.rects.push_back(s);
3194 0 : lightbatches.push_back(std::move(key));
3195 0 : ++lightbatchrectsused;
3196 0 : }
3197 : }
3198 0 : if(splitidx != USHRT_MAX)
3199 : {
3200 0 : int numoverlap = batched - outside;
3201 0 : split.intersect(s);
3202 :
3203 0 : if(split.y1 > s.y1)
3204 : {
3205 0 : stack.push(BatchStack(s.x1, s.y1, s.x2, split.y1, outside, numoverlap, flags));
3206 : }
3207 0 : if(split.x1 > s.x1)
3208 : {
3209 0 : stack.push(BatchStack(s.x1, split.y1, split.x1, split.y2, outside, numoverlap, flags));
3210 : }
3211 0 : stack.push(BatchStack(split.x1, split.y1, split.x2, split.y2, outside, numoverlap, flags));
3212 0 : if(split.x2 < s.x2)
3213 : {
3214 0 : stack.push(BatchStack(split.x2, split.y1, s.x2, split.y2, outside, numoverlap, flags));
3215 : }
3216 0 : if(split.y2 < s.y2)
3217 : {
3218 0 : stack.push(BatchStack(s.x1, split.y2, s.x2, s.y2, outside, numoverlap, flags));
3219 : }
3220 : }
3221 : }
3222 0 : }
3223 :
3224 0 : static bool sortlightbatches(const LightBatch &x, const LightBatch &y)
3225 : {
3226 0 : if(x.flags < y.flags)
3227 : {
3228 0 : return true;
3229 : }
3230 0 : if(x.flags > y.flags)
3231 : {
3232 0 : return false;
3233 : }
3234 0 : return x.numlights > y.numlights;
3235 : }
3236 :
3237 0 : static void batchlights(std::vector<BatchRect> &batchrects, int &lightbatchstacksused, int &lightbatchrectsused, int &lightbatchesused)
3238 : {
3239 0 : lightbatches.clear();
3240 0 : lightbatchstacksused = 0;
3241 0 : lightbatchrectsused = 0;
3242 :
3243 0 : if(lighttilebatch && drawtex != Draw_TexMinimap)
3244 : {
3245 0 : batchlights(BatchStack(0, 0, lighttilew, lighttileh, 0, batchrects.size()), batchrects, lightbatchstacksused, lightbatchrectsused);
3246 0 : std::sort(lightbatches.begin(), lightbatches.end(), sortlightbatches);
3247 : }
3248 :
3249 0 : lightbatchesused = lightbatches.size();
3250 0 : }
3251 :
3252 0 : void GBuffer::packlights()
3253 : {
3254 0 : lightsvisible = lightsoccluded = 0;
3255 0 : lightpassesused = 0;
3256 0 : std::vector<BatchRect> batchrects;
3257 :
3258 0 : for(size_t i = 0; i < lightorder.size(); i++)
3259 : {
3260 0 : int idx = lightorder[i];
3261 0 : lightinfo &l = lights[idx];
3262 0 : if(l.checkquery())
3263 : {
3264 0 : if(l.shadowmap >= 0)
3265 : {
3266 0 : shadowmaps[l.shadowmap].light = -1;
3267 0 : l.shadowmap = -1;
3268 : }
3269 0 : lightsoccluded++;
3270 0 : continue;
3271 : }
3272 :
3273 0 : if(!l.noshadow() && !smnoshadow && l.shadowmap < 0)
3274 : {
3275 0 : float prec = smprec,
3276 : lod;
3277 : int w, h;
3278 0 : if(l.spot)
3279 : {
3280 0 : w = 1;
3281 0 : h = 1;
3282 0 : prec *= tan360(l.spot);
3283 0 : lod = smspotprec;
3284 : }
3285 : else
3286 : {
3287 0 : w = 3;
3288 0 : h = 2;
3289 0 : lod = smcubeprec;
3290 : }
3291 0 : lod *= std::clamp(l.radius * prec / sqrtf(std::max(1.0f, l.dist/l.radius)), static_cast<float>(smminsize), static_cast<float>(smmaxsize));
3292 0 : const float sasizex = shadowatlaspacker.dimensions().x;
3293 0 : int size = std::clamp(static_cast<int>(std::ceil((lod * sasizex) / shadowatlassize)), 1, static_cast<int>(sasizex) / w);
3294 0 : w *= size;
3295 0 : h *= size;
3296 0 : ushort x = USHRT_MAX,
3297 0 : y = USHRT_MAX;
3298 0 : if(shadowatlaspacker.insert(x, y, w, h))
3299 : {
3300 0 : addshadowmap(x, y, size, l.shadowmap, idx);
3301 0 : smused += w*h;
3302 : }
3303 0 : else if(smcache)
3304 : {
3305 0 : shadowatlas.full = true;
3306 : }
3307 : }
3308 0 : batchrects.emplace_back(l, i);
3309 : }
3310 :
3311 0 : lightsvisible = lightorder.size() - lightsoccluded;
3312 :
3313 0 : batchlights(batchrects, lightbatchstacksused, lightbatchrectsused, lightbatchesused);
3314 0 : }
3315 :
3316 0 : void GBuffer::rendercsmshadowmaps() const
3317 : {
3318 0 : if(sunlight.iszero() || !csm.getcsmproperty(CascadedShadowMap::ShadowMap))
3319 : {
3320 0 : return;
3321 : }
3322 0 : if(inoq)
3323 : {
3324 0 : glBindFramebuffer(GL_FRAMEBUFFER, shadowatlas.fbo);
3325 0 : glDepthMask(GL_TRUE);
3326 : }
3327 0 : csm.setup();
3328 0 : shadowmapping = ShadowMap_Cascade;
3329 0 : shadoworigin = vec(0, 0, 0);
3330 0 : shadowdir = csm.getlightview();
3331 0 : shadowbias = csm.getlightview().project_bb(worldmin, worldmax);
3332 0 : shadowradius = std::fabs(csm.getlightview().project_bb(worldmax, worldmin));
3333 :
3334 0 : float polyfactor = csm.getcsmproperty(CascadedShadowMap::PolyFactor),
3335 0 : polyoffset = csm.getcsmproperty(CascadedShadowMap::PolyOffset);
3336 0 : if(smfilter > 2)
3337 : {
3338 0 : csm.setcsmproperty(CascadedShadowMap::PolyFactor, csm.getcsmproperty(CascadedShadowMap::PolyFactor2));
3339 0 : csm.setcsmproperty(CascadedShadowMap::PolyOffset, csm.getcsmproperty(CascadedShadowMap::PolyOffset2));
3340 : }
3341 0 : if(polyfactor || polyoffset)
3342 : {
3343 0 : glPolygonOffset(polyfactor, polyoffset);
3344 0 : glEnable(GL_POLYGON_OFFSET_FILL);
3345 : }
3346 0 : glEnable(GL_SCISSOR_TEST);
3347 :
3348 0 : findshadowvas();
3349 0 : findshadowmms();
3350 :
3351 0 : batching::shadowmaskbatchedmodels(smdynshadow!=0);
3352 0 : batchshadowmapmodels();
3353 :
3354 0 : for(int i = 0; i < csm.getcsmproperty(CascadedShadowMap::Splits); ++i)
3355 : {
3356 0 : if(csm.splits[i].idx >= 0)
3357 : {
3358 0 : const ShadowMapInfo &sm = shadowmaps[csm.splits[i].idx];
3359 :
3360 0 : shadowmatrix.mul(csm.splits[i].proj, csm.getmodel());
3361 0 : GLOBALPARAM(shadowmatrix, shadowmatrix);
3362 :
3363 0 : glViewport(sm.x, sm.y, sm.size, sm.size);
3364 0 : glScissor(sm.x, sm.y, sm.size, sm.size);
3365 0 : glClear(GL_DEPTH_BUFFER_BIT);
3366 :
3367 0 : shadowside = i;
3368 :
3369 0 : rendershadowmapworld();
3370 0 : batching::rendershadowmodelbatches();
3371 : }
3372 : }
3373 :
3374 0 : batching::clearbatchedmapmodels();
3375 :
3376 0 : glDisable(GL_SCISSOR_TEST);
3377 :
3378 0 : if(polyfactor || polyoffset)
3379 : {
3380 0 : glDisable(GL_POLYGON_OFFSET_FILL);
3381 : }
3382 0 : shadowmapping = 0;
3383 :
3384 0 : if(inoq)
3385 : {
3386 0 : glBindFramebuffer(GL_FRAMEBUFFER, msaasamples ? msfbo : gfbo);
3387 0 : glViewport(0, 0, vieww, viewh);
3388 :
3389 0 : glFlush();
3390 : }
3391 : }
3392 :
3393 0 : int calcshadowinfo(const extentity &e, vec &origin, float &radius, vec &spotloc, int &spotangle, float &bias)
3394 : {
3395 0 : if(e.attr5&LightEnt_NoShadow || e.attr1 <= smminradius)
3396 : {
3397 0 : return ShadowMap_None;
3398 : }
3399 0 : origin = e.o;
3400 0 : radius = e.attr1;
3401 : int type, w, border;
3402 : float lod;
3403 0 : if(e.attached && e.attached->type == EngineEnt_Spotlight)
3404 : {
3405 0 : type = ShadowMap_Spot;
3406 0 : w = 1;
3407 0 : border = 0;
3408 0 : lod = smspotprec;
3409 0 : spotloc = e.attached->o;
3410 0 : spotangle = std::clamp(static_cast<int>(e.attached->attr1), 1, 89);
3411 : }
3412 : else
3413 : {
3414 0 : type = ShadowMap_CubeMap;
3415 0 : w = 3;
3416 0 : lod = smcubeprec;
3417 0 : border = smfilter > 2 ? smborder2 : smborder;
3418 0 : spotloc = e.o;
3419 0 : spotangle = 0;
3420 : }
3421 :
3422 0 : lod *= smminsize;
3423 0 : const float sasizex = shadowatlaspacker.dimensions().x;
3424 0 : int size = std::clamp(static_cast<int>(std::ceil((lod * sasizex) / shadowatlassize)), 1, static_cast<int>(sasizex) / w);
3425 0 : bias = border / static_cast<float>(size - border);
3426 :
3427 0 : return type;
3428 : }
3429 :
3430 : matrix4 shadowmatrix;
3431 :
3432 0 : void GBuffer::rendershadowmaps(int offset) const
3433 : {
3434 0 : if(!(sminoq && !debugshadowatlas && !inoq && shouldworkinoq()))
3435 : {
3436 0 : offset = 0;
3437 : }
3438 :
3439 0 : for(; offset < static_cast<int>(shadowmaps.size()); offset++)
3440 : {
3441 0 : if(shadowmaps[offset].light >= 0)
3442 : {
3443 0 : break;
3444 : }
3445 : }
3446 :
3447 0 : if(offset >= static_cast<int>(shadowmaps.size()))
3448 : {
3449 0 : return;
3450 : }
3451 :
3452 0 : if(inoq)
3453 : {
3454 0 : glBindFramebuffer(GL_FRAMEBUFFER, shadowatlas.fbo);
3455 0 : glDepthMask(GL_TRUE);
3456 : }
3457 :
3458 0 : float polyfactor = smpolyfactor,
3459 0 : polyoffset = smpolyoffset;
3460 0 : if(smfilter > 2)
3461 : {
3462 0 : polyfactor = smpolyfactor2;
3463 0 : polyoffset = smpolyoffset2;
3464 : }
3465 0 : if(polyfactor || polyoffset)
3466 : {
3467 0 : glPolygonOffset(polyfactor, polyoffset);
3468 0 : glEnable(GL_POLYGON_OFFSET_FILL);
3469 : }
3470 :
3471 0 : glEnable(GL_SCISSOR_TEST);
3472 :
3473 0 : const std::vector<extentity *> &ents = entities::getents();
3474 0 : for(size_t i = offset; i < shadowmaps.size(); i++)
3475 : {
3476 0 : ShadowMapInfo &sm = shadowmaps[i];
3477 0 : if(sm.light < 0)
3478 : {
3479 0 : continue;
3480 : }
3481 0 : const lightinfo &l = lights[sm.light];
3482 0 : const extentity *e = l.ent >= 0 ? ents[l.ent] : nullptr;
3483 : int border, sidemask;
3484 0 : if(l.spot)
3485 : {
3486 0 : shadowmapping = ShadowMap_Spot;
3487 0 : border = 0;
3488 0 : sidemask = 1;
3489 : }
3490 : else
3491 : {
3492 0 : shadowmapping = ShadowMap_CubeMap;
3493 0 : border = smfilter > 2 ? smborder2 : smborder;
3494 0 : sidemask = drawtex == Draw_TexMinimap ? 0x2F : (smsidecull ? view.cullfrustumsides(l.o, l.radius, sm.size, border) : 0x3F);
3495 : }
3496 :
3497 0 : sm.sidemask = sidemask;
3498 :
3499 0 : shadoworigin = l.o;
3500 0 : shadowradius = l.radius;
3501 0 : shadowbias = border / static_cast<float>(sm.size - border);
3502 0 : shadowdir = l.dir;
3503 0 : shadowspot = l.spot;
3504 :
3505 0 : const shadowmesh *mesh = e ? findshadowmesh(l.ent, *e) : nullptr;
3506 :
3507 0 : findshadowvas();
3508 0 : findshadowmms();
3509 :
3510 0 : batching::shadowmaskbatchedmodels(!(l.flags&LightEnt_Static) && smdynshadow);
3511 0 : batchshadowmapmodels(mesh != nullptr);
3512 :
3513 0 : const shadowcacheval *cached = nullptr;
3514 0 : int cachemask = 0;
3515 0 : if(smcache)
3516 : {
3517 0 : int dynmask = smcache <= 1 ? batching::batcheddynamicmodels() : 0;
3518 0 : cached = sm.cached;
3519 0 : if(cached)
3520 : {
3521 0 : if(!debugshadowatlas)
3522 : {
3523 0 : cachemask = cached->sidemask & ~dynmask;
3524 : }
3525 0 : sm.sidemask |= cachemask;
3526 : }
3527 0 : sm.sidemask &= ~dynmask;
3528 :
3529 0 : sidemask &= ~cachemask;
3530 0 : if(!sidemask)
3531 : {
3532 0 : batching::clearbatchedmapmodels();
3533 0 : continue;
3534 : }
3535 : }
3536 :
3537 0 : float smnearclip = SQRT3 / l.radius,
3538 0 : smfarclip = SQRT3;
3539 0 : matrix4 smprojmatrix(vec4<float>(static_cast<float>(sm.size - border) / sm.size, 0, 0, 0),
3540 0 : vec4<float>(0, static_cast<float>(sm.size - border) / sm.size, 0, 0),
3541 0 : vec4<float>(0, 0, -(smfarclip + smnearclip) / (smfarclip - smnearclip), -1),
3542 0 : vec4<float>(0, 0, -2*smnearclip*smfarclip / (smfarclip - smnearclip), 0));
3543 :
3544 0 : if(shadowmapping == ShadowMap_Spot)
3545 : {
3546 0 : glViewport(sm.x, sm.y, sm.size, sm.size);
3547 0 : glScissor(sm.x, sm.y, sm.size, sm.size);
3548 0 : glClear(GL_DEPTH_BUFFER_BIT);
3549 :
3550 0 : float invradius = 1.0f / l.radius,
3551 0 : spotscale = invradius * cotan360(l.spot);
3552 0 : matrix4 spotmatrix(vec(l.spotx).mul(spotscale), vec(l.spoty).mul(spotscale), vec(l.dir).mul(-invradius));
3553 0 : spotmatrix.translate(vec(l.o).neg());
3554 0 : shadowmatrix.mul(smprojmatrix, spotmatrix);
3555 0 : GLOBALPARAM(shadowmatrix, shadowmatrix);
3556 :
3557 0 : glCullFace((l.dir.z >= 0) == (smcullside != 0) ? GL_BACK : GL_FRONT);
3558 :
3559 0 : shadowside = 0;
3560 :
3561 0 : if(mesh)
3562 : {
3563 0 : rendershadowmesh(mesh);
3564 : }
3565 : else
3566 : {
3567 0 : rendershadowmapworld();
3568 : }
3569 0 : batching::rendershadowmodelbatches();
3570 : }
3571 : else
3572 : {
3573 0 : if(!cachemask)
3574 : {
3575 0 : int cx1 = sidemask & 0x03 ? 0 : (sidemask & 0xC ? sm.size : 2 * sm.size),
3576 0 : cx2 = sidemask & 0x30 ? 3 * sm.size : (sidemask & 0xC ? 2 * sm.size : sm.size),
3577 0 : cy1 = sidemask & 0x15 ? 0 : sm.size,
3578 0 : cy2 = sidemask & 0x2A ? 2 * sm.size : sm.size;
3579 0 : glScissor(sm.x + cx1, sm.y + cy1, cx2 - cx1, cy2 - cy1);
3580 0 : glClear(GL_DEPTH_BUFFER_BIT);
3581 : }
3582 0 : for(int side = 0; side < 6; ++side)
3583 : {
3584 0 : if(sidemask&(1<<side))
3585 : {
3586 0 : int sidex = (side>>1)*sm.size,
3587 0 : sidey = (side&1)*sm.size;
3588 0 : glViewport(sm.x + sidex, sm.y + sidey, sm.size, sm.size);
3589 0 : glScissor(sm.x + sidex, sm.y + sidey, sm.size, sm.size);
3590 0 : if(cachemask)
3591 : {
3592 0 : glClear(GL_DEPTH_BUFFER_BIT);
3593 : }
3594 0 : matrix4 cubematrix(cubeshadowviewmatrix[side]);
3595 0 : cubematrix.scale(1.0f/l.radius);
3596 0 : cubematrix.translate(vec(l.o).neg());
3597 0 : shadowmatrix.mul(smprojmatrix, cubematrix);
3598 0 : GLOBALPARAM(shadowmatrix, shadowmatrix);
3599 :
3600 0 : glCullFace((side & 1) ^ (side >> 2) ^ smcullside ? GL_FRONT : GL_BACK);
3601 :
3602 0 : shadowside = side;
3603 :
3604 0 : if(mesh)
3605 : {
3606 0 : rendershadowmesh(mesh);
3607 : }
3608 : else
3609 : {
3610 0 : rendershadowmapworld();
3611 : }
3612 0 : batching::rendershadowmodelbatches();
3613 : }
3614 : }
3615 : }
3616 :
3617 0 : batching::clearbatchedmapmodels();
3618 : }
3619 :
3620 0 : glCullFace(GL_BACK);
3621 0 : glDisable(GL_SCISSOR_TEST);
3622 :
3623 0 : if(polyfactor || polyoffset)
3624 : {
3625 0 : glDisable(GL_POLYGON_OFFSET_FILL);
3626 : }
3627 0 : shadowmapping = 0;
3628 0 : if(inoq)
3629 : {
3630 0 : glBindFramebuffer(GL_FRAMEBUFFER, msaasamples ? msfbo : gfbo);
3631 0 : glViewport(0, 0, vieww, viewh);
3632 :
3633 0 : glFlush();
3634 : }
3635 : }
3636 :
3637 0 : void GBuffer::rendershadowatlas()
3638 : {
3639 0 : timer *smcputimer = begintimer("shadow map", false),
3640 0 : *smtimer = begintimer("shadow map");
3641 :
3642 0 : glBindFramebuffer(GL_FRAMEBUFFER, shadowatlas.fbo);
3643 0 : glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
3644 :
3645 0 : if(debugshadowatlas)
3646 : {
3647 0 : glClearDepth(0);
3648 0 : glClear(GL_DEPTH_BUFFER_BIT);
3649 0 : glClearDepth(1);
3650 : }
3651 :
3652 : // sun light
3653 0 : if(!csminoq || debugshadowatlas || inoq || !shouldworkinoq())
3654 : {
3655 0 : rendercsmshadowmaps();
3656 : }
3657 :
3658 0 : const int smoffset = shadowmaps.size();
3659 :
3660 0 : packlights();
3661 :
3662 : // point lights
3663 0 : rendershadowmaps(smoffset);
3664 :
3665 0 : glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
3666 :
3667 0 : endtimer(smtimer);
3668 0 : endtimer(smcputimer);
3669 0 : }
3670 :
3671 0 : void GBuffer::workinoq()
3672 : {
3673 0 : collectlights();
3674 :
3675 0 : if(drawtex)
3676 : {
3677 0 : return;
3678 : }
3679 :
3680 0 : if(shouldworkinoq())
3681 : {
3682 0 : inoq = true;
3683 :
3684 0 : if(csminoq && !debugshadowatlas)
3685 : {
3686 0 : rendercsmshadowmaps();
3687 : }
3688 0 : if(sminoq && !debugshadowatlas)
3689 : {
3690 0 : rendershadowmaps();
3691 : }
3692 0 : if(rhinoq)
3693 : {
3694 0 : renderradiancehints();
3695 : }
3696 :
3697 0 : inoq = false;
3698 : }
3699 : }
3700 :
3701 : static VAR(gdepthclear, 0, 1, 1); //toggles whether to clear the g depth buffer to 0000/1111 (black or white depending on gdepthformat) upon creation
3702 : static VAR(gcolorclear, 0, 1, 1); //toggles whether to clear the g buffer to 0,0,0,0 (black) upon creation
3703 :
3704 0 : void GBuffer::preparegbuffer(bool depthclear)
3705 : {
3706 0 : glBindFramebuffer(GL_FRAMEBUFFER, msaasamples && (msaalight || !drawtex) ? msfbo : gfbo);
3707 0 : glViewport(0, 0, vieww, viewh);
3708 :
3709 0 : if(drawtex && gdepthinit)
3710 : {
3711 0 : glEnable(GL_SCISSOR_TEST);
3712 0 : glScissor(0, 0, vieww, viewh);
3713 : }
3714 0 : if(gdepthformat && gdepthclear)
3715 : {
3716 0 : maskgbuffer("d");
3717 0 : if(gdepthformat == 1)
3718 : {
3719 0 : glClearColor(1, 1, 1, 1);
3720 : }
3721 : else
3722 : {
3723 0 : glClearColor(-farplane, 0, 0, 0);
3724 : }
3725 0 : glClear(GL_COLOR_BUFFER_BIT);
3726 0 : maskgbuffer("cn");
3727 : }
3728 : else
3729 : {
3730 0 : maskgbuffer("cnd");
3731 : }
3732 0 : if(gcolorclear)
3733 : {
3734 0 : glClearColor(0, 0, 0, 0);
3735 : }
3736 0 : glClear((depthclear ? GL_DEPTH_BUFFER_BIT : 0)|(gcolorclear ? GL_COLOR_BUFFER_BIT : 0)|(depthclear && ghasstencil && (!msaasamples || msaalight || ghasstencil > 1) ? GL_STENCIL_BUFFER_BIT : 0));
3737 0 : if(gdepthformat && gdepthclear)
3738 : {
3739 0 : maskgbuffer("cnd");
3740 : }
3741 0 : if(drawtex && gdepthinit)
3742 : {
3743 0 : glDisable(GL_SCISSOR_TEST);
3744 : }
3745 0 : gdepthinit = true;
3746 :
3747 0 : matrix4 invscreenmatrix,
3748 0 : invcammatrix,
3749 0 : invcamprojmatrix;
3750 0 : invcammatrix.invert(cammatrix);
3751 0 : invcamprojmatrix.invert(camprojmatrix);
3752 0 : invscreenmatrix.identity();
3753 0 : invscreenmatrix.settranslation(-1.0f, -1.0f, -1.0f);
3754 0 : invscreenmatrix.setscale(2.0f/vieww, 2.0f/viewh, 2.0f);
3755 :
3756 0 : eyematrix.muld(projmatrix.inverse(), invscreenmatrix);
3757 0 : if(drawtex == Draw_TexMinimap)
3758 : {
3759 0 : linearworldmatrix.muld(invcamprojmatrix, invscreenmatrix);
3760 0 : if(!gdepthformat)
3761 : {
3762 0 : worldmatrix = linearworldmatrix;
3763 : }
3764 0 : linearworldmatrix.a.z = invcammatrix.a.z;
3765 0 : linearworldmatrix.b.z = invcammatrix.b.z;
3766 0 : linearworldmatrix.c.z = invcammatrix.c.z;
3767 0 : linearworldmatrix.d.z = invcammatrix.d.z;
3768 0 : if(gdepthformat)
3769 : {
3770 0 : worldmatrix = linearworldmatrix;
3771 : }
3772 0 : GLOBALPARAMF(radialfogscale, 0, 0, 0, 0);
3773 : }
3774 : else
3775 : {
3776 0 : float xscale = eyematrix.a.x,
3777 0 : yscale = eyematrix.b.y,
3778 0 : xoffset = eyematrix.d.x,
3779 0 : yoffset = eyematrix.d.y,
3780 0 : zscale = eyematrix.d.z;
3781 0 : matrix4 depthmatrix(vec(xscale/zscale, 0, xoffset/zscale), vec(0, yscale/zscale, yoffset/zscale));
3782 0 : linearworldmatrix.muld(invcammatrix, depthmatrix);
3783 0 : if(gdepthformat)
3784 : {
3785 0 : worldmatrix = linearworldmatrix;
3786 : }
3787 : else
3788 : {
3789 0 : worldmatrix.muld(invcamprojmatrix, invscreenmatrix);
3790 : }
3791 :
3792 0 : GLOBALPARAMF(radialfogscale, xscale/zscale, yscale/zscale, xoffset/zscale, yoffset/zscale);
3793 : }
3794 :
3795 0 : screenmatrix.identity();
3796 0 : screenmatrix.settranslation(0.5f*vieww, 0.5f*viewh, 0.5f);
3797 0 : screenmatrix.setscale(0.5f*vieww, 0.5f*viewh, 0.5f);
3798 0 : screenmatrix.muld(camprojmatrix);
3799 :
3800 0 : GLOBALPARAMF(viewsize, vieww, viewh, 1.0f/vieww, 1.0f/viewh);
3801 0 : GLOBALPARAMF(gdepthscale, eyematrix.d.z, eyematrix.c.w, eyematrix.d.w);
3802 0 : GLOBALPARAMF(gdepthinvscale, eyematrix.d.z / eyematrix.c.w, eyematrix.d.w / eyematrix.c.w);
3803 0 : GLOBALPARAMF(gdepthpackparams, -1.0f/farplane, -255.0f/farplane, -(255.0f*255.0f)/farplane);
3804 0 : GLOBALPARAMF(gdepthunpackparams, -farplane, -farplane/255.0f, -farplane/(255.0f*255.0f));
3805 0 : GLOBALPARAM(worldmatrix, worldmatrix);
3806 :
3807 0 : GLOBALPARAMF(ldrscale, ldrscale);
3808 0 : GLOBALPARAMF(hdrgamma, hdrgamma, 1.0f/hdrgamma);
3809 0 : GLOBALPARAM(camera, camera1->o);
3810 0 : GLOBALPARAMF(millis, lastmillis/1000.0f);
3811 :
3812 0 : glerror();
3813 :
3814 0 : if(depthclear)
3815 : {
3816 0 : resetlights();
3817 : }
3818 0 : batching::resetmodelbatches();
3819 0 : }
3820 :
3821 :
3822 : //allows passing nothing to internal uses of rendergbuffer
3823 : //(the parameter is for taking a game function to be rendered onscreen)
3824 0 : void GBuffer::dummyfxn()
3825 : {
3826 0 : return;
3827 : }
3828 :
3829 0 : void GBuffer::rendergbuffer(bool depthclear, void (*gamefxn)())
3830 : {
3831 0 : timer *gcputimer = drawtex ? nullptr : begintimer("g-buffer", false),
3832 0 : *gtimer = drawtex ? nullptr : begintimer("g-buffer");
3833 :
3834 0 : preparegbuffer(depthclear);
3835 :
3836 0 : if(limitsky())
3837 : {
3838 0 : renderexplicitsky();
3839 0 : glerror();
3840 : }
3841 0 : rendergeom();
3842 0 : glerror();
3843 0 : renderdecals();
3844 0 : glerror();
3845 0 : rendermapmodels();
3846 0 : glerror();
3847 0 : gamefxn();
3848 0 : if(drawtex == Draw_TexMinimap)
3849 : {
3850 0 : if(depthclear)
3851 : {
3852 0 : findmaterials();
3853 : }
3854 0 : renderminimapmaterials();
3855 0 : glerror();
3856 : }
3857 0 : else if(!drawtex)
3858 : {
3859 0 : rendermodelbatches();
3860 0 : glerror();
3861 0 : renderstains(StainBuffer_Opaque, true);
3862 0 : renderstains(StainBuffer_Mapmodel, true);
3863 0 : glerror();
3864 : }
3865 :
3866 0 : endtimer(gtimer);
3867 0 : endtimer(gcputimer);
3868 0 : }
3869 :
3870 0 : void GBuffer::shademinimap(const vec &color)
3871 : {
3872 0 : glerror();
3873 :
3874 0 : glBindFramebuffer(GL_FRAMEBUFFER, msaalight ? mshdrfbo : hdrfbo);
3875 0 : glViewport(0, 0, vieww, viewh);
3876 :
3877 0 : if(color.x >= 0)
3878 : {
3879 0 : glClearColor(color.x, color.y, color.z, 0);
3880 0 : glClear(GL_COLOR_BUFFER_BIT);
3881 : }
3882 :
3883 0 : renderlights(-1, -1, 1, 1, nullptr, 0, msaalight ? -1 : 0);
3884 0 : glerror();
3885 0 : }
3886 :
3887 0 : void GBuffer::shademodelpreview(int x, int y, int w, int h, bool background, bool scissor)
3888 : {
3889 0 : glerror();
3890 :
3891 0 : glBindFramebuffer(GL_FRAMEBUFFER, 0);
3892 0 : glViewport(0, 0, hudw(), hudh());
3893 :
3894 0 : if(msaalight)
3895 : {
3896 0 : glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, mscolortex);
3897 : }
3898 : else
3899 : {
3900 0 : glBindTexture(GL_TEXTURE_RECTANGLE, gcolortex);
3901 : }
3902 0 : glActiveTexture(GL_TEXTURE1);
3903 0 : if(msaalight)
3904 : {
3905 0 : glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, msnormaltex);
3906 : }
3907 : else
3908 : {
3909 0 : glBindTexture(GL_TEXTURE_RECTANGLE, gnormaltex);
3910 : }
3911 0 : glActiveTexture(GL_TEXTURE3);
3912 0 : if(msaalight)
3913 : {
3914 0 : glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, msdepthtex);
3915 : }
3916 : else
3917 : {
3918 0 : glBindTexture(GL_TEXTURE_RECTANGLE, gdepthtex);
3919 : }
3920 0 : glActiveTexture(GL_TEXTURE0);
3921 :
3922 0 : float lightscale = 2.0f*ldrscale;
3923 0 : GLOBALPARAMF(lightscale, 0.1f*lightscale, 0.1f*lightscale, 0.1f*lightscale, lightscale);
3924 0 : GLOBALPARAM(sunlightdir, vec(0, -1, 2).normalize());
3925 0 : GLOBALPARAMF(sunlightcolor, 0.6f*lightscale, 0.6f*lightscale, 0.6f*lightscale);
3926 :
3927 0 : SETSHADER(modelpreview);
3928 :
3929 0 : LOCALPARAMF(cutout, background ? -1 : 0);
3930 :
3931 0 : if(scissor)
3932 : {
3933 0 : glEnable(GL_SCISSOR_TEST);
3934 : }
3935 :
3936 0 : int sx = std::clamp(x, 0, hudw()),
3937 0 : sy = std::clamp(y, 0, hudh()),
3938 0 : sw = std::clamp(x + w, 0, hudw()) - sx,
3939 0 : sh = std::clamp(y + h, 0, hudh()) - sy;
3940 0 : float sxk = 2.0f/hudw(),
3941 0 : syk = 2.0f/hudh(),
3942 0 : txk = vieww/static_cast<float>(w),
3943 0 : tyk = viewh/static_cast<float>(h);
3944 0 : hudquad(sx*sxk - 1, sy*syk - 1, sw*sxk, sh*syk, (sx-x)*txk, (sy-y)*tyk, sw*txk, sh*tyk);
3945 :
3946 0 : if(scissor)
3947 : {
3948 0 : glDisable(GL_SCISSOR_TEST);
3949 : }
3950 :
3951 0 : glerror();
3952 0 : }
3953 :
3954 0 : void GBuffer::shadesky() const
3955 : {
3956 0 : glBindFramebuffer(GL_FRAMEBUFFER, msaalight ? mshdrfbo : hdrfbo);
3957 0 : glViewport(0, 0, vieww, viewh);
3958 :
3959 0 : drawskybox((hdrclear > 0 ? hdrclear-- : msaalight) > 0);
3960 0 : }
3961 :
3962 0 : bool GBuffer::istransparentlayer() const
3963 : {
3964 0 : return transparentlayer;
3965 : }
3966 :
3967 0 : void shadegbuffer()
3968 : {
3969 0 : if(msaasamples && !msaalight && !drawtex)
3970 : {
3971 0 : gbuf.resolvemsaadepth(vieww, viewh);
3972 : }
3973 0 : glerror();
3974 :
3975 0 : timer *shcputimer = begintimer("deferred shading", false),
3976 0 : *shtimer = begintimer("deferred shading");
3977 :
3978 0 : gbuf.shadesky();
3979 :
3980 0 : if(msaasamples && (msaalight || !drawtex))
3981 : {
3982 0 : if((ghasstencil && msaaedgedetect) || msaalight==2)
3983 : {
3984 0 : for(int i = 0; i < 2; ++i)
3985 : {
3986 0 : gbuf.renderlights(-1, -1, 1, 1, nullptr, 0, i+1);
3987 : }
3988 0 : }
3989 : else
3990 : {
3991 0 : gbuf.renderlights(-1, -1, 1, 1, nullptr, 0, drawtex ? -1 : 3);
3992 : }
3993 0 : }
3994 : else
3995 : {
3996 0 : gbuf.renderlights();
3997 : }
3998 0 : glerror();
3999 :
4000 0 : if(!drawtex)
4001 : {
4002 0 : renderstains(StainBuffer_Opaque, false);
4003 0 : renderstains(StainBuffer_Mapmodel, false);
4004 : }
4005 :
4006 0 : endtimer(shtimer);
4007 0 : endtimer(shcputimer);
4008 0 : }
4009 :
4010 0 : void setuplights(GBuffer &buf)
4011 : {
4012 0 : glerror();
4013 0 : buf.setupgbuffer();
4014 0 : if(bloomw < 0 || bloomh < 0)
4015 : {
4016 0 : setupbloom(gw, gh);
4017 : }
4018 0 : if(ao && (aow < 0 || aoh < 0))
4019 : {
4020 0 : setupao(gw, gh);
4021 : }
4022 0 : if(volumetriclights && volumetric && (volw < 0 || volh < 0))
4023 : {
4024 0 : setupvolumetric(gw, gh);
4025 : }
4026 0 : if(!shadowatlas.fbo)
4027 : {
4028 0 : shadowatlas.setup();
4029 : }
4030 0 : if(useradiancehints() && !rhfbo)
4031 : {
4032 0 : setupradiancehints();
4033 : }
4034 0 : if(!deferredlightshader)
4035 : {
4036 0 : loaddeferredlightshaders();
4037 : }
4038 0 : if(drawtex == Draw_TexMinimap && !deferredminimapshader)
4039 : {
4040 0 : deferredminimapshader = loaddeferredlightshader(msaalight ? "mM" : "m");
4041 : }
4042 0 : setupaa(buf, gw, gh);
4043 0 : glerror();
4044 0 : }
4045 :
4046 0 : bool debuglights()
4047 : {
4048 0 : viewao(); //this fxn checks for the appropriate debug var
4049 0 : if(debugshadowatlas)
4050 : {
4051 0 : shadowatlas.view();
4052 : }
4053 0 : else if(debugdepth)
4054 : {
4055 0 : gbuf.viewdepth();
4056 : }
4057 0 : else if(debugstencil)
4058 : {
4059 0 : viewstencil();
4060 : }
4061 0 : else if(debugrefract)
4062 : {
4063 0 : gbuf.viewrefract();
4064 : }
4065 0 : else if(debuglightscissor)
4066 : {
4067 0 : viewlightscissor();
4068 : }
4069 0 : else if(debugrsm)
4070 : {
4071 0 : viewrsm();
4072 : }
4073 0 : else if(debugrh)
4074 : {
4075 0 : viewrh();
4076 : }
4077 0 : else if(!debugaa())
4078 : {
4079 0 : return false;
4080 : }
4081 0 : return true;
4082 : }
4083 :
4084 0 : void cleanuplights()
4085 : {
4086 0 : gbuf.cleanupgbuffer();
4087 0 : cleanupbloom();
4088 0 : cleanupao();
4089 0 : cleanupvolumetric();
4090 0 : shadowatlas.cleanup();
4091 0 : cleanupradiancehints();
4092 0 : lightsphere::cleanup();
4093 0 : cleanupaa();
4094 0 : }
4095 :
4096 1 : int GBuffer::getlightdebuginfo(uint type) const
4097 : {
4098 1 : switch(type)
4099 : {
4100 1 : case 0:
4101 : {
4102 1 : return lightpassesused;
4103 : }
4104 0 : case 1:
4105 : {
4106 0 : return lightsvisible;
4107 : }
4108 0 : case 2:
4109 : {
4110 0 : return lightsoccluded;
4111 : }
4112 0 : case 3:
4113 : {
4114 0 : return lightbatchesused;
4115 : }
4116 0 : case 4:
4117 : {
4118 0 : return lightbatchrectsused;
4119 : }
4120 0 : case 5:
4121 : {
4122 0 : return lightbatchstacksused;
4123 : }
4124 0 : default:
4125 : {
4126 0 : return -1;
4127 : }
4128 : }
4129 : }
4130 :
4131 1 : void initrenderlightscmds()
4132 : {
4133 2 : addcommand("usepacknorm", reinterpret_cast<identfun>(+[](){intret(usepacknorm() ? 1 : 0);}), "", Id_Command);
4134 2 : addcommand("lightdebuginfo", reinterpret_cast<identfun>(+[] (int * index) {intret(gbuf.getlightdebuginfo(static_cast<uint>(*index)));} ), "i", Id_Command);
4135 2 : addcommand("getcsmproperty", reinterpret_cast<identfun>(+[] (int * index) {floatret(csm.getcsmproperty(*index));} ), "i", Id_Command);
4136 2 : addcommand("setcsmproperty", reinterpret_cast<identfun>(+[] (int * index, float * value) {intret(csm.setcsmproperty(*index, *value));} ), "if", Id_Command);
4137 1 : }
|