-
Notifications
You must be signed in to change notification settings - Fork 56
/
ltface.cc
3693 lines (3024 loc) · 127 KB
/
ltface.cc
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
/* Copyright (C) 1996-1997 Id Software, Inc.
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
See file, 'COPYING', for details.
*/
#include <light/ltface.hh>
#include <light/light.hh>
#include <light/trace_embree.hh>
#include <light/phong.hh>
#include <light/surflight.hh> //mxd
#include <light/entities.hh>
#include <light/lightgrid.hh>
#include <light/trace.hh>
#include <light/litfile.hh> // for facesup_t
#include <common/imglib.hh>
#include <common/log.hh>
#include <common/bsputils.hh>
#include <common/qvec.hh>
#include <common/ostream.hh>
#include <atomic>
#include <cassert>
#include <cmath>
#include <algorithm>
#include <fstream>
#if 0
std::atomic<uint32_t> total_light_rays, total_light_ray_hits, total_samplepoints;
std::atomic<uint32_t> total_bounce_rays, total_bounce_ray_hits;
std::atomic<uint32_t> total_surflight_rays, total_surflight_ray_hits; // mxd
#endif
std::atomic<uint32_t> fully_transparent_lightmaps;
static bool warned_about_light_map_overflow, warned_about_light_style_overflow;
/* Debug helper - move elsewhere? */
void PrintFaceInfo(const mface_t *face, const mbsp_t *bsp)
{
const mtexinfo_t *tex = &bsp->texinfo[face->texinfo];
const char *texname = Face_TextureName(bsp, face);
logging::print("face {}, texture {}, {} edges; vectors:\n"
"{}\n",
Face_GetNum(bsp, face), texname, face->numedges, tex->vecs);
for (int i = 0; i < face->numedges; i++) {
int edge = bsp->dsurfedges[face->firstedge + i];
int vert = Face_VertexAtIndex(bsp, face, i);
const qvec3f &point = GetSurfaceVertexPoint(bsp, face, i);
const qvec3f norm = GetSurfaceVertexNormal(bsp, face, i).normal;
logging::print("{} {:3} ({:3.3}, {:3.3}, {:3.3}) :: normal ({:3.3}, {:3.3}, {:3.3}) :: edge {}\n",
i ? " " : " verts ", vert, point[0], point[1], point[2], norm[0], norm[1], norm[2], edge);
}
}
class position_t
{
public:
bool m_unoccluded;
const mface_t *m_actualFace;
qvec3f m_position;
qvec3f m_interpolatedNormal;
position_t(qvec3f position)
: m_unoccluded(false),
m_actualFace(nullptr),
m_position(position),
m_interpolatedNormal({})
{
}
position_t(const mface_t *actualFace, const qvec3f &position, const qvec3f &interpolatedNormal)
: m_unoccluded(true),
m_actualFace(actualFace),
m_position(position),
m_interpolatedNormal(interpolatedNormal){};
};
static constexpr float sampleOffPlaneDist = 1.0f;
/*
Why this is so complicated:
- vanilla tools just did a trace from the face centroid to the desired location of the sample point.
This doesn't work because we want to allow pillars blocking parts of the face. (func_detail_wall).
- must avoid solutions that leak light through walls (e.g. having an interior wall
pick up light from outside), and avoid light leaks e.g. in V-shaped sconces
that have a light inside the "V".
- it's critical to allow sample points to extend onto neighbouring faces,
both for phong shading to look good, as well as general light quality
*/
static position_t PositionSamplePointOnFace(
const mbsp_t *bsp, const mface_t *face, const bool phongShaded, const qvec3f &point, const qvec3f &modelOffset);
std::vector<const mface_t *> NeighbouringFaces_old(const mbsp_t *bsp, const mface_t *face)
{
std::vector<const mface_t *> result;
for (int i = 0; i < face->numedges; i++) {
const mface_t *smoothed = Face_EdgeIndexSmoothed(bsp, face, i);
if (smoothed != nullptr && smoothed != face) {
result.push_back(smoothed);
}
}
return result;
}
position_t CalcPointNormal(const mbsp_t *bsp, const mface_t *face, const qvec3f &origPoint, bool phongShaded,
const faceextents_t &faceextents, int recursiondepth, const qvec3f &modelOffset)
{
const auto &facecache = FaceCacheForFNum(Face_GetNum(bsp, face));
const qvec4f &surfplane = facecache.plane();
const auto &points = facecache.points();
const auto &edgeplanes = facecache.edgePlanes();
// const auto &neighbours = facecache.neighbours();
// check for degenerate face
if (points.empty() || edgeplanes.empty())
return position_t(origPoint);
// project `point` onto the surface plane, then lift it off again
const qvec3f point = ProjectPointOntoPlane(surfplane, origPoint) + (qvec3f(surfplane) * sampleOffPlaneDist);
// check if in face..
if (EdgePlanes_PointInside(edgeplanes, point)) {
return PositionSamplePointOnFace(bsp, face, phongShaded, point, modelOffset);
}
#if 0
// fixme: handle "not possible to compute"
const qvec3f centroid = Face_Centroid(bsp, face);
for (const neighbour_t &n : neighbours) {
/*
check if in XXX area:
"in1" "in2"
\XXXX|
\XXX|
|--|----|
|\ | |
| * | * = centroid
|------/
*/
const qvec3f in1_normal = qv::cross(qv::normalize(n.p0 - centroid), facecache.normal());
const qvec3f in2_normal = qv::cross(facecache.normal(), qv::normalize(n.p1 - centroid));
const qvec4f in1 = MakePlane(in1_normal, n.p0);
const qvec4f in2 = MakePlane(in2_normal, n.p1);
const float in1_dist = DistAbovePlane(in1, point);
const float in2_dist = DistAbovePlane(in2, point);
if (in1_dist >= 0 && in2_dist >= 0) {
const auto &n_facecache = FaceCacheForFNum(Face_GetNum(bsp, n.face));
const qvec4f &n_surfplane = n_facecache.plane();
const auto &n_edgeplanes = n_facecache.edgePlanes();
// project `point` onto the surface plane, then lift it off again
const qvec3f n_point = ProjectPointOntoPlane(n_surfplane, origPoint) + (qvec3f(n_surfplane) * sampleOffPlaneDist);
// check if in face..
if (EdgePlanes_PointInside(n_edgeplanes, n_point)) {
return PositionSamplePointOnFace(bsp, n.face, phongShaded, n_point, modelOffset);
}
}
}
#endif
// not in any triangle. among the edges this point is _behind_,
// search for the one that the point is least past the endpoints of the edge
{
int bestplane = -1;
float bestdist = FLT_MAX;
for (int i = 0; i < face->numedges; i++) {
const qvec3f &v0 = points.at(i);
const qvec3f &v1 = points.at((i + 1) % points.size());
const auto edgeplane = MakeInwardFacingEdgePlane(v0, v1, surfplane);
if (!edgeplane.first)
continue; // degenerate edge
const float planedist = DistAbovePlane(edgeplane.second, point);
if (planedist < POINT_EQUAL_EPSILON) {
// behind this plane. check whether we're between the endpoints.
const qvec3f v0v1 = v1 - v0;
const float v0v1dist = qv::length(v0v1);
const float t = FractionOfLine(v0, v1, point); // t=0 for point=v0, t=1 for point=v1
float edgedist;
if (t < 0)
edgedist = fabs(t) * v0v1dist;
else if (t > 1)
edgedist = t * v0v1dist;
else
edgedist = 0;
if (edgedist < bestdist) {
bestplane = i;
bestdist = edgedist;
}
}
}
if (bestplane != -1) {
// FIXME: Also need to handle non-smoothed but same plane
const mface_t *smoothed = Face_EdgeIndexSmoothed(bsp, face, bestplane);
if (smoothed) {
// try recursive search
if (recursiondepth < 3) {
// call recursively to look up normal in the adjacent face
return CalcPointNormal(
bsp, smoothed, point, phongShaded, faceextents, recursiondepth + 1, modelOffset);
}
}
}
}
// 2. Try snapping to poly
const std::pair<int, qvec3f> closest = ClosestPointOnPolyBoundary(points, point);
float luxelSpaceDist;
{
auto desired_point_in_lmspace = faceextents.worldToLMCoord(point);
auto closest_point_on_face_in_lmspace = faceextents.worldToLMCoord(closest.second);
luxelSpaceDist = qv::distance(desired_point_in_lmspace, closest_point_on_face_in_lmspace);
}
if (luxelSpaceDist <= 1) {
// Snap it to the face edge. Add the 1 unit off plane.
const qvec3f snapped = closest.second + (qvec3f(surfplane) * sampleOffPlaneDist);
return PositionSamplePointOnFace(bsp, face, phongShaded, snapped, modelOffset);
}
// This point is too far from the polygon to be visible in game, so don't bother calculating lighting for it.
// Dont contribute to interpolating.
// We could safely colour it in pink for debugging.
return position_t(point);
}
// Dump points to a .map file
static void CalcPoints_Debug(const lightsurf_t *surf, const mbsp_t *bsp)
{
std::ofstream f("calcpoints.map");
for (int t = 0; t < surf->height; t++) {
for (int s = 0; s < surf->width; s++) {
const int i = t * surf->width + s;
const auto &sample = surf->samples[i];
const qvec3f &point = sample.point;
const qvec3f mangle = qv::mangle_from_vec(sample.normal);
f << "{\n";
f << "\"classname\" \"light\"\n";
ewt::print(f, "\"origin\" \"{}\"\n", point);
ewt::print(f, "\"mangle\" \"{}\"\n", mangle);
ewt::print(f, "\"face\" \"{}\"\n", sample.realfacenum);
ewt::print(f, "\"occluded\" \"{}\"\n", sample.occluded);
ewt::print(f, "\"s\" \"{}\"\n", s);
ewt::print(f, "\"t\" \"{}\"\n", t);
f << "}\n";
}
}
logging::print("wrote face {}'s sample points ({}x{}) to calcpoints.map\n", Face_GetNum(bsp, surf->face),
surf->width, surf->height);
PrintFaceInfo(surf->face, bsp);
}
/// Checks if the point is in any solid (solid or sky leaf)
/// 1. the world
/// 2. any shadow-casting bmodel
/// 3. the `self` model (regardless of whether it's selfshadowing)
///
/// This is used for marking sample points as occluded.
static bool Light_PointInAnySolid(const mbsp_t *bsp, const dmodelh2_t *self, const qvec3f &point)
{
if (Light_PointInSolid(bsp, self, point))
return true;
auto *self_modelinfo = ModelInfoForModel(bsp, self - bsp->dmodels.data());
if (self_modelinfo->object_channel_mask.value() == CHANNEL_MASK_DEFAULT) {
if (Light_PointInWorld(bsp, point))
return true;
}
for (const auto &modelinfo : tracelist) {
if (modelinfo->object_channel_mask.value() != self_modelinfo->object_channel_mask.value())
continue;
if (Light_PointInSolid(bsp, modelinfo->model, point - modelinfo->offset)) {
// Only mark occluded if the bmodel is fully opaque
if (modelinfo->alpha.value() == 1.0f)
return true;
}
}
return false;
}
// precondition: `point` is on the same plane as `face` and within the bounds.
static position_t PositionSamplePointOnFace(
const mbsp_t *bsp, const mface_t *face, const bool phongShaded, const qvec3f &point, const qvec3f &modelOffset)
{
const auto &facecache = FaceCacheForFNum(Face_GetNum(bsp, face));
const auto &points = facecache.points();
const auto &normals = facecache.normals();
const auto &edgeplanes = facecache.edgePlanes();
const auto &plane = facecache.plane();
if (edgeplanes.empty()) {
// degenerate polygon
return position_t(point);
}
const float planedist = DistAbovePlane(plane, point);
if (!(fabs(planedist - sampleOffPlaneDist) <= 0.1)) {
// something is wrong?
return position_t(point);
}
const float insideDist = EdgePlanes_PointInsideDist(edgeplanes, point);
if (insideDist < -POINT_EQUAL_EPSILON) {
// Non-convex polygon
return position_t(point);
}
const modelinfo_t *mi = ModelInfoForFace(bsp, Face_GetNum(bsp, face));
if (mi == nullptr) {
// missing model ("skip" faces) don't get lighting
return position_t(point);
}
// Get the point normal
qvec3f pointNormal;
if (phongShaded) {
const auto interpNormal = InterpolateNormal(points, normals, point);
// We already know the point is in the face, so this should always succeed
if (!interpNormal.first)
return position_t(point);
pointNormal = interpNormal.second;
} else {
pointNormal = plane;
}
const bool inSolid = Light_PointInAnySolid(bsp, mi->model, point + modelOffset);
if (inSolid) {
#if 1
// try +/- 0.5 units in X/Y/Z (8 tests)
for (int x = -1; x <= 1; x += 2) {
for (int y = -1; y <= 1; y += 2) {
for (int z = -1; z <= 1; z += 2) {
const qvec3f jitter = qvec3f(x, y, z) * 0.5;
const qvec3f new_point = point + jitter;
if (!Light_PointInAnySolid(bsp, mi->model, new_point + modelOffset)) {
return position_t(face, new_point, pointNormal);
}
}
}
}
#else
// this has issues with narrow sliver-shaped faces moving the sample points a lot into vastly different lighting
// Check distance to border
const float distanceInside = EdgePlanes_PointInsideDist(edgeplanes, point);
if (distanceInside < 1.0f) {
// Point is too close to the border. Try nudging it inside.
const auto &shrunk = facecache.pointsShrunkBy1Unit();
if (!shrunk.empty()) {
const pair<int, qvec3f> closest = ClosestPointOnPolyBoundary(shrunk, point);
const qvec3f newPoint = closest.second + (qvec3f(plane) * sampleOffPlaneDist);
if (!Light_PointInAnySolid(bsp, mi->model, newPoint + modelOffset))
return position_t(face, newPoint, pointNormal);
}
}
#endif
return position_t(point);
}
return position_t(face, point, pointNormal);
}
/*
* =================
* CalcPoints
* For each texture aligned grid point, back project onto the plane
* to get the world xyz value of the sample point
* =================
*/
static void CalcPoints(
const modelinfo_t *modelinfo, const qvec3f &offset, lightsurf_t *surf, const mbsp_t *bsp, const mface_t *face)
{
const settings::worldspawn_keys &cfg = *surf->cfg;
surf->width = surf->extents.width() * light_options.extra.value();
surf->height = surf->extents.height() * light_options.extra.value();
const float starts = -0.5 + (0.5 / light_options.extra.value());
const float startt = -0.5 + (0.5 / light_options.extra.value());
const float st_step = 1.0f / light_options.extra.value();
/* Allocate surf->points */
size_t num_points = surf->width * surf->height;
surf->samples.resize(num_points);
const auto points = Face_Points(bsp, face);
const auto edgeplanes = MakeInwardFacingEdgePlanes(points);
for (int t = 0; t < surf->height; t++) {
for (int s = 0; s < surf->width; s++) {
const int i = t * surf->width + s;
auto &sample = surf->samples[i];
const double us = starts + s * st_step;
const double ut = startt + t * st_step;
sample.point =
surf->extents.LMCoordToWorld(qvec2f(us, ut)) + surf->plane.normal; // one unit in front of face
// do this before correcting the point, so we can wrap around the inside of pipes
const bool phongshaded = (surf->curved && cfg.phongallowed.value());
const auto res = CalcPointNormal(bsp, face, sample.point, phongshaded, surf->extents, 0, offset);
sample.occluded = !res.m_unoccluded;
sample.realfacenum = res.m_actualFace != nullptr ? Face_GetNum(bsp, res.m_actualFace) : -1;
sample.point = res.m_position + offset;
sample.normal = res.m_interpolatedNormal;
}
}
if (dump_facenum == Face_GetNum(bsp, face)) {
CalcPoints_Debug(surf, bsp);
}
}
static bool Mod_LeafPvs(const mbsp_t *bsp, const mleaf_t *leaf, uint8_t *out)
{
const size_t num_pvsclusterbytes = DecompressedVisSize(bsp);
// init to all visible
memset(out, 0xFF, num_pvsclusterbytes);
if (bsp->loadversion->game->id == GAME_QUAKE_II) {
auto it = UncompressedVis().find(leaf->cluster);
if (it == UncompressedVis().end()) {
return false;
}
memcpy(out, it->second.data(), num_pvsclusterbytes);
} else {
auto it = UncompressedVis().find(leaf->visofs);
if (it == UncompressedVis().end()) {
return false;
}
memcpy(out, it->second.data(), num_pvsclusterbytes);
}
return true;
}
static const std::vector<uint8_t> *Mod_LeafPvs(const mbsp_t *bsp, const mleaf_t *leaf)
{
if (bsp->loadversion->game->contents_are_liquid({leaf->contents})) {
// the liquid case is because leaf->contents might be in an opaque liquid,
// which we typically want light to pass through, but visdata would report that
// there's no visibility across the opaque liquid. so, skip culling and do the raytracing.
return nullptr;
}
const int key = (bsp->loadversion->game->id == GAME_QUAKE_II) ? leaf->cluster : leaf->visofs;
if (auto it = UncompressedVis().find(key); it != UncompressedVis().end()) {
return &it->second;
}
return nullptr;
}
static void CalcPvs(const mbsp_t *bsp, lightsurf_t *lightsurf)
{
const int pvssize = DecompressedVisSize(bsp);
const mleaf_t *lastleaf = nullptr;
// set defaults
lightsurf->pvs.clear();
if (!bsp->dvis.bits.size()) {
return;
}
// set lightsurf->pvs
uint8_t *pointpvs = (uint8_t *)alloca(pvssize);
lightsurf->pvs.resize(pvssize);
for (auto &sample : lightsurf->samples) {
const mleaf_t *leaf = Light_PointInLeaf(bsp, sample.point);
/* most/all of the surface points are probably in the same leaf */
if (leaf == lastleaf)
continue;
lastleaf = leaf;
/* copy the pvs for this leaf into pointpvs */
Mod_LeafPvs(bsp, leaf, pointpvs);
if (bsp->loadversion->game->contents_are_liquid({leaf->contents})) {
// hack for when the sample point might be in an opaque liquid, blocking vis,
// but we typically want light to pass through these.
// see also VisCullEntity() which handles the case when the light emitter is in liquid.
for (int j = 0; j < pvssize; j++) {
lightsurf->pvs[j] |= 0xff;
}
break;
}
/* merge the pvs for this sample point into lightsurf->pvs */
for (int j = 0; j < pvssize; j++) {
lightsurf->pvs[j] |= pointpvs[j];
}
}
}
static std::unique_ptr<lightsurf_t> Lightsurf_Init(const modelinfo_t *modelinfo, const settings::worldspawn_keys &cfg,
const mface_t *face, const mbsp_t *bsp, const facesup_t *facesup,
const bspx_decoupled_lm_perface *facesup_decoupled)
{
auto spaceToWorld = TexSpaceToWorld(bsp, face);
/* Check for invalid texture axes */
if (std::isnan(spaceToWorld.at(0, 0))) {
logging::print("Bad texture axes on face:\n");
PrintFaceInfo(face, bsp);
return nullptr;
}
auto lightsurf = std::make_unique<lightsurf_t>();
lightsurf->cfg = &cfg;
lightsurf->modelinfo = modelinfo;
lightsurf->bsp = bsp;
lightsurf->face = face;
lightsurf->occlusion_stream = std::make_unique<raystream_occlusion_t>();
lightsurf->intersection_stream = std::make_unique<raystream_intersection_t>();
if (Face_IsLightmapped(bsp, face)) {
/* if liquid doesn't have the TEX_SPECIAL flag set, the map was qbsp'ed with
* lit water in mind. In that case receive light from both top and bottom.
* (lit will only be rendered in compatible engines, but degrades gracefully.)
*/
lightsurf->twosided = Face_IsTranslucent(bsp, face);
// pick the larger of the two scales
lightsurf->lightmapscale =
(facesup && facesup->lmscale < modelinfo->lightmapscale) ? facesup->lmscale : modelinfo->lightmapscale;
const surfflags_t &extended_flags = extended_texinfo_flags[face->texinfo];
lightsurf->curved = extended_flags.phong_angle != 0 || Q2_FacePhongValue(bsp, face);
// override the autodetected twosided setting?
if (extended_flags.light_twosided) {
lightsurf->twosided = *extended_flags.light_twosided;
}
// nodirt
if (modelinfo->dirt.is_changed()) {
lightsurf->nodirt = (modelinfo->dirt.value() == -1);
} else {
lightsurf->nodirt = extended_flags.no_dirt;
}
// minlight
if (modelinfo->minlight.is_changed()) {
lightsurf->minlight = modelinfo->minlight.value();
} else if (extended_flags.minlight) {
lightsurf->minlight = *extended_flags.minlight;
} else {
lightsurf->minlight = light_options.minlight.value();
}
// minlightMottle
if (modelinfo->minlightMottle.is_changed()) {
lightsurf->minlightMottle = modelinfo->minlightMottle.value();
} else if (light_options.minlightMottle.is_changed()) {
lightsurf->minlightMottle = light_options.minlightMottle.value();
} else {
lightsurf->minlightMottle = false;
}
// Q2 uses a 0-1 range for minlight
if (bsp->loadversion->game->id == GAME_QUAKE_II) {
lightsurf->minlight *= 128.f;
}
// maxlight
if (modelinfo->maxlight.is_changed()) {
lightsurf->maxlight = modelinfo->maxlight.value();
} else {
lightsurf->maxlight = extended_flags.maxlight;
}
// lightcolorscale
if (modelinfo->lightcolorscale.is_changed()) {
lightsurf->lightcolorscale = modelinfo->lightcolorscale.value();
} else {
lightsurf->lightcolorscale = extended_flags.lightcolorscale;
}
// Q2 uses a 0-1 range for minlight
if (bsp->loadversion->game->id == GAME_QUAKE_II) {
lightsurf->maxlight *= 128.f;
}
// minlight_color
if (modelinfo->minlight_color.is_changed()) {
lightsurf->minlight_color = modelinfo->minlight_color.value();
} else if (!qv::emptyExact(extended_flags.minlight_color)) {
lightsurf->minlight_color = extended_flags.minlight_color;
} else {
lightsurf->minlight_color = light_options.minlight_color.value();
}
/* never receive dirtmapping on lit liquids */
if (Face_IsTranslucent(bsp, face)) {
lightsurf->nodirt = true;
}
/* handle glass alpha */
if (modelinfo->alpha.value() < 1) {
/* skip culling of rays coming from the back side of the face */
lightsurf->twosided = true;
}
/* object channel mask */
if (extended_flags.object_channel_mask) {
lightsurf->object_channel_mask = *extended_flags.object_channel_mask;
} else {
lightsurf->object_channel_mask = modelinfo->object_channel_mask.value();
}
if (extended_flags.surflight_minlight_scale) {
lightsurf->surflight_minlight_scale = *extended_flags.surflight_minlight_scale;
} else {
lightsurf->surflight_minlight_scale = 1.0f;
}
/* Set up the plane, not including model offset */
qplane3f &plane = lightsurf->plane;
if (face->side) {
plane = -bsp->dplanes[face->planenum];
} else {
plane = bsp->dplanes[face->planenum];
}
const mtexinfo_t *tex = &bsp->texinfo[face->texinfo];
lightsurf->snormal = qv::normalize(tex->vecs.row(0).xyz());
lightsurf->tnormal = -qv::normalize(tex->vecs.row(1).xyz());
/* Set up the surface points */
if (light_options.world_units_per_luxel.is_changed()) {
if (bsp->loadversion->game->id == GAME_QUAKE_II && (Face_Texinfo(bsp, face)->flags.native & Q2_SURF_SKY)) {
lightsurf->extents = faceextents_t(*face, *bsp, world_units_per_luxel_t{}, 512.f);
} else if (extended_flags.world_units_per_luxel) {
lightsurf->extents =
faceextents_t(*face, *bsp, world_units_per_luxel_t{}, *extended_flags.world_units_per_luxel);
} else {
lightsurf->extents =
faceextents_t(*face, *bsp, world_units_per_luxel_t{}, light_options.world_units_per_luxel.value());
}
} else {
lightsurf->extents = faceextents_t(*face, *bsp, lightsurf->lightmapscale);
}
lightsurf->vanilla_extents = faceextents_t(*face, *bsp, LMSCALE_DEFAULT);
CalcPoints(modelinfo, modelinfo->offset, lightsurf.get(), bsp, face);
/* Correct the plane for the model offset (must be done last,
calculation of face extents / points needs the uncorrected plane) */
qvec3f planepoint = (plane.normal * plane.dist) + modelinfo->offset;
plane.dist = qv::dot(plane.normal, planepoint);
/* Correct bounding sphere */
lightsurf->extents.origin += modelinfo->offset;
lightsurf->extents.bounds = lightsurf->extents.bounds.translate(modelinfo->offset);
lightsurf->intersection_stream->resize(lightsurf->samples.size());
lightsurf->occlusion_stream->resize(lightsurf->samples.size());
/* Setup vis data */
CalcPvs(bsp, lightsurf.get());
}
// emissiveness is handled later and allocated only if necessary
return lightsurf;
}
static void Lightmap_AllocOrClear(lightmap_t *lightmap, const lightsurf_t *lightsurf)
{
if (!lightmap->samples.size()) {
/* first use of this lightmap, allocate the storage for it. */
lightmap->samples.resize(lightsurf->samples.size());
} else if (lightmap->style != INVALID_LIGHTSTYLE) {
/* clear only the data that is going to be merged to it. there's no point clearing more */
std::fill_n(lightmap->samples.begin(), lightsurf->samples.size(), lightsample_t{});
lightmap->bounce_color = {};
}
}
#if 0
static const lightmap_t *Lightmap_ForStyle_ReadOnly(const lightsurf_t *lightsurf, const int style)
{
for (const auto &lm : lightsurf->lightmapsByStyle) {
if (lm.style == style)
return &lm;
}
return nullptr;
}
#endif
/*
* Lightmap_ForStyle
*
* If lightmap with given style has already been allocated, return it.
* Otherwise, return the next available map. A new map is not marked as
* allocated since it may not be kept if no lights hit.
*/
static lightmap_t *Lightmap_ForStyle(lightmapdict_t *lightmaps, const int style, const lightsurf_t *lightsurf)
{
for (auto &lm : *lightmaps) {
if (lm.style == style)
return &lm;
}
// no exact match, check for an unsaved one
for (auto &lm : *lightmaps) {
if (lm.style == INVALID_LIGHTSTYLE) {
Lightmap_AllocOrClear(&lm, lightsurf);
return &lm;
}
}
// add a new one to the vector (invalidates existing lightmap_t pointers)
lightmap_t &newLightmap = lightmaps->emplace_back();
newLightmap.style = INVALID_LIGHTSTYLE;
Lightmap_AllocOrClear(&newLightmap, lightsurf);
return &newLightmap;
}
/*
* Lightmap_Save
*
* As long as we have space for the style, mark as allocated,
* otherwise emit a warning.
*/
static void Lightmap_Save(
const mbsp_t *bsp, lightmapdict_t *lightmaps, const lightsurf_t *lightsurf, lightmap_t *lightmap, const int style)
{
Q_assert(Face_IsLightmapped(bsp, lightsurf->face));
if (lightmap->style == INVALID_LIGHTSTYLE) {
lightmap->style = style;
}
}
/*
* ============================================================================
* FACE LIGHTING
* ============================================================================
*/
// returns the light contribution at a given distance, without regard for angle
double GetLightValue(const settings::worldspawn_keys &cfg, const light_t *entity, double dist)
{
const float light = entity->light.value();
// mxd. Apply falloff?
const float lightdistance = entity->falloff.value();
if (lightdistance > 0.0f) {
if (entity->getFormula() == LF_LINEAR) {
// Light can affect surface?
if (lightdistance > dist)
return light * (1.0f - (dist / lightdistance));
else
return 0.0f; // Surface is unaffected
}
}
if (entity->getFormula() == LF_INFINITE || entity->getFormula() == LF_LOCALMIN)
return light;
double value = cfg.scaledist.value() * entity->atten.value() * dist;
switch (entity->getFormula()) {
case LF_INVERSE: return light / (value / LF_SCALE);
case LF_INVERSE2A:
value += LF_SCALE;
/* Fall through */
case LF_INVERSE2: return light / ((value * value) / (LF_SCALE * LF_SCALE));
case LF_LINEAR:
if (light > 0)
return (light - value > 0) ? light - value : 0;
else
return (light + value < 0) ? light + value : 0;
default: Error("Internal error: unknown light formula");
}
}
static float GetLightValueWithAngle(const settings::worldspawn_keys &cfg, const light_t *entity, const qvec3f &surfnorm,
bool use_surfnorm, const qvec3f &surfpointToLightDir, float dist, bool twosided)
{
float angle;
if (use_surfnorm) {
angle = qv::dot(surfpointToLightDir, surfnorm);
} else {
angle = 1.0f;
}
if (entity->bleed.value() || twosided) {
if (angle < 0) {
angle = -angle; // ericw -- support "_bleed" option
}
}
/* Light behind sample point? Zero contribution, period.
see: https://github.com/ericwa/ericw-tools/issues/181 */
if (angle < 0) {
return 0;
}
/* Apply anglescale */
angle = (1.0 - entity->anglescale.value()) + (entity->anglescale.value() * angle);
/* Check spotlight cone */
float spotscale = 1;
if (entity->spotlight) {
const float falloff = qv::dot(entity->spotvec, surfpointToLightDir);
if (falloff > entity->spotfalloff) {
return 0;
}
if (falloff > entity->spotfalloff2) {
/* Interpolate between the two spotlight falloffs */
spotscale = falloff - entity->spotfalloff2;
spotscale /= entity->spotfalloff - entity->spotfalloff2;
spotscale = 1.0 - spotscale;
}
}
float add = GetLightValue(cfg, entity, dist) * angle * spotscale;
return add;
}
template<typename T>
static void Matrix4x4_CM_Transform4(const std::array<T, 16> &matrix, const qvec<T, 4> &vector, qvec<T, 4> &product)
{
product[0] = matrix[0] * vector[0] + matrix[4] * vector[1] + matrix[8] * vector[2] + matrix[12] * vector[3];
product[1] = matrix[1] * vector[0] + matrix[5] * vector[1] + matrix[9] * vector[2] + matrix[13] * vector[3];
product[2] = matrix[2] * vector[0] + matrix[6] * vector[1] + matrix[10] * vector[2] + matrix[14] * vector[3];
product[3] = matrix[3] * vector[0] + matrix[7] * vector[1] + matrix[11] * vector[2] + matrix[15] * vector[3];
}
template<typename T>
static bool Matrix4x4_CM_Project(const qvec<T, 3> &in, qvec<T, 3> &out, const std::array<T, 16> &modelviewproj)
{
bool result = true;
qvec<T, 4> v;
Matrix4x4_CM_Transform4(modelviewproj, {in, 1}, v);
v[0] /= v[3];
v[1] /= v[3];
if (v[2] < 0)
result = false; // too close to the view
v[2] /= v[3];
out[0] = (1 + v[0]) / 2;
out[1] = (1 + v[1]) / 2;
out[2] = (1 + v[2]) / 2;
if (out[2] > 1)
result = false; // beyond far clip plane
return result;
}
static bool LightFace_SampleMipTex(
const img::texture *tex, const std::array<float, 16> &projectionmatrix, const qvec3f &point, qvec3f &result)
{
// okay, yes, this is weird, yes we're using a vec3_t for a coord...
// this is because we're treating it like a cubemap. why? no idea.
float weight[4];
qvec4b pi[4];
qvec3f coord;
if (!Matrix4x4_CM_Project(point, coord, projectionmatrix) || coord[0] <= 0 || coord[0] >= 1 || coord[1] <= 0 ||
coord[1] >= 1) {
result = {};
return false; // mxd
}
float sfrac = (coord[0]) * (tex->meta.width - 1); // mxd. We are sampling sbase+1 pixels, so multiplying by
// tex->width will result in an 1px overdraw, same for tbase
const int sbase = sfrac;
sfrac -= sbase;
float tfrac = (1 - coord[1]) * (tex->meta.height - 1);
const int tbase = tfrac;
tfrac -= tbase;
pi[0] = tex->pixels[((sbase + 0) % tex->meta.width) + (tex->meta.width * ((tbase + 0) % tex->meta.height))];
weight[0] = (1 - sfrac) * (1 - tfrac);
pi[1] = tex->pixels[((sbase + 1) % tex->meta.width) + (tex->meta.width * ((tbase + 0) % tex->meta.height))];
weight[1] = (sfrac) * (1 - tfrac);
pi[2] = tex->pixels[((sbase + 0) % tex->meta.width) + (tex->meta.width * ((tbase + 1) % tex->meta.height))];
weight[2] = (1 - sfrac) * (tfrac);
pi[3] = tex->pixels[((sbase + 1) % tex->meta.width) + (tex->meta.width * ((tbase + 1) % tex->meta.height))];
weight[3] = (sfrac) * (tfrac);
result = pi[0].xyz() * weight[0] + pi[1].xyz() * weight[1] + pi[2].xyz() * weight[2] + pi[3].xyz() * weight[3];
result *= 2;
return true;
}
static void GetLightContrib(const settings::worldspawn_keys &cfg, const light_t *entity, const qvec3f &surfnorm,
bool use_surfnorm, const qvec3f &surfpoint, bool twosided, qvec3f &color_out, qvec3f &surfpointToLightDir_out,
qvec3f &normalmap_addition_out, float *dist_out)
{
float dist = GetDir(surfpoint, entity->origin.value(), surfpointToLightDir_out);
if (dist < 0.1) {
// Catch 0 distance between sample point and light (produces infinite brightness / nan's) and causes
// problems later
dist = 0.1f;
surfpointToLightDir_out = {0, 0, 1};
}
const float add =
GetLightValueWithAngle(cfg, entity, surfnorm, use_surfnorm, surfpointToLightDir_out, dist, twosided);
/* write out the final color */
if (entity->projectedmip) {
qvec3f col;
if (LightFace_SampleMipTex(entity->projectedmip, entity->projectionmatrix, surfpoint, col)) {
// mxd. Modulate by light color...
const auto &entcol = entity->color.value();
for (int i = 0; i < 3; i++)
col[i] *= entcol[i] * (1.0f / 255.0f);
}
color_out = col * add * (1.0f / 255.0f);
} else {
color_out = entity->color.value() * add * (1.0f / 255.0f);
}
// write normalmap contrib
normalmap_addition_out = surfpointToLightDir_out * add;
*dist_out = dist;
}
constexpr double SQR(double x)
{
return x * x;
}
// CHECK: naming? why clamp*min*?
constexpr bool Light_ClampMin(lightsample_t &sample, const double light, const qvec3f &color)
{
bool changed = false;
for (int i = 0; i < 3; i++) {
float c = (float)(color[i] * (light / 255.0f));
if (c > sample.color[i]) {
sample.color[i] = c;
changed = true;
}
}