-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathllightmapper.cpp
2003 lines (1543 loc) · 50.2 KB
/
llightmapper.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
#include "llightmapper.h"
#include "core/os/threaded_array_processor.h"
#include "llightprobe.h"
#include "llightscene.h"
#include "lmerger.h"
#include "lscene_saver.h"
#include "lunmerger.h"
#include "scene/resources/packed_scene.h"
namespace LM {
bool LightMapper::uv_map_meshes(Spatial *pRoot) {
if (m_Settings_UVFilename == "") {
ShowWarning("UV Filename is not set, aborting.");
return false;
}
CalculateQualityAdjustedSettings();
bool replace_mesh_scene = false;
if (!pRoot)
return false;
// can't do uv mapping if not tools build, as xatlas isn't compiled
if (bake_begin_function) {
bake_begin_function(4);
}
if (bake_step_function) {
bake_step_function(0, String("Saving uvmap_backup.tscn"));
}
// first back up the existing meshes scene.
SceneSaver saver;
saver.SaveScene(pRoot, "res://uvmap_backup.tscn");
if (bake_step_function) {
bake_step_function(1, String("Merging to proxy"));
}
Merger m;
MeshInstance *pMerged = m.Merge(pRoot, m_Settings_UVPadding);
if (!pMerged) {
if (bake_end_function) {
bake_end_function();
}
return false;
}
// test save the merged mesh
//saver.SaveScene(pMerged, "res://merged_test.tscn");
if (bake_step_function) {
bake_step_function(2, String("Unmerging"));
}
// unmerge
UnMerger u;
bool res = u.UnMerge(m, *pMerged);
// for debug save the merged version
saver.SaveScene(pMerged, "res://merged_proxy.tscn");
pMerged->queue_delete();
if (bake_step_function) {
bake_step_function(2, String("Saving"));
}
// if we specified an output file, save
if (m_Settings_UVFilename != "") {
Node *pOrigOwner = pRoot->get_owner();
if (!saver.SaveScene(pRoot, m_Settings_UVFilename, true)) {
ShowWarning("Error saving UV mapped scene. Does the folder exist?\n\n" + m_Settings_UVFilename);
}
if (replace_mesh_scene) {
// delete the orig
Node *pParent = pRoot->get_parent();
// rename the old scene to prevent naming conflict
pRoot->set_name("ToBeDeleted");
pRoot->queue_delete();
// now load the new file
//ResourceLoader::import(m_Settings_UVFilename);
Ref<PackedScene> ps = ResourceLoader::load(m_Settings_UVFilename, "PackedScene");
if (ps.is_null()) {
if (bake_end_function) {
bake_end_function();
}
return res;
}
Node *pFinalScene = ps->instance();
if (pFinalScene) {
pParent->add_child(pFinalScene);
// set owners
saver.SetOwnerRecursive(pFinalScene, pFinalScene);
pFinalScene->set_owner(pOrigOwner);
}
} // if replace the scene
else {
// delete, to save confusion
pRoot->queue_delete();
}
}
if (bake_end_function) {
bake_end_function();
}
return res;
}
bool LightMapper::lightmap_mesh(Spatial *pMeshesRoot, Spatial *pLR, Image *pIm_Lightmap, Image *pIm_AO, Image *pIm_Combined) {
CalculateQualityAdjustedSettings();
// get the output dimensions before starting, because we need this
// to determine number of rays, and the progress range
m_iWidth = pIm_Combined->get_width();
m_iHeight = pIm_Combined->get_height();
m_iNumRays = m_AdjustedSettings.m_Forward_NumRays;
int nTexels = m_iWidth * m_iHeight;
// set num rays depending on method
if (m_Settings_Mode == LMMODE_FORWARD) {
// the num rays / texel. This is per light!
m_iNumRays *= nTexels;
}
// do twice to test SIMD
uint32_t beforeA = OS::get_singleton()->get_ticks_msec();
m_Scene.m_bUseSIMD = true;
m_Scene.m_Tracer.m_bSIMD = true;
bool res = LightmapMesh(pMeshesRoot, *pLR, *pIm_Lightmap, *pIm_AO, *pIm_Combined);
uint32_t afterA = OS::get_singleton()->get_ticks_msec();
print_line("Overall took : " + itos(afterA - beforeA));
return res;
}
void LightMapper::Reset() {
m_Lights.clear(true);
m_Scene.Reset();
RayBank_Reset();
Base_Reset();
}
void LightMapper::Refresh_Process_State() {
// defaults
m_Logic_Process_Lightmap = true;
m_Logic_Process_AO = true;
m_Logic_Reserve_AO = true;
m_Logic_Process_Probes = false;
m_Logic_Output_Final = true;
// process states
switch (m_Settings_BakeMode) {
case LMBAKEMODE_PROBES: {
m_Logic_Process_Probes = true;
m_Logic_Process_Lightmap = false;
m_Logic_Process_AO = false;
m_Logic_Output_Final = false;
} break;
case LMBAKEMODE_LIGHTMAP: {
m_Logic_Process_AO = false;
m_Logic_Reserve_AO = false;
} break;
case LMBAKEMODE_AO: {
m_Logic_Process_Lightmap = false;
} break;
case LMBAKEMODE_MERGE: {
m_Logic_Process_Lightmap = false;
m_Logic_Process_AO = false;
} break;
case LMBAKEMODE_UVMAP: {
m_Logic_Process_Lightmap = false;
m_Logic_Process_AO = false;
m_Logic_Reserve_AO = false;
m_Logic_Output_Final = false;
} break;
default: {
} break;
}
}
bool LightMapper::LightmapMesh(Spatial *pMeshesRoot, const Spatial &light_root, Image &out_image_lightmap, Image &out_image_ao, Image &out_image_combined) {
// print out settings
print_line("Lightmap mesh");
print_line("\tnum_directional_bounces " + itos(m_AdjustedSettings.m_NumDirectionalBounces));
print_line("\tdirectional_bounce_power " + String(Variant(m_Settings_DirectionalBouncePower)));
Refresh_Process_State();
Reset();
m_bCancel = false;
if (m_iWidth <= 0)
return false;
if (m_iHeight <= 0)
return false;
// create stuff used by everything
m_Image_L.Create(m_iWidth, m_iHeight);
m_Image_L_mirror.Create(m_iWidth, m_iHeight);
// whether we need storage
if (m_Logic_Reserve_AO)
m_Image_AO.Create(m_iWidth, m_iHeight);
if (m_Settings_BakeMode != LMBAKEMODE_MERGE) {
if (m_Logic_Process_AO)
m_QMC.Create(m_AdjustedSettings.m_AO_Samples);
uint32_t before, after;
FindLights_Recursive(&light_root);
print_line("Found " + itos(m_Lights.size()) + " lights.");
m_Image_ID_p1.Create(m_iWidth, m_iHeight);
//m_Image_ID2_p1.Create(m_iWidth, m_iHeight);
if (m_Logic_Process_AO) {
m_Image_TriIDs.Create(m_iWidth, m_iHeight);
m_TriIDs.clear(true);
}
m_Image_Barycentric.Create(m_iWidth, m_iHeight);
//m_Image_Cuts.Create(m_iWidth, m_iHeight);
//m_CuttingTris.clear(true);
print_line("Scene Create");
before = OS::get_singleton()->get_ticks_msec();
if (!m_Scene.Create(pMeshesRoot, m_iWidth, m_iHeight, m_Settings_VoxelDensity, m_AdjustedSettings.m_Max_Material_Size, m_AdjustedSettings.m_EmissionDensity))
return false;
PrepareLights();
RayBank_Create();
after = OS::get_singleton()->get_ticks_msec();
print_line("SceneCreate took " + itos(after - before) + " ms");
if (m_bCancel)
return false;
print_line("PrepareImageMaps");
before = OS::get_singleton()->get_ticks_msec();
PrepareImageMaps();
after = OS::get_singleton()->get_ticks_msec();
print_line("PrepareImageMaps took " + itos(after - before) + " ms");
if (m_bCancel)
return false;
if (m_Logic_Process_AO) {
print_line("ProcessAO");
before = OS::get_singleton()->get_ticks_msec();
ProcessAO();
after = OS::get_singleton()->get_ticks_msec();
print_line("ProcessAO took " + itos(after - before) + " ms");
//Convolve_AO();
}
if (m_Logic_Process_Lightmap) {
print_line("ProcessTexels");
before = OS::get_singleton()->get_ticks_msec();
if (m_Settings_Mode == LMMODE_BACKWARD)
ProcessTexels();
else {
ProcessLights();
ProcessEmissionTris();
}
DoAmbientBounces();
after = OS::get_singleton()->get_ticks_msec();
print_line("ProcessTexels took " + itos(after - before) + " ms");
}
if (m_Logic_Process_Probes) {
// calculate probes
print_line("ProcessProbes");
if (LoadLightmap(out_image_lightmap)) {
ProcessLightProbes();
}
}
if (m_bCancel)
return false;
if (!m_Logic_Process_Probes) {
WriteOutputImage_Lightmap(out_image_lightmap);
WriteOutputImage_AO(out_image_ao);
// test convolution
// Merge_AndWriteOutputImage_Combined(out_image_combined);
// out_image_combined.save_png("before_convolve.png");
// WriteOutputImage_AO(out_image_ao, true);
}
} // if not just merging
else {
// merging
// need the meshes list for seam stitching
m_Scene.FindMeshes(pMeshesRoot);
// load the lightmap and ao from disk
LoadLightmap(out_image_lightmap);
LoadAO(out_image_ao);
}
// print_line("WriteOutputImage");
// before = OS::get_singleton()->get_ticks_msec();
if (m_Logic_Output_Final)
Merge_AndWriteOutputImage_Combined(out_image_combined);
// after = OS::get_singleton()->get_ticks_msec();
// print_line("WriteOutputImage took " + itos(after -before) + " ms");
// clear everything out of ram as no longer needed
Reset();
return true;
}
void LightMapper::ProcessTexels_AmbientBounce_Line_MT(uint32_t offset_y, int start_y) {
int y = offset_y + start_y;
for (int x = 0; x < m_iWidth; x++) {
FColor power = ProcessTexel_AmbientBounce(x, y);
// save the incoming light power in the mirror image (as the source is still being used)
m_Image_L_mirror.GetItem(x, y) = power;
}
}
void LightMapper::ProcessTexels_AmbientBounce(int section_size, int num_sections) {
m_Image_L_mirror.Blank();
// disable multithread
//num_sections = 0;
for (int s = 0; s < num_sections; s++) {
int section_start = s * section_size;
if (bake_step_function) {
m_bCancel = bake_step_function(section_start, String("Process TexelsBounce: ") + " (" + itos(section_start) + ")");
if (m_bCancel) {
if (bake_end_function)
bake_end_function();
return;
}
}
thread_process_array(section_size, this, &LightMapper::ProcessTexels_AmbientBounce_Line_MT, section_start);
// for (int n=0; n<section_size; n++)
// {
// ProcessTexel_Line_MT(n, section_start);
// }
}
int leftover_start = num_sections * section_size;
for (int y = leftover_start; y < m_iHeight; y++) {
if ((y % 10) == 0) {
// print_line("\tTexels bounce line " + itos(y));
// OS::get_singleton()->delay_usec(1);
if (bake_step_function) {
m_bCancel = bake_step_function(y, String("Process TexelsBounce: ") + " (" + itos(y) + ")");
if (m_bCancel)
return;
}
}
ProcessTexels_AmbientBounce_Line_MT(y, 0);
// for (int x=0; x<m_iWidth; x++)
// {
// FColor power = ProcessTexel_Bounce(x, y);
// // save the incoming light power in the mirror image (as the source is still being used)
// m_Image_L_mirror.GetItem(x, y) = power;
// }
}
// merge the 2 luminosity maps
for (int y = 0; y < m_iHeight; y++) {
for (int x = 0; x < m_iWidth; x++) {
FColor col = m_Image_L.GetItem(x, y);
FColor col_add = m_Image_L_mirror.GetItem(x, y) * m_Settings_AmbientBouncePower;
// assert (col_add.r >= 0.0f);
// assert (col_add.g >= 0.0f);
// assert (col_add.b >= 0.0f);
col += col_add;
m_Image_L.GetItem(x, y) = col;
}
}
}
void LightMapper::Backward_TraceTriangles() {
int nTris = m_Scene.m_Tris.size();
if (bake_begin_function) {
int progress_range = nTris;
bake_begin_function(progress_range);
}
for (int n = 0; n < nTris; n++) {
if ((n % 128) == 0) {
if (bake_step_function) {
m_bCancel = bake_step_function(n, String("Process Backward Tris: ") + " (" + itos(n) + ")");
if (m_bCancel) {
if (bake_end_function)
bake_end_function();
return;
}
}
}
Backward_TraceTriangle(n);
}
if (bake_end_function) {
bake_end_function();
}
}
void LightMapper::Backward_TraceTriangle(int tri_id) {
const UVTri &tri = m_Scene.m_UVTris[tri_id];
float area = tri.CalculateTwiceArea();
if (area < 0.0f)
area = -area;
int nSamples = area * 400000.0f * m_AdjustedSettings.m_Backward_NumRays;
for (int n = 0; n < nSamples; n++) {
Backward_TraceSample(tri_id);
}
}
void LightMapper::Backward_TraceSample(int tri_id) {
const UVTri &uv_tri = m_Scene.m_UVTris[tri_id];
const Tri &tri = m_Scene.m_Tris[tri_id];
// choose random point on triangle
Vector3 bary;
RandomBarycentric(bary);
// test, clamp the barycentric
// bary *= 0.998f;
// bary += Vector3(0.001f, 0.001f, 0.001f);
// get position in world space
Vector3 pos;
tri.InterpolateBarycentric(pos, bary);
// test, pull in a little
//pos = pos.linear_interpolate(tri.GetCentre(), 0.001f);
// get uv / texel position
Vector2 uv;
uv_tri.FindUVBarycentric(uv, bary);
uv.x *= m_iWidth;
uv.y *= m_iHeight;
// round?
int tx = uv.x;
int ty = uv.y;
// int tx = Math::round(uv.x);
// int ty = Math::round(uv.y);
// could be off the image
FColor *pTexel = m_Image_L.Get(tx, ty);
if (!pTexel)
return;
// apply bias
// add epsilon to pos to prevent self intersection and neighbour intersection
const Vector3 &plane_normal = m_Scene.m_TriPlanes[tri_id].normal;
pos += plane_normal * m_Settings_SurfaceBias;
// interpolated normal
Vector3 normal;
m_Scene.m_TriNormals[tri_id].InterpolateBarycentric(normal, bary.x, bary.y, bary.z);
FColor temp;
for (int l = 0; l < m_Lights.size(); l++) {
BF_ProcessTexel_Light(Color(), l, pos, plane_normal, normal, temp, 1);
*pTexel += temp;
}
// add emission
Color emission_tex_color;
Color emission_color;
if (m_Scene.FindEmissionColor(tri_id, bary, emission_tex_color, emission_color)) {
FColor femm;
femm.Set(emission_tex_color);
// float power = m_Settings_Backward_RayPower * m_AdjustedSettings.m_Backward_NumRays * 128.0f;
float power = m_Settings_Backward_RayPower * 128.0f;
*pTexel += femm * power;
}
}
void LightMapper::ProcessTexels() {
//Backward_TraceTriangles();
//return;
//int nCores = OS::get_singleton()->get_processor_count();
int section_size = m_iHeight / 64; //nCores;
int num_sections = m_iHeight / section_size;
int leftover_start = 0;
if (bake_begin_function) {
int progress_range = m_iHeight;
bake_begin_function(progress_range);
}
m_iNumTests = 0;
// load sky
m_Sky.load_sky(m_Settings_Sky_Filename, m_Settings_Sky_BlurAmount, m_Settings_Sky_Size);
// prevent multithread
#ifndef BACKWARD_TRACE_MULTITHEADED
num_sections = 0;
#endif
for (int s = 0; s < num_sections; s++) {
int section_start = s * section_size;
if (bake_step_function) {
m_bCancel = bake_step_function(section_start, String("Process Texels: ") + " (" + itos(section_start) + ")");
if (m_bCancel) {
if (bake_end_function)
bake_end_function();
return;
}
}
thread_process_array(section_size, this, &LightMapper::ProcessTexel_Line_MT, section_start);
// for (int n=0; n<section_size; n++)
// {
// ProcessTexel_Line_MT(n, section_start);
// }
}
leftover_start = num_sections * section_size;
for (int y = leftover_start; y < m_iHeight; y++) {
if ((y % 10) == 0) {
//print_line("\tTexels line " + itos(y));
//OS::get_singleton()->delay_usec(1);
if (bake_step_function) {
m_bCancel = bake_step_function(y, String("Process Texels: ") + " (" + itos(y) + ")");
if (m_bCancel) {
if (bake_end_function)
bake_end_function();
return;
}
}
}
ProcessTexel_Line_MT(y, 0);
}
// m_iNumTests /= (m_iHeight * m_iWidth);
print_line("num tests : " + itos(m_iNumTests));
m_Sky.unload_sky();
if (bake_end_function) {
bake_end_function();
}
}
void LightMapper::DoAmbientBounces() {
if (!m_AdjustedSettings.m_NumAmbientBounces)
return;
int section_size = m_iHeight / 64; //nCores;
int num_sections = m_iHeight / section_size;
if (bake_begin_function) {
int progress_range = m_iHeight;
bake_begin_function(progress_range);
}
for (int b = 0; b < m_AdjustedSettings.m_NumAmbientBounces; b++) {
if (!m_bCancel)
ProcessTexels_AmbientBounce(section_size, num_sections);
}
if (bake_end_function) {
bake_end_function();
}
}
void LightMapper::ProcessTexel_Line_MT(uint32_t offset_y, int start_y) {
int y = offset_y + start_y;
for (int x = 0; x < m_iWidth; x++) {
BF_ProcessTexel(x, y);
}
}
bool LightMapper::Light_RandomSample(const LLight &light, const Vector3 &ptSurf, Ray &ray, Vector3 &ptLight, float &ray_length, float &multiplier) const {
// for a spotlight, we can cull completely in a lot of cases.
if (light.type == LLight::LT_SPOT) {
Ray r;
r.o = light.spot_emanation_point;
r.d = ptSurf - r.o;
r.d.normalize();
float dot = r.d.dot(light.dir);
//float angle = safe_acosf(dot);
//if (angle >= light.spot_angle_radians)
dot -= light.spot_dot_max;
if (dot <= 0.0f)
return false;
}
// default
multiplier = 1.0f;
switch (light.type) {
case LLight::LT_DIRECTIONAL: {
// we set this to maximum, better not to check at all but makes code simpler
ray_length = FLT_MAX;
ray.o = ptSurf;
//r.d = -light.dir;
// perturb direction depending on light scale
//Vector3 ptTarget = light.dir * -2.0f;
Vector3 offset;
RandomUnitDir(offset);
offset *= light.scale;
offset += (light.dir * -2.0f);
ray.d = offset.normalized();
// disallow zero length (should be rare)
if (ray.d.length_squared() < 0.00001f)
return false;
// don't allow from opposite direction
if (ray.d.dot(light.dir) > 0.0f)
ray.d = -ray.d;
// this is used for intersection test to see
// if e.g. sun is obscured. So we make the light position a long way from the origin
ptLight = ptSurf + (ray.d * 10000000.0f);
} break;
case LLight::LT_SPOT: {
// source
float dot;
while (true) {
Vector3 offset;
RandomUnitDir(offset);
offset *= light.scale;
ray.o = light.pos;
ray.o += offset;
// offset from origin to destination texel
ray.d = ptSurf - ray.o;
// normalize and find length
ray_length = NormalizeAndFindLength(ray.d);
dot = ray.d.dot(light.dir);
//float angle = safe_acosf(dot);
//if (angle >= light.spot_angle_radians)
dot -= light.spot_dot_max;
// if within cone, it is ok
if (dot > 0.0f)
break;
}
// store the light sample point
ptLight = ray.o;
// reverse ray for precision reasons
ray.d = -ray.d;
ray.o = ptSurf;
dot *= 1.0f / (1.0f - light.spot_dot_max);
multiplier = dot * dot;
multiplier *= multiplier;
} break;
default: {
Vector3 offset;
RandomUnitDir(offset);
offset *= light.scale;
ptLight = light.pos + offset;
// offset from origin to destination texel
ray.o = ptSurf;
ray.d = ptLight - ray.o;
// normalize and find length
ray_length = NormalizeAndFindLength(ray.d);
// safety
//assert (r.d.length() > 0.0f);
} break;
}
// by this point...
// ray should be set, ray_length, and ptLight
return true;
}
bool LightMapper::BF_ProcessTexel_Sky(const Color &orig_albedo, const Vector3 &ptSource, const Vector3 &orig_face_normal, const Vector3 &orig_vertex_normal, FColor &color) {
color.Set(0.0);
if (!m_Sky.is_active())
return false;
if (m_Settings_Sky_Brightness == 0.0f)
return false;
Ray r;
// we need more samples for sky, than for a normal light
//nSamples *= 4;
int nSamples = m_AdjustedSettings.m_Sky_Samples;
FColor total;
total.Set(0.0);
for (int s = 0; s < nSamples; s++) {
r.o = ptSource;
Vector3 offset;
RandomUnitDir(offset);
// offset += (light.dir * -2.0f);
// r.d = offset.normalized();
r.d = offset;
// disallow zero length (should be rare)
// if (r.d.length_squared() < 0.00001f)
// continue;
// don't allow from opposite direction
if (r.d.dot(orig_face_normal) < 0.0f)
r.d = -r.d;
// ray test
if (!m_Scene.TestIntersect_Ray(r, FLT_MAX)) {
m_Sky.read_sky(r.d, total);
}
} // for s
color = total * (m_AdjustedSettings.m_Sky_Brightness * (64.0 / nSamples));
return true;
}
// trace from the poly TO the light, not the other way round, to avoid precision errors
void LightMapper::BF_ProcessTexel_Light(const Color &orig_albedo, int light_id, const Vector3 &ptSource, const Vector3 &orig_face_normal, const Vector3 &orig_vertex_normal, FColor &color, int nSamples) //, uint32_t tri_ignore)
{
const LLight &light = m_Lights[light_id];
Ray r;
float power = light.energy;
power *= m_Settings_Backward_RayPower;
//int nSamples = m_AdjustedSettings.m_Backward_NumRays;
// total light hitting texel
color.Set(0.0f);
// for a spotlight, we can cull completely in a lot of cases.
if (light.type == LLight::LT_SPOT) {
r.o = light.spot_emanation_point;
r.d = ptSource - r.o;
r.d.normalize();
float dot = r.d.dot(light.dir);
//float angle = safe_acosf(dot);
//if (angle >= light.spot_angle_radians)
dot -= light.spot_dot_max;
if (dot <= 0.0f)
return;
// cull by surface back facing NYI
}
// lower power of directionals - no distance falloff
if (light.type == LLight::LT_DIRECTIONAL) {
power *= 0.08f;
// cull by back face determined by the sky softness ... NYI
}
// omni cull by distance?
// cull by surface normal .. anything facing away gets no light (plus a bit for wraparound)
// about 5% faster with this cull with a lot of omnis
if (light.type == LLight::LT_OMNI) {
Vector3 light_vec = light.pos - ptSource;
float light_dist = light_vec.length();
// cull by dist test
if (m_Settings_MaxLightDist) {
if ((int)light_dist > m_Settings_MaxLightDist)
return;
}
float radius = MAX(light.scale.x, light.scale.y);
radius = MAX(radius, light.scale.z);
// we can only cull if outside the radius of the light
if (light_dist > radius) {
// normalize light vec
light_vec *= 1.0f / light_dist;
// angle in radians from the surface to the furthest points on the sphere
float theta = Math::asin(CLAMP(radius / light_dist, 0.0f, 1.0f));
float dot_threshold = Math::cos(theta + Math_PI / 2.0);
float dot_light_surf = orig_vertex_normal.dot(light_vec);
// doesn't need an epsilon, because at 90 degrees the dot will be zero
// and the lighting will be zero.
if (dot_light_surf < dot_threshold)
return;
}
}
// for quick primary test on the last blocking triangle
int quick_reject_tri_id = -1;
// each ray
for (int n = 0; n < nSamples; n++) {
Vector3 ptDest = light.pos;
// allow falloff for cones
float multiplier = 1.0f;
// if the hit point is further that the distance to the light, then it doesn't count
// must be set by the light type
float ray_length;
switch (light.type) {
case LLight::LT_DIRECTIONAL: {
// we set this to maximum, better not to check at all but makes code simpler
ray_length = FLT_MAX;
r.o = ptSource;
//r.d = -light.dir;
// perturb direction depending on light scale
//Vector3 ptTarget = light.dir * -2.0f;
Vector3 offset;
RandomUnitDir(offset);
offset *= light.scale;
offset += (light.dir * -2.0f);
r.d = offset.normalized();
// disallow zero length (should be rare)
if (r.d.length_squared() < 0.00001f)
continue;
// don't allow from opposite direction
if (r.d.dot(light.dir) > 0.0f)
r.d = -r.d;
} break;
case LLight::LT_SPOT: {
// source
float dot;
while (true) {
Vector3 offset;
RandomUnitDir(offset);
offset *= light.scale;
r.o = light.pos;
r.o += offset;
// offset from origin to destination texel
r.d = ptSource - r.o;
// normalize and find length
ray_length = NormalizeAndFindLength(r.d);
dot = r.d.dot(light.dir);
//float angle = safe_acosf(dot);
//if (angle >= light.spot_angle_radians)
dot -= light.spot_dot_max;
// if within cone, it is ok
if (dot > 0.0f)
break;
}
// reverse ray for precision reasons
r.d = -r.d;
r.o = ptSource;
dot *= 1.0f / (1.0f - light.spot_dot_max);
multiplier = dot * dot;
multiplier *= multiplier;
} break;
default: {
Vector3 offset;
RandomUnitDir(offset);
offset *= light.scale;
ptDest += offset;
// offset from origin to destination texel
r.o = ptSource;
r.d = ptDest - r.o;
// normalize and find length
ray_length = NormalizeAndFindLength(r.d);
// safety
//assert (r.d.length() > 0.0f);
} break;
}
// only bother tracing if the light is in front of the surface normal
float dot_light_surf = orig_vertex_normal.dot(r.d);
if (dot_light_surf <= 0.0f)
continue;
//Vector3 ray_origin = r.o;
FColor sample_color = light.color;
int panic_count = 32;
// for bounces
Vector3 hit_face_normal = orig_face_normal;
bool keep_tracing = true;
// quick reject triangle
if (quick_reject_tri_id != -1) {
if (m_Scene.TestIntersect_Ray_Triangle(r, ray_length, quick_reject_tri_id)) {
keep_tracing = false;
}
}
while (keep_tracing) {
keep_tracing = false;
// collision detect
float u, v, w, t;
m_Scene.m_Tracer.m_bUseSDF = true;
int tri = m_Scene.FindIntersect_Ray(r, u, v, w, t);
// m_Scene.m_Tracer.m_bUseSDF = false;
// int tri2 = m_Scene.IntersectRay(r, u, v, w, t, m_iNumTests);
// if (tri != tri2)
// {
// // repeat SDF version
// m_Scene.m_Tracer.m_bUseSDF = true;
// int tri = m_Scene.IntersectRay(r, u, v, w, t, m_iNumTests);
// }
// further away than the destination?
if (tri != -1) {
if (t > ray_length)
tri = -1;
// else