/
rend_main.cpp
6421 lines (5484 loc) · 216 KB
/
rend_main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** @file rend_main.cpp World Map Renderer.
*
* @authors Copyright © 2003-2013 Jaakko Keränen <jaakko.keranen@iki.fi>
* @authors Copyright © 2006-2015 Daniel Swanson <danij@dengine.net>
* @authors Copyright © 2006 Jamie Jones <jamie_jones_au@yahoo.com.au>
*
* @par License
* GPL: http://www.gnu.org/licenses/gpl.html
*
* <small>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. This program is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details. You should have received a copy of the GNU
* General Public License along with this program; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA</small>
*/
#include "de_platform.h"
#include "render/rend_main.h"
#include "MaterialVariantSpec"
#include "ClientTexture"
#include "Face"
#include "world/map.h"
#include "world/blockmap.h"
#include "world/lineowner.h"
#include "world/p_object.h"
#include "world/p_players.h"
#include "world/sky.h"
#include "world/thinkers.h"
#include "BspLeaf"
#include "Contact"
#include "ConvexSubspace"
#include "Hand"
#include "client/clientsubsector.h"
#include "Surface"
#include "BiasIllum"
#include "HueCircleVisual"
#include "LightDecoration"
#include "Lumobj"
#include "Shard"
#include "SkyFixEdge"
#include "SurfaceDecorator"
#include "TriangleStripBuilder"
#include "WallEdge"
#include "gl/gl_main.h"
#include "gl/gl_tex.h" // pointlight_analysis_t
#include "gl/gl_texmanager.h"
#include "gl/sys_opengl.h"
#include "api_fontrender.h"
#include "misc/r_util.h"
#include "render/fx/bloom.h"
#include "render/fx/vignette.h"
#include "render/fx/lensflares.h"
#include "render/angleclipper.h"
#include "render/blockmapvisual.h"
#include "render/billboard.h"
#include "render/cameralensfx.h"
#include "render/modelrenderer.h"
#include "render/r_main.h"
#include "render/r_things.h"
#include "render/rend_fakeradio.h"
#include "render/rend_halo.h"
#include "render/rend_particle.h"
#include "render/rendpoly.h"
#include "render/skydrawable.h"
#include "render/store.h"
#include "render/viewports.h"
#include "render/vissprite.h"
#include "render/vr.h"
#include "ui/editors/rendererappearanceeditor.h"
#include "ui/editors/modelasseteditor.h"
#include "ui/ui_main.h"
#include "ui/editors/edit_bias.h"
#include "sys_system.h"
#include "dd_main.h"
#include "clientapp.h"
#include <doomsday/console/cmd.h>
#include <doomsday/console/var.h>
#include <doomsday/defs/sprite.h>
#include <doomsday/res/TextureManifest>
#include <doomsday/world/Materials>
#include <doomsday/BspNode>
#include <de/concurrency.h>
#include <de/timer.h>
#include <de/vector1.h>
#include <de/GLState>
#include <QtAlgorithms>
#include <QBitArray>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace de;
using namespace world;
/**
* POD structure used to transport vertex data refs as a logical unit.
* @note The geometric data itself is not owned!
*/
struct Geometry
{
Vector3f *pos;
Vector4f *color;
Vector2f *tex;
Vector2f *tex2;
};
/**
* POD structure used to describe texture modulation data.
*/
struct TexModulationData
{
DGLuint texture = 0;
Vector3f color;
Vector2f topLeft;
Vector2f bottomRight;
};
// Surface (tangent-space) Vector Flags.
#define SVF_TANGENT 0x01
#define SVF_BITANGENT 0x02
#define SVF_NORMAL 0x04
/**
* @defgroup soundOriginFlags Sound Origin Flags
* Flags for use with the sound origin debug display.
* @ingroup flags
*/
///@{
#define SOF_SECTOR 0x01
#define SOF_PLANE 0x02
#define SOF_SIDE 0x04
///@}
void Rend_DrawBBox(Vector3d const &pos, coord_t w, coord_t l, coord_t h, dfloat a,
dfloat const color[3], dfloat alpha, dfloat br, bool alignToBase = true);
void Rend_DrawArrow(Vector3d const &pos, dfloat a, dfloat s, dfloat const color3f[3], dfloat alpha);
D_CMD(OpenRendererAppearanceEditor);
D_CMD(LowRes);
D_CMD(MipMap);
D_CMD(TexReset);
dint useBias; ///< Shadow Bias enabled? cvar
FogParams fogParams;
dfloat fieldOfView = 95.0f;
dbyte smoothTexAnim = true;
dint renderTextures = true;
dint renderWireframe;
dint useMultiTexLights = true;
dint useMultiTexDetails = true;
dint dynlightBlend;
Vector3f torchColor(1, 1, 1);
dint torchAdditive = true;
dint useShinySurfaces = true;
dint useDynLights = true;
dfloat dynlightFactor = .7f;
dfloat dynlightFogBright = .15f;
dint useGlowOnWalls = true;
dfloat glowFactor = .8f;
dfloat glowHeightFactor = 3; ///< Glow height as a multiplier.
dint glowHeightMax = 100; ///< 100 is the default (0-1024).
dint useShadows = true;
dfloat shadowFactor = 1.2f;
dint shadowMaxRadius = 80;
dint shadowMaxDistance = 1000;
dbyte useLightDecorations = true; ///< cvar
dfloat detailFactor = .5f;
dfloat detailScale = 4;
dint mipmapping = 5;
dint filterUI = 1;
dint texQuality = TEXQ_BEST;
dint ratioLimit; ///< Zero if none.
dd_bool fillOutlines = true;
dint useSmartFilter; ///< Smart filter mode (cvar: 1=hq2x)
dint filterSprites = true;
dint texMagMode = 1; ///< Linear.
dint texAniso = -1; ///< Use best.
dd_bool noHighResTex;
dd_bool noHighResPatches;
dd_bool highResWithPWAD;
dbyte loadExtAlways; ///< Always check for extres (cvar)
dfloat texGamma;
dint glmode[6] = // Indexed by 'mipmapping'.
{
GL_NEAREST,
GL_LINEAR,
GL_NEAREST_MIPMAP_NEAREST,
GL_LINEAR_MIPMAP_NEAREST,
GL_NEAREST_MIPMAP_LINEAR,
GL_LINEAR_MIPMAP_LINEAR
};
Vector3d vOrigin;
dfloat vang, vpitch;
dfloat viewsidex, viewsidey;
dbyte freezeRLs;
dint devNoCulling; ///< @c 1= disabled (cvar).
dint devRendSkyMode;
dbyte devRendSkyAlways;
// Ambient lighting, rAmbient is used within the renderer, ambientLight is
// used to store the value of the ambient light cvar.
// The value chosen for rAmbient occurs in Rend_UpdateLightModMatrix
// for convenience (since we would have to recalculate the matrix anyway).
dint rAmbient, ambientLight;
dint viewpw, viewph; ///< Viewport size, in pixels.
dint viewpx, viewpy; ///< Viewpoint top left corner, in pixels.
dfloat yfov;
dint gameDrawHUD = 1; ///< Set to zero when we advise that the HUD should not be drawn
/**
* Implements a pre-calculated LUT for light level limiting and range
* compression offsets, arranged such that it may be indexed with a
* light level value. Return value is an appropriate delta (considering
* all applicable renderer properties) which has been pre-clamped such
* that when summed with the original light value the result remains in
* the normalized range [0..1].
*/
dfloat lightRangeCompression;
dfloat lightModRange[255];
byte devLightModRange;
dfloat rendLightDistanceAttenuation = 924;
dint rendLightAttenuateFixedColormap = 1;
dfloat rendLightWallAngle = 1.2f; ///< Intensity of angle-based wall lighting.
dbyte rendLightWallAngleSmooth = true;
dfloat rendSkyLight = .273f; ///< Intensity factor.
dbyte rendSkyLightAuto = true;
dint rendMaxLumobjs; ///< Max lumobjs per viewer, per frame. @c 0= no maximum.
dint extraLight; ///< Bumped light from gun blasts.
dfloat extraLightDelta;
DGLuint dlBBox; ///< Display list id for the active-textured bbox model.
/*
* Debug/Development cvars:
*/
dbyte devMobjVLights; ///< @c 1= Draw mobj vertex lighting vector.
dint devMobjBBox; ///< @c 1= Draw mobj bounding boxes.
dint devPolyobjBBox; ///< @c 1= Draw polyobj bounding boxes.
dbyte devVertexIndices; ///< @c 1= Draw vertex indices.
dbyte devVertexBars; ///< @c 1= Draw vertex position bars.
dbyte devDrawGenerators; ///< @c 1= Draw active generators.
dbyte devSoundEmitters; ///< @c 1= Draw sound emitters.
dbyte devSurfaceVectors; ///< @c 1= Draw tangent space vectors for surfaces.
dbyte devNoTexFix; ///< @c 1= Draw "missing" rather than fix materials.
dbyte devSectorIndices; ///< @c 1= Draw sector indicies.
dbyte devThinkerIds; ///< @c 1= Draw (mobj) thinker indicies.
dbyte rendInfoLums; ///< @c 1= Print lumobj debug info to the console.
dbyte devDrawLums; ///< @c 1= Draw lumobjs origins.
dbyte devLightGrid; ///< @c 1= Draw lightgrid debug visual.
dfloat devLightGridSize = 1.5f; ///< Lightgrid debug visual size factor.
static void drawBiasEditingVisuals(Map &map);
//static void drawFakeRadioShadowPoints(Map &map);
static void drawGenerators(Map &map);
static void drawLumobjs(Map &map);
static void drawMobjBoundingBoxes(Map &map);
static void drawSectors(Map &map);
static void drawSoundEmitters(Map &map);
static void drawSurfaceTangentVectors(Map &map);
static void drawThinkers(Map &map);
static void drawVertexes(Map &map);
// Draw state:
static Vector3d eyeOrigin; ///< Viewer origin.
static ConvexSubspace *curSubspace; ///< Subspace currently being drawn.
static Vector3f curSectorLightColor;
static dfloat curSectorLightLevel;
static bool firstSubspace; ///< No range checking for the first one.
static void reportWallDrawn(Line &line)
{
// Already been here?
dint playerNum = DoomsdayApp::players().indexOf(viewPlayer);
if (line.isMappedByPlayer(playerNum)) return;
// Mark as drawn.
line.setMappedByPlayer(playerNum);
// Send a status report.
if (gx.HandleMapObjectStatusReport)
{
gx.HandleMapObjectStatusReport(DMUSC_LINE_FIRSTRENDERED, line.indexInMap(),
DMU_LINE, &playerNum);
}
}
static void scheduleFullLightGridUpdate()
{
if (!ClientApp::world().hasMap()) return;
// Schedule a LightGrid update.
if (ClientApp::world().map().hasLightGrid())
{
ClientApp::world().map().lightGrid().scheduleFullUpdate();
}
}
/// World/map renderer reset.
void Rend_Reset()
{
R_ClearViewData();
if (App_World().hasMap())
{
App_World().map().removeAllLumobjs();
}
if (dlBBox)
{
GL_DeleteLists(dlBBox, 1);
dlBBox = 0;
}
}
bool Rend_IsMTexLights()
{
return IS_MTEX_LIGHTS;
}
bool Rend_IsMTexDetails()
{
return IS_MTEX_DETAILS;
}
dfloat Rend_FieldOfView()
{
if (vrCfg().mode() == VRConfig::OculusRift)
{
// OVR tells us which FOV to use.
return vrCfg().oculusRift().fovX();
}
else
{
// Correction is applied for wide screens so that when the FOV is kept
// at a certain value (e.g., the default FOV), a 16:9 view has a wider angle
// than a 4:3, but not just scaled linearly since that would go too far
// into the fish eye territory.
dfloat widescreenCorrection = dfloat(viewpw) / dfloat(viewph) / (4.f / 3.f);
if (widescreenCorrection < 1.5) // up to ~16:9
{
widescreenCorrection = (1 + 2 * widescreenCorrection) / 3;
return de::clamp(1.f, widescreenCorrection * fieldOfView, 179.f);
}
// This is an unusually wide (perhaps multimonitor) setup, so just use the
// configured FOV as is.
return de::clamp(1.f, fieldOfView, 179.f);
}
}
static Vector3d vEyeOrigin;
Vector3d Rend_EyeOrigin()
{
return vEyeOrigin;
}
Matrix4f Rend_GetModelViewMatrix(dint consoleNum, bool inWorldSpace)
{
viewdata_t const *viewData = &DD_Player(consoleNum)->viewport();
dfloat bodyAngle = viewData->current.angleWithoutHeadTracking() / (dfloat) ANGLE_MAX * 360 - 90;
/// @todo vOrigin et al. shouldn't be changed in a getter function. -jk
vOrigin = viewData->current.origin.xzy();
vang = viewData->current.angle() / (dfloat) ANGLE_MAX * 360 - 90; // head tracking included
vpitch = viewData->current.pitch * 85.0 / 110.0;
vEyeOrigin = vOrigin;
OculusRift &ovr = vrCfg().oculusRift();
bool const applyHead = (vrCfg().mode() == VRConfig::OculusRift && ovr.isReady());
Matrix4f modelView;
Matrix4f headOrientation;
Matrix4f headOffset;
if (applyHead)
{
Vector3f headPos = swizzle(Matrix4f::rotate(bodyAngle, Vector3f(0, 1, 0))
* ovr.headPosition() * vrCfg().mapUnitsPerMeter()
, AxisNegX, AxisNegY, AxisZ);
headOffset = Matrix4f::translate(headPos);
vEyeOrigin -= headPos;
}
if (inWorldSpace)
{
dfloat yaw = vang;
dfloat pitch = vpitch;
dfloat roll = 0;
/// @todo Elevate roll angle use into viewer_t, and maybe all the way up into player
/// model.
// Pitch and yaw can be taken directly from the head tracker, as the game is aware of
// these values and is syncing with them independently (however, game has more
// latency).
if (applyHead)
{
// Use angles directly from the Rift for best response.
Vector3f const pry = ovr.headOrientation();
roll = -radianToDegree(pry[1]);
pitch = radianToDegree(pry[0]);
}
headOrientation = Matrix4f::rotate(roll, Vector3f(0, 0, 1))
* Matrix4f::rotate(pitch, Vector3f(1, 0, 0))
* Matrix4f::rotate(yaw, Vector3f(0, 1, 0));
modelView = headOrientation * headOffset;
}
if (applyHead)
{
// Apply the current eye offset to the eye origin.
vEyeOrigin -= headOrientation.inverse() * (ovr.eyeOffset() * vrCfg().mapUnitsPerMeter());
}
return (modelView
* Matrix4f::scale(Vector3f(1.0f, 1.2f, 1.0f)) // This is the aspect correction.
* Matrix4f::translate(-vOrigin));
}
void Rend_ModelViewMatrix(bool inWorldSpace)
{
DENG_ASSERT_IN_MAIN_THREAD();
DENG_ASSERT_GL_CONTEXT_ACTIVE();
glMatrixMode(GL_MODELVIEW);
glLoadMatrixf(Rend_GetModelViewMatrix(DoomsdayApp::players().indexOf(viewPlayer), inWorldSpace).values());
}
static inline ddouble viewFacingDot(Vector2d const &v1, Vector2d const &v2)
{
// The dot product.
return (v1.y - v2.y) * (v1.x - Rend_EyeOrigin().x) + (v2.x - v1.x) * (v1.y - Rend_EyeOrigin().z);
}
dfloat Rend_ExtraLightDelta()
{
return extraLightDelta;
}
void Rend_ApplyTorchLight(Vector4f &color, dfloat distance)
{
ddplayer_t *ddpl = &viewPlayer->publicData();
// Disabled?
if (!ddpl->fixedColorMap) return;
// Check for torch.
if (!rendLightAttenuateFixedColormap || distance < 1024)
{
// Colormap 1 is the brightest. I'm guessing 16 would be
// the darkest.
dfloat d = (16 - ddpl->fixedColorMap) / 15.0f;
if (rendLightAttenuateFixedColormap)
{
d *= (1024 - distance) / 1024.0f;
}
if (torchAdditive)
{
color += torchColor * d;
}
else
{
color += ((color * torchColor) - color) * d;
}
}
}
void Rend_ApplyTorchLight(dfloat *color3, dfloat distance)
{
Vector4f tmp(color3, 0);
Rend_ApplyTorchLight(tmp, distance);
for (dint i = 0; i < 3; ++i)
{
color3[i] = tmp[i];
}
}
dfloat Rend_AttenuateLightLevel(dfloat distToViewer, dfloat lightLevel)
{
if (distToViewer > 0 && rendLightDistanceAttenuation > 0)
{
dfloat real = lightLevel -
(distToViewer - 32) / rendLightDistanceAttenuation *
(1 - lightLevel);
dfloat minimum = de::max(0.f, de::squared(lightLevel) + (lightLevel - .63f) * .5f);
if (real < minimum)
real = minimum; // Clamp it.
return de::min(real, 1.f);
}
return lightLevel;
}
dfloat Rend_ShadowAttenuationFactor(coord_t distance)
{
if (shadowMaxDistance > 0 && distance > 3 * shadowMaxDistance / 4)
{
return (shadowMaxDistance - distance) / (shadowMaxDistance / 4);
}
return 1;
}
static Vector3f skyLightColor;
static Vector3f oldSkyAmbientColor(-1.f, -1.f, -1.f);
static dfloat oldRendSkyLight = -1;
bool Rend_SkyLightIsEnabled()
{
return rendSkyLight > .001f;
}
Vector3f Rend_SkyLightColor()
{
if (Rend_SkyLightIsEnabled() && ClientApp::world().hasMap())
{
Sky &sky = ClientApp::world().map().sky();
Vector3f const &ambientColor = sky.ambientColor();
if (rendSkyLight != oldRendSkyLight
|| !INRANGE_OF(ambientColor.x, oldSkyAmbientColor.x, .001f)
|| !INRANGE_OF(ambientColor.y, oldSkyAmbientColor.y, .001f)
|| !INRANGE_OF(ambientColor.z, oldSkyAmbientColor.z, .001f))
{
skyLightColor = ambientColor;
R_AmplifyColor(skyLightColor);
// Apply the intensity factor cvar.
for (dint i = 0; i < 3; ++i)
{
skyLightColor[i] = skyLightColor[i] + (1 - rendSkyLight) * (1.f - skyLightColor[i]);
}
// When the sky light color changes we must update the light grid.
scheduleFullLightGridUpdate();
oldSkyAmbientColor = ambientColor;
}
oldRendSkyLight = rendSkyLight;
return skyLightColor;
}
return Vector3f(1, 1, 1);
}
/**
* Determine the effective ambient light color for the given @a sector. Usually
* one would obtain this info from Subsector, however in some situations the
* correct light color is *not* that of the subsector (e.g., where map hacks use
* mapped planes to reference another sector).
*/
static Vector3f Rend_AmbientLightColor(Sector const §or)
{
if (Rend_SkyLightIsEnabled() && sector.hasSkyMaskPlane())
{
return Rend_SkyLightColor();
}
// A non-skylight sector (i.e., everything else!)
// Return the sector's ambient light color.
return sector.lightColor();
}
Vector3f Rend_LuminousColor(Vector3f const &color, dfloat light)
{
light = de::clamp(0.f, light, 1.f) * dynlightFactor;
// In fog additive blending is used; the normal fog color is way too bright.
if(fogParams.usingFog) light *= dynlightFogBright;
// Multiply light with (ambient) color.
return color * light;
}
coord_t Rend_PlaneGlowHeight(dfloat intensity)
{
return de::clamp<ddouble>(0, GLOW_HEIGHT_MAX * intensity * glowHeightFactor, glowHeightMax);
}
ClientMaterial *Rend_ChooseMapSurfaceMaterial(Surface const &surface)
{
switch(renderTextures)
{
case 0: // No texture mode.
case 1: // Normal mode.
if(!(devNoTexFix && surface.hasFixMaterial()))
{
if(surface.hasMaterial() || surface.parent().type() != DMU_PLANE)
return static_cast<ClientMaterial *>(surface.materialPtr());
}
// Use special "missing" material.
return &ClientMaterial::find(de::Uri("System", Path("missing")));
case 2: // Lighting debug mode.
if(surface.hasMaterial() && !(!devNoTexFix && surface.hasFixMaterial()))
{
if(!surface.hasSkyMaskedMaterial() || devRendSkyMode)
{
// Use the special "gray" material.
return &ClientMaterial::find(de::Uri("System", Path("gray")));
}
}
break;
default: break;
}
// No material, then.
return nullptr;
}
/**
* This doesn't create a rendering primitive but a vissprite! The vissprite
* represents the masked poly and will be rendered during the rendering
* of sprites. This is necessary because all masked polygons must be
* rendered back-to-front, or there will be alpha artifacts along edges.
*/
void Rend_AddMaskedPoly(Vector3f const *rvertices, Vector4f const *rcolors,
coord_t wallLength, MaterialAnimator *matAnimator, Vector2f const &materialOrigin,
blendmode_t blendMode, duint lightListIdx, dfloat glow)
{
vissprite_t *vis = R_NewVisSprite(VSPR_MASKED_WALL);
vis->pose.origin = (rvertices[0] + rvertices[3]) / 2;
vis->pose.distance = Rend_PointDist2D(vis->pose.origin);
VS_WALL(vis)->texOffset[0] = materialOrigin[0];
VS_WALL(vis)->texOffset[1] = materialOrigin[1];
// Masked walls are sometimes used for special effects like arcs,
// cobwebs and bottoms of sails. In order for them to look right,
// we need to disable texture wrapping on the horizontal axis (S).
// Most masked walls need wrapping, though. What we need to do is
// look at the texture coordinates and see if they require texture
// wrapping.
if(renderTextures)
{
// Ensure we've up to date info about the material.
matAnimator->prepare();
Vector2ui const &matDimensions = matAnimator->dimensions();
VS_WALL(vis)->texCoord[0][0] = VS_WALL(vis)->texOffset[0] / matDimensions.x;
VS_WALL(vis)->texCoord[1][0] = VS_WALL(vis)->texCoord[0][0] + wallLength / matDimensions.x;
VS_WALL(vis)->texCoord[0][1] = VS_WALL(vis)->texOffset[1] / matDimensions.y;
VS_WALL(vis)->texCoord[1][1] = VS_WALL(vis)->texCoord[0][1] +
(rvertices[3].z - rvertices[0].z) / matDimensions.y;
dint wrapS = GL_REPEAT, wrapT = GL_REPEAT;
if(!matAnimator->isOpaque())
{
if(!(VS_WALL(vis)->texCoord[0][0] < 0 || VS_WALL(vis)->texCoord[0][0] > 1 ||
VS_WALL(vis)->texCoord[1][0] < 0 || VS_WALL(vis)->texCoord[1][0] > 1))
{
// Visible portion is within the actual [0..1] range.
wrapS = GL_CLAMP_TO_EDGE;
}
// Clamp on the vertical axis if the coords are in the normal [0..1] range.
if(!(VS_WALL(vis)->texCoord[0][1] < 0 || VS_WALL(vis)->texCoord[0][1] > 1 ||
VS_WALL(vis)->texCoord[1][1] < 0 || VS_WALL(vis)->texCoord[1][1] > 1))
{
wrapT = GL_CLAMP_TO_EDGE;
}
}
// Choose a specific variant for use as a middle wall section.
matAnimator = &matAnimator->material().getAnimator(Rend_MapSurfaceMaterialSpec(wrapS, wrapT));
}
VS_WALL(vis)->animator = matAnimator;
VS_WALL(vis)->blendMode = blendMode;
for(dint i = 0; i < 4; ++i)
{
VS_WALL(vis)->vertices[i].pos[0] = rvertices[i].x;
VS_WALL(vis)->vertices[i].pos[1] = rvertices[i].y;
VS_WALL(vis)->vertices[i].pos[2] = rvertices[i].z;
for(dint c = 0; c < 4; ++c)
{
/// @todo Do not clamp here.
VS_WALL(vis)->vertices[i].color[c] = de::clamp(0.f, rcolors[i][c], 1.f);
}
}
/// @todo Semitransparent masked polys arn't lit atm
if(glow < 1 && lightListIdx && numTexUnits > 1 && envModAdd &&
!(rcolors[0].w < 1))
{
// The dynlights will have already been sorted so that the brightest
// and largest of them is first in the list. So grab that one.
ClientApp::renderSystem().forAllSurfaceProjections(lightListIdx, [&vis] (ProjectedTextureData const &tp)
{
VS_WALL(vis)->modTex = tp.texture;
VS_WALL(vis)->modTexCoord[0][0] = tp.topLeft.x;
VS_WALL(vis)->modTexCoord[0][1] = tp.topLeft.y;
VS_WALL(vis)->modTexCoord[1][0] = tp.bottomRight.x;
VS_WALL(vis)->modTexCoord[1][1] = tp.bottomRight.y;
for(dint c = 0; c < 4; ++c)
{
VS_WALL(vis)->modColor[c] = tp.color[c];
}
return LoopAbort;
});
}
else
{
VS_WALL(vis)->modTex = 0;
}
}
static void quadTexCoords(Vector2f *tc, Vector3f const *rverts, coord_t wallLength, Vector3d const &topLeft)
{
DENG2_ASSERT(tc && rverts);
tc[0].x = tc[1].x = rverts[0].x - topLeft.x;
tc[3].y = tc[1].y = rverts[0].y - topLeft.y;
tc[3].x = tc[2].x = tc[0].x + wallLength;
tc[2].y = tc[3].y + (rverts[1].z - rverts[0].z);
tc[0].y = tc[3].y + (rverts[3].z - rverts[2].z);
}
static void lightVertex(Vector4f &color, Vector3f const &vtx, dfloat lightLevel, Vector3f const &ambientColor)
{
dfloat const dist = Rend_PointDist2D(vtx);
// Apply distance attenuation.
lightLevel = Rend_AttenuateLightLevel(dist, lightLevel);
// Add extra light.
lightLevel = de::clamp(0.f, lightLevel + Rend_ExtraLightDelta(), 1.f);
Rend_ApplyLightAdaptation(lightLevel);
for(dint i = 0; i < 3; ++i)
{
color[i] = lightLevel * ambientColor[i];
}
}
/**
* Apply map-space lighting to the given geometry. All vertex lighting contributions affecting
* map-space geometry are applied here.
*
* @param verts Geometry to be illuminated.
*
* Surface geometry:
* @param numVertices Total number of map-space surface geometry vertices.
* @param posCoords Position coordinates for the map-space surface geometry.
* @param mapElement Source MapElement for the map-space surface geometry.
* @param geomGroup Source MapElement geometry-group selector, for the map-space surface geometry.
* @param surfaceTangents Tangent-space vectors for the map-space surface geometry.
*
* Surface lighting characteristics:
* @param color Tint color.
* @param color2 Secondary tint color, for walls (if any).
* @param glowing Self-luminosity factor (normalized [0..1]).
* @param luminosityDeltas Edge luminosity deltas (for walls [left edge, right edge]).
*/
static void lightWallOrFlatGeometry(Geometry &verts, duint numVertices, Vector3f const *posCoords,
MapElement &mapElement, dint geomGroup, Matrix3f const &surfaceTangents,
Vector3f const &color, Vector3f const *color2, dfloat glowing, dfloat const luminosityDeltas[2])
{
bool const haveWall = mapElement.is<LineSideSegment>();
auto &subsec = ::curSubspace->subsector().as<world::ClientSubsector>();
// Uniform color?
if(::levelFullBright || !(glowing < 1))
{
dfloat const lum = de::clamp(0.f, ::curSectorLightLevel + (::levelFullBright? 1 : glowing), 1.f);
Vector4f const uniformColor(lum, lum, lum, 0);
for(duint i = 0; i < numVertices; ++i)
{
verts.color[i] = uniformColor;
}
return;
}
if(::useBias) // Bias lighting model.
{
Map &map = subsec.sector().map();
Shard &shard = subsec.shard(mapElement, geomGroup);
// Apply the ambient light term from the grid (if available).
if(map.hasLightGrid())
{
for(duint i = 0; i < numVertices; ++i)
{
verts.color[i] = map.lightGrid().evaluate(posCoords[i]);
}
}
// Apply bias light source contributions.
shard.lightWithBiasSources(posCoords, verts.color, surfaceTangents, map.biasCurrentTime());
// Apply surface glow.
if(glowing > 0)
{
Vector4f const glow(glowing, glowing, glowing, 0);
for(duint i = 0; i < numVertices; ++i)
{
verts.color[i] += glow;
}
}
// Apply light range compression and clamp.
for(duint i = 0; i < numVertices; ++i)
{
Vector4f &color = verts.color[i];
for(dint k = 0; k < 3; ++k)
{
color[k] = de::clamp(0.f, color[k] + Rend_LightAdaptationDelta(color[k]), 1.f);
}
}
}
else // Doom lighting model.
{
// Blend sector light color with the surface color tint.
Vector3f const colorBlended = ::curSectorLightColor * color;
dfloat const lumLeft = de::clamp(0.f, ::curSectorLightLevel + luminosityDeltas[0] + glowing, 1.f);
dfloat const lumRight = de::clamp(0.f, ::curSectorLightLevel + luminosityDeltas[1] + glowing, 1.f);
if(haveWall && !de::fequal(lumLeft, lumRight))
{
lightVertex(verts.color[0], posCoords[0], lumLeft, colorBlended);
lightVertex(verts.color[1], posCoords[1], lumLeft, colorBlended);
lightVertex(verts.color[2], posCoords[2], lumRight, colorBlended);
lightVertex(verts.color[3], posCoords[3], lumRight, colorBlended);
}
else
{
for(duint i = 0; i < numVertices; ++i)
{
lightVertex(verts.color[i], posCoords[i], lumLeft, colorBlended);
}
}
// Secondary color?
if(haveWall && color2)
{
// Blend the secondary surface color tint with the sector light color.
Vector3f const color2Blended = ::curSectorLightColor * (*color2);
lightVertex(verts.color[0], posCoords[0], lumLeft, color2Blended);
lightVertex(verts.color[2], posCoords[2], lumRight, color2Blended);
}
}
// Apply torch light?
DENG2_ASSERT(::viewPlayer);
if(::viewPlayer->publicData().fixedColorMap)
{
for(duint i = 0; i < numVertices; ++i)
{
Rend_ApplyTorchLight(verts.color[i], Rend_PointDist2D(posCoords[i]));
}
}
}
static void makeFlatGeometry(Geometry &verts, duint numVertices, Vector3f const *posCoords,
Vector3d const &topLeft, Vector3d const & /*bottomRight*/, MapElement &mapElement, dint geomGroup,
Matrix3f const &surfaceTangents, dfloat uniformOpacity, Vector3f const &color, Vector3f const *color2,
dfloat glowing, dfloat const luminosityDeltas[2], bool useVertexLighting = true)
{
DENG2_ASSERT(posCoords);
for(duint i = 0; i < numVertices; ++i)
{
verts.pos[i] = posCoords[i];
Vector3f const delta(posCoords[i] - topLeft);
if(verts.tex) // Primary.
{
verts.tex[i] = Vector2f(delta.x, -delta.y);
}
if(verts.tex2) // Inter.
{
verts.tex2[i] = Vector2f(delta.x, -delta.y);
}
}
// Light the geometry?
if(useVertexLighting)
{
lightWallOrFlatGeometry(verts, numVertices, posCoords, mapElement, geomGroup, surfaceTangents,
color, color2, glowing, luminosityDeltas);
// Apply uniform opacity (overwritting luminance factors).
for(duint i = 0; i < numVertices; ++i)
{
verts.color[i].w = uniformOpacity;
}
}
}
static void makeWallGeometry(Geometry &verts, duint numVertices, Vector3f const *posCoords,
Vector3d const &topLeft, Vector3d const & /*bottomRight*/, coord_t sectionWidth,
MapElement &mapElement, dint geomGroup, Matrix3f const &surfaceTangents, dfloat uniformOpacity,
Vector3f const &color, Vector3f const *color2, dfloat glowing, dfloat const luminosityDeltas[2],
bool useVertexLighting = true)
{
DENG2_ASSERT(posCoords);
for(duint i = 0; i < numVertices; ++i)
{
verts.pos[i] = posCoords[i];
}
if(verts.tex) // Primary.
{
quadTexCoords(verts.tex, posCoords, sectionWidth, topLeft);
}
if(verts.tex2) // Inter.
{
quadTexCoords(verts.tex2, posCoords, sectionWidth, topLeft);
}
// Light the geometry?
if(useVertexLighting)
{
lightWallOrFlatGeometry(verts, numVertices, posCoords, mapElement, geomGroup, surfaceTangents,
color, color2, glowing, luminosityDeltas);
// Apply uniform opacity (overwritting luminance factors).
for(duint i = 0; i < numVertices; ++i)
{
verts.color[i].w = uniformOpacity;
}
}
}
static inline dfloat shineVertical(dfloat dy, dfloat dx)
{
return ((std::atan(dy/dx) / (PI/2)) + 1) / 2;
}
static void makeFlatShineGeometry(Geometry &verts, duint numVertices, Vector3f const *posCoords,
Geometry const &mainVerts, Vector3f const &shineColor, dfloat shineOpacity)
{
DENG2_ASSERT(posCoords);
for(duint i = 0; i < numVertices; ++i)
{
Vector3f const eye = Rend_EyeOrigin();
// Determine distance to viewer.
dfloat distToEye = (eye.xz() - Vector2f(posCoords[i])).normalize().length();
// Short distances produce an ugly 'crunch' below and above the viewpoint.
if(distToEye < 10) distToEye = 10;
// Offset from the normal view plane.