-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlighter.cpp
1359 lines (1184 loc) · 37.5 KB
/
lighter.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 "lighter_int.hpp"
LTRBOOL ltr_DefaultSizeFunc
(
ltr_Config* config,
const char* mesh_ident,
size_t mesh_ident_size,
const char* inst_ident,
size_t inst_ident_size,
float computed_surface_area,
float inst_importance,
u32 out_size[2]
)
{
float size = config->global_size_factor * sqrtf( computed_surface_area ) * inst_importance;
if( size < 1 )
size = 1;
u32 ui_size = ltr_NextPowerOfTwo( (u32) size );
if( ui_size > config->max_lightmap_size )
return 0;
out_size[0] = ui_size;
out_size[1] = ui_size;
return 1;
}
void RasterizeInstance( ltr_MeshInstance* mi, float margin, Vec3* R1, Vec3* R2, Vec4* R3 )
{
ltr_Mesh* mesh = mi->mesh;
for( u32 part = 0; part < mesh->m_parts.size(); ++part )
{
const ltr_MeshPart& mp = mesh->m_parts[ part ];
u32 O = mp.m_vertexOffset;
const u32* indexBase = &mesh->m_indices[ mp.m_indexOffset ];
for( u32 tri = 0; tri < mp.m_indexCount; tri += 3 )
{
u32 tridx1 = tri, tridx2 = tri + 1, tridx3 = tri + 2;
tridx1 = O + indexBase[ tridx1 ];
tridx2 = O + indexBase[ tridx2 ];
tridx3 = O + indexBase[ tridx3 ];
float samplearea = CalculateSampleArea(
mi->m_ltex[ tridx1 ], mi->m_ltex[ tridx2 ], mi->m_ltex[ tridx3 ],
mi->m_vpos[ tridx1 ], mi->m_vpos[ tridx2 ], mi->m_vpos[ tridx3 ]
);
RasterizeTriangle2D_x2_ex
(
R1, R2, R3, mi->lm_width, mi->lm_height, margin,
mi->m_ltex[ tridx1 ], mi->m_ltex[ tridx2 ], mi->m_ltex[ tridx3 ],
mi->m_vpos[ tridx1 ], mi->m_vpos[ tridx2 ], mi->m_vpos[ tridx3 ],
mi->m_vnrm[ tridx1 ], mi->m_vnrm[ tridx2 ], mi->m_vnrm[ tridx3 ],
V4( mi->m_vtex[ tridx1 ].x, mi->m_vtex[ tridx1 ].y, (float) part, samplearea ),
V4( mi->m_vtex[ tridx2 ].x, mi->m_vtex[ tridx2 ].y, (float) part, samplearea ),
V4( mi->m_vtex[ tridx3 ].x, mi->m_vtex[ tridx3 ].y, (float) part, samplearea )
);
}
}
}
struct QueryIDAdder
{
std::vector< int32_t >* dest;
void operator () ( int32_t* ids, int32_t count )
{
dest->reserve( dest->size() + count );
for( int32_t i = 0; i < count; ++i )
dest->push_back( ids[ i ] );
}
};
void ltr_Light::QueryMeshInsts( AABBTree& tree, std::vector< int32_t >& out )
{
QueryIDAdder query = { &out };
if( type == LTR_LT_POINT )
{
Vec3 range3 = V3( range );
tree.Query( position - range3, position + range3, query );
}
else if( type == LTR_LT_SPOT )
{
// optimize?
Vec3 range3 = V3( range );
tree.Query( position - range3, position + range3, query );
}
else if( type == LTR_LT_DIRECT )
{
tree.GetAll( query );
}
}
ltr_Scene* ltr_CreateScene()
{
return new ltr_Scene;
}
void ltr_DestroyScene( ltr_Scene* scene )
{
delete scene;
}
struct SceneAnyHitRayQuery : BaseRayQuery
{
SceneAnyHitRayQuery( ltr_Scene* s, const Vec3& r0, const Vec3& r1 ) : hit(false), S(s), ray_end(r1)
{
SetRay( r0, r1 );
}
bool operator () ( int32_t* ids, int32_t count )
{
for( int32_t i = 0; i < count; ++i )
{
ltr_MeshInstance* mi = S->m_meshInstances[ ids[ i ] ];
if( mi->m_shadow )
{
hit = mi->m_triTree.IntersectRay( ray_origin, ray_end );
if( hit )
return false;
}
}
return true;
}
bool hit;
ltr_Scene* S;
Vec3 ray_end;
};
bool ltr_Scene::VisibilityTest( const Vec3& A, const Vec3& B )
{
Vec3 diffnorm = ( B - A ).Normalized();
Vec3 mA = A + diffnorm * SMALL_FLOAT;
Vec3 mB = B - diffnorm * SMALL_FLOAT;
SceneAnyHitRayQuery query( this, mA, mB );
m_instTree.RayQuery( query );
return query.hit;
}
struct SceneDistanceQuery
{
SceneDistanceQuery( ltr_Scene* s, const Vec3& p ) : pos( p ), dist( MAX_PENUMBRA_SIZE ), S( s ){ RecalcBB(); }
void operator () ( int32_t* ids, int32_t count )
{
for( int32_t i = 0; i < count; ++i )
{
ltr_MeshInstance* mi = S->m_meshInstances[ ids[ i ] ];
if( mi->m_shadow )
{
float ndst = mi->m_triTree.GetDistance( pos, dist );
if( ndst < dist )
{
dist = ndst;
RecalcBB();
}
}
}
}
FORCEINLINE void RecalcBB()
{
bbmin = pos - V3(dist);
bbmax = pos + V3(dist);
}
Vec3 bbmin, bbmax;
Vec3 pos;
float dist;
ltr_Scene* S;
};
float ltr_Scene::Distance( const Vec3& p )
{
SceneDistanceQuery query( this, p );
m_instTree.DynBBQuery( query );
return query.dist;
}
float ltr_Scene::CalcInvShadowFactor( const Vec3& from, const Vec3& to, float k )
{
Vec3 rd = ( to - from ).Normalized();
float mint = 0.001f;
float maxt = ( to - from ).Length();
float res = 1.0f;
for( float t = mint; t < maxt; )
{
float h = Distance( from + rd * t );
if( h < 0.001f )
return 0.0f;
res = TMIN( res, h / TMIN( t * k, MAX_PENUMBRA_SIZE ) );
h = TMIN( h, MAX_PENUMBRA_STEP );
t += h;
}
return res;
}
struct SceneClosestHitRayQueryBSP : BaseRayQuery
{
SceneClosestHitRayQueryBSP( ltr_Scene* s, const Vec3& r0, const Vec3& r1, Vec3* on ) : closest(2), outnormal(on), S(s), ray_end(r1)
{
SetRay( r0, r1 );
}
bool operator () ( int32_t* ids, int32_t count )
{
for( int32_t i = 0; i < count; ++i )
{
ltr_MeshInstance* mi = S->m_meshInstances[ ids[ i ] ];
if( mi->m_shadow )
{
Vec3 nrm;
float dist = mi->m_bspTree.IntersectRay( ray_origin, ray_end, &nrm );
if( dist < closest )
{
closest = dist;
if( outnormal )
*outnormal = nrm;
}
}
}
return true;
}
float closest;
Vec3* outnormal;
ltr_Scene* S;
Vec3 ray_end;
};
float ltr_Scene::DistanceTest( const Vec3& A, const Vec3& B, Vec3* outnormal )
{
Vec3 diffnorm = ( B - A ).Normalized();
Vec3 mA = A + diffnorm * SMALL_FLOAT;
Vec3 mB = B - diffnorm * SMALL_FLOAT;
SceneClosestHitRayQueryBSP query( this, mA, mB, outnormal );
m_instTree.RayQuery( query );
return query.closest;
}
struct SceneClosestHitRayQueryBBT : BaseRayQuery
{
SceneClosestHitRayQueryBBT( ltr_Scene* s, const Vec3& r0, const Vec3& r1 ) : closest(2), S(s), ray_end(r1)
{
SetRay( r0, r1 );
}
bool operator () ( int32_t* ids, int32_t count )
{
for( int32_t i = 0; i < count; ++i )
{
ltr_MeshInstance* mi = S->m_meshInstances[ ids[ i ] ];
if( mi->m_shadow )
{
float dist = mi->m_triTree.IntersectRayDist( ray_origin, ray_end, NULL );
if( dist < closest )
closest = dist;
}
}
return true;
}
float closest;
ltr_Scene* S;
Vec3 ray_end;
};
float ltr_Scene::DistanceTestBBT( const Vec3& A, const Vec3& B )
{
Vec3 diffnorm = ( B - A ).Normalized();
Vec3 mA = A + diffnorm * SMALL_FLOAT;
Vec3 mB = B - diffnorm * SMALL_FLOAT;
SceneClosestHitRayQueryBBT query( this, mA, mB );
m_instTree.RayQuery( query );
return query.closest;
}
void ltr_Scene::Job_PreXForm_Inner( ltr_MeshInstance* mi )
{
if( mi->m_samplecont )
return;
ltr_Mesh* mesh = mi->mesh;
mi->m_vpos.resize( mesh->m_vpos.size() );
mi->m_vnrm.resize( mesh->m_vnrm.size() );
mi->m_vtex.resize( mesh->m_vtex1.size() );
mi->m_ltex.resize( mesh->m_vtex2.size() );
TransformPositions( VDATA( mi->m_vpos ), VDATA( mesh->m_vpos ), mesh->m_vpos.size(), mi->matrix );
TransformNormals( VDATA( mi->m_vnrm ), VDATA( mesh->m_vnrm ), mesh->m_vnrm.size(), mi->matrix );
// compute total area
float total_area = 0.0f;
for( u32 part = 0; part < mesh->m_parts.size(); ++part )
{
const ltr_MeshPart& mp = mesh->m_parts[ part ];
const Vec3* vertexBase = &mi->m_vpos[ mp.m_vertexOffset ];
const u32* indexBase = &mesh->m_indices[ mp.m_indexOffset ];
for( u32 tri = 0; tri < mp.m_indexCount; tri += 3 )
{
u32 tridx1 = tri, tridx2 = tri + 1, tridx3 = tri + 2;
tridx1 = indexBase[ tridx1 ];
tridx2 = indexBase[ tridx2 ];
tridx3 = indexBase[ tridx3 ];
total_area += TriangleArea( vertexBase[ tridx1 ], vertexBase[ tridx2 ], vertexBase[ tridx3 ] );
}
}
// call lightmap resizer
u32 out_size[2] = { config.default_width, config.default_height };
if( !config.size_fn( &config, mesh->m_ident.c_str(), mesh->m_ident.size(), mi->m_ident.c_str(), mi->m_ident.size(), total_area, mi->m_importance, out_size ) )
{
out_size[0] = config.default_width;
out_size[1] = config.default_height;
}
mi->lm_width = out_size[0];
mi->lm_height = out_size[1];
// transform texcoords
Vec2 lsize = Vec2::Create( (float) mi->lm_width, (float) mi->lm_height );
for( size_t i = 0; i < mi->m_ltex.size(); ++i )
{
mi->m_vtex[ i ] = mesh->m_vtex1[ i ];
mi->m_ltex[ i ] = mesh->m_vtex2[ i ] * lsize - Vec2::Create(0.5f);
}
}
void ltr_Scene::Job_PreXForm( LTRWorker::IO* io )
{
ltr_Scene* S = (ltr_Scene*) io->shared;
S->Job_PreXForm_Inner( S->m_meshInstances[ io->i ] );
}
void ltr_Scene::Job_ColInfo_Inner( ltr_MeshInstance* mi )
{
if( mi->m_samplecont )
{
mi->m_triTree.SetTris( NULL, 0 );
return;
}
std::vector< Triangle > tris;
ltr_Mesh* mesh = mi->mesh;
for( u32 part = 0; part < mesh->m_parts.size(); ++part )
{
const ltr_MeshPart& mp = mesh->m_parts[ part ];
if( !mp.m_shadow )
continue;
const Vec3* vertexBase = &mi->m_vpos[ mp.m_vertexOffset ];
const u32* indexBase = &mesh->m_indices[ mp.m_indexOffset ];
for( u32 tri = 0; tri < mp.m_indexCount; tri += 3 )
{
u32 tridx1 = tri, tridx2 = tri + 1, tridx3 = tri + 2;
tridx1 = indexBase[ tridx1 ];
tridx2 = indexBase[ tridx2 ];
tridx3 = indexBase[ tridx3 ];
Triangle T = { vertexBase[ tridx1 ], vertexBase[ tridx2 ], vertexBase[ tridx3 ] };
if( T.CheckIsUseful() )
tris.push_back( T );
}
}
if( tris.size() )
mi->m_bspTree.SetTriangles( VDATA( tris ), tris.size() );
mi->m_triTree.SetTris( VDATA( tris ), tris.size() );
}
void ltr_Scene::Job_ColInfo( LTRWorker::IO* io )
{
ltr_Scene* S = (ltr_Scene*) io->shared;
S->Job_ColInfo_Inner( S->m_meshInstances[ io->i ] );
}
void ltr_Scene::Job_Samples_Inner( ltr_Scene* S, ltr_MeshInstance* mi )
{
float corr_min_dot = cosf( config.max_correct_angle / 180.0f * (float) M_PI );
if( mi->m_samplecont )
{
for( size_t i = 0; i < mi->m_lightmap.size(); ++i )
mi->m_lightmap[ i ] = Vec3::CreateFromPtr( config.ambient_color );
return;
}
Vec3Vector R1;
Vec3Vector R2;
Vec4Vector R3;
R1.resize( mi->lm_width * mi->lm_height );
R2.resize( mi->lm_width * mi->lm_height );
R3.resize( mi->lm_width * mi->lm_height );
TMEMSET( VDATA( R1 ), R1.size(), V3(0) );
TMEMSET( VDATA( R2 ), R2.size(), V3(0) );
TMEMSET( VDATA( R3 ), R3.size(), V4(0) );
// first do excessive rasterization
// RasterizeInstance( mi, 2.0f + SMALL_FLOAT, VDATA( R1 ), VDATA( R2 ), VDATA( R3 ) );
// RasterizeInstance( mi, 1.5f + SMALL_FLOAT, VDATA( R1 ), VDATA( R2 ), VDATA( R3 ) );
// RasterizeInstance( mi, 1.0f + SMALL_FLOAT, VDATA( R1 ), VDATA( R2 ), VDATA( R3 ) );
RasterizeInstance( mi, 0.5f + SMALL_FLOAT, VDATA( R1 ), VDATA( R2 ), VDATA( R3 ) );
// then do proper rasterization
RasterizeInstance( mi, 0.0f, VDATA( R1 ), VDATA( R2 ), VDATA( R3 ) );
// compress samples to packed array
u32 sample_count = 0;
for( size_t i = 0; i < R2.size(); ++i )
{
Vec3& N = R2[ i ];
if( !N.IsZero() )
sample_count++;
}
mi->m_samples_pos.reserve( sample_count );
mi->m_samples_nrm.reserve( sample_count );
mi->m_samples_loc.reserve( sample_count );
mi->m_samples_radinfo.reserve( sample_count );
for( size_t i = 0; i < R2.size(); ++i )
{
Vec3 N = R2[ i ];
if( !N.IsZero() )
{
N = N.Normalized();
Vec3 P = R1[ i ];
Vec4 XD = R3[ i ];
// move sample out of concave edges
for( size_t mid = 0; mid < S->m_meshInstances.size(); ++mid )
S->m_meshInstances[ mid ]->m_triTree.OffsetSample( P, N, sqrtf( XD.w ) );
// move sample in front of overlapping faces
if( config.max_correct_dist )
{
int itsleft = 100;
float md = config.max_correct_dist;
Vec3 PEnd = P + N * md;
while( md > SMALL_FLOAT && itsleft --> 0 )
{
Vec3 hitnrm = {0,0,0};
float q = DistanceTest( P, PEnd, &hitnrm );
if( -Vec3Dot( hitnrm, N ) < corr_min_dot )
break;
if( q < SMALL_FLOAT )
q = SMALL_FLOAT;
P = P * ( 1.0f - q ) + PEnd * q;
md *= ( 1.0f - q );
}
}
mi->m_samples_pos.push_back( P );
mi->m_samples_nrm.push_back( N );
mi->m_samples_loc.push_back( i );
mi->m_samples_radinfo.push_back( XD );
}
}
mi->m_lightmap.resize( sample_count );
for( size_t i = 0; i < mi->m_lightmap.size(); ++i )
mi->m_lightmap[ i ] = Vec3::CreateFromPtr( config.ambient_color );
}
void ltr_Scene::Job_Samples( LTRWorker::IO* io )
{
ltr_Scene* S = (ltr_Scene*) io->shared;
S->Job_Samples_Inner( S, S->m_meshInstances[ io->i ] );
}
void ltr_Scene::Job_LMRender_Point_Inner( size_t i, dw_lmrender_data* data )
{
ltr_MeshInstance* mi = data->mi;
ltr_Light& light = *data->light;
// MAY BE THREADED
// for( size_t i = 0; i < mi->m_lightmap.size(); ++i )
{
Vec3& SP = mi->m_samples_pos[ i ];
Vec3& SN = mi->m_samples_nrm[ i ];
Vec3 sample2light = light.position - SP;
float dist = sample2light.Length();
if( dist )
sample2light /= dist;
float f_dist = pow( 1 - TMIN( 1.0f, dist / light.range ), light.power );
float f_ndotl = TMAX( 0.0f, Vec3Dot( sample2light, SN ) );
if( f_dist * f_ndotl <= 0 )
return; // continue;
float f_vistest = CalcInvShadowFactor( SP + SN * SAMPLE_SHADOW_OFFSET, light.position, light.light_radius );
mi->m_lightmap[ i ] += light.color_rgb * ( f_dist * f_ndotl * f_vistest );
if( config.generate_normalmap_data && !mi->m_samplecont )
{
float factor = f_dist * f_vistest * f_ndotl * CalcBrightness( light.color_rgb );
if( factor > 0 )
{
ltr_LightContribSample contrib = { sample2light * factor, (int32_t) i };
(*data->contribs)[ i ] = contrib;
}
}
}
}
void ltr_Scene::Job_LMRender_Spot_Inner( size_t i, dw_lmrender_data* data )
{
ltr_MeshInstance* mi = data->mi;
ltr_Light& light = *data->light;
float angle_out_rad = data->angle_out_rad;
// float angle_in_rad = data->angle_in_rad;
float angle_diff = data->angle_diff;
// MAY BE THREADED
// for( size_t i = 0; i < mi->m_lightmap.size(); ++i )
{
Vec3& SP = mi->m_samples_pos[ i ];
Vec3& SN = mi->m_samples_nrm[ i ];
Vec3 sample2light = light.position - SP;
float dist = sample2light.Length();
if( dist )
sample2light /= dist;
float f_dist = pow( 1 - TMIN( 1.0f, dist / light.range ), light.power );
float f_ndotl = TMAX( 0.0f, Vec3Dot( sample2light, SN ) );
float angle = acosf( TMIN( 1.0f, Vec3Dot( sample2light, -light.direction ) ) );
float f_dir = TMAX( 0.0f, TMIN( 1.0f, ( angle - angle_out_rad ) / angle_diff ) );
f_dir = pow( f_dir, light.spot_curve );
if( f_dist * f_ndotl * f_dir <= 0 )
return; // continue;
float f_vistest = CalcInvShadowFactor( SP + SN * SAMPLE_SHADOW_OFFSET, light.position, light.light_radius );
mi->m_lightmap[ i ] += light.color_rgb * ( f_dist * f_ndotl * f_dir * f_vistest );
if( config.generate_normalmap_data && !mi->m_samplecont )
{
float factor = f_dist * f_dir * f_vistest * f_ndotl * CalcBrightness( light.color_rgb );
if( factor > 0 )
{
ltr_LightContribSample contrib = { sample2light * factor, (int32_t) i };
(*data->contribs)[ i ] = contrib;
}
}
}
}
void ltr_Scene::Job_LMRender_Direct_Inner( size_t i, dw_lmrender_data* data )
{
ltr_MeshInstance* mi = data->mi;
ltr_Light& light = *data->light;
// MAY BE THREADED
// for( size_t i = 0; i < mi->m_lightmap.size(); ++i )
{
Vec3& SP = mi->m_samples_pos[ i ];
Vec3& SN = mi->m_samples_nrm[ i ];
#if 0
float f_ndotl = 0.0f;
float f_vistest = 0.0f;
Vec3 ray_origin = SP;
float randoff = randf();//( sin( SP.x ) + sin( SP.y ) + sin( SP.z ) ) / 6 + 0.5f;
for( int s = 0; s < light.shadow_sample_count; ++s )
{
Vec3 adjdir = Vec3::CreateSpiralDirVector( -light.direction, randoff, s, light.shadow_sample_count );
adjdir = ( adjdir + (-light.direction) * tan( ( light.light_radius - 0.5f ) * float(M_PI) * 0.999f ) ).Normalized();
f_ndotl += TMAX( 0.0f, Vec3Dot( adjdir, SN ) );
if( VisibilityTest( ray_origin, ray_origin + adjdir * light.range ) )
f_vistest += 1.0f;
}
f_ndotl /= light.shadow_sample_count;
f_vistest /= light.shadow_sample_count;
f_vistest = 1.0f - f_vistest;
#else
float f_ndotl = TMAX( 0.0f, Vec3Dot( light.direction, SN ) );
float f_vistest = CalcInvShadowFactor( SP + SN * SAMPLE_SHADOW_OFFSET, SP + light.direction * light.range, light.light_radius );
#endif
mi->m_lightmap[ i ] += light.color_rgb * ( f_ndotl * f_vistest );
if( config.generate_normalmap_data && !mi->m_samplecont )
{
float factor = f_vistest * f_ndotl * CalcBrightness( light.color_rgb );
if( factor > 0 )
{
ltr_LightContribSample contrib = { light.direction * factor, (int32_t) i };
(*data->contribs)[ i ] = contrib;
}
}
}
}
void ltr_Scene::Job_LMRender_Point( LTRWorker::IO* io )
{
ltr_Scene* S = (ltr_Scene*) io->shared;
dw_lmrender_data* data = (dw_lmrender_data*) io->item;
S->Job_LMRender_Point_Inner( io->i, data );
}
void ltr_Scene::Job_LMRender_Spot( LTRWorker::IO* io )
{
ltr_Scene* S = (ltr_Scene*) io->shared;
dw_lmrender_data* data = (dw_lmrender_data*) io->item;
S->Job_LMRender_Spot_Inner( io->i, data );
}
void ltr_Scene::Job_LMRender_Direct( LTRWorker::IO* io )
{
ltr_Scene* S = (ltr_Scene*) io->shared;
dw_lmrender_data* data = (dw_lmrender_data*) io->item;
S->Job_LMRender_Direct_Inner( io->i, data );
}
void ltr_Scene::Int_LMRender( ltr_Light& light, ltr_MeshInstance* mi )
{
std::vector<ltr_LightContribSample> contribs;
if( config.generate_normalmap_data )
{
contribs.resize( mi->m_lightmap.size() );
ltr_LightContribSample nullsample = { V3(0), -1 };
TMEMSET( VDATA( contribs ), contribs.size(), nullsample );
}
if( light.type == LTR_LT_POINT )
{
dw_lmrender_data data = { &contribs, mi, &light };
m_worker.DoWork( this, &data, 0, mi->m_lightmap.size(), ltr_Scene::Job_LMRender_Point );
}
if( light.type == LTR_LT_SPOT )
{
float angle_out_rad = light.spot_angle_out / 180.0f * (float) M_PI, angle_in_rad = light.spot_angle_in / 180.0f * (float) M_PI;
if( angle_in_rad == angle_out_rad )
angle_in_rad -= SMALL_FLOAT;
float angle_diff = angle_in_rad - angle_out_rad;
dw_lmrender_data data = { &contribs, mi, &light, angle_out_rad, angle_in_rad, angle_diff };
m_worker.DoWork( this, &data, 0, mi->m_lightmap.size(), ltr_Scene::Job_LMRender_Spot );
}
else if( light.type == LTR_LT_DIRECT )
{
dw_lmrender_data data = { &contribs, mi, &light };
m_worker.DoWork( this, &data, 0, mi->m_lightmap.size(), ltr_Scene::Job_LMRender_Direct );
}
// commit contributions
if( config.generate_normalmap_data )
{
for( size_t i = 0; i < contribs.size(); ++i )
{
if( contribs[ i ].sid >= 0 )
mi->m_contrib.push_back( contribs[ i ] );
}
}
}
void ltr_Scene::Int_RDGenLinks()
{
#ifdef LTRDEBUG
double t0 = ltr_gettime();
#endif
for( size_t mi_id = 0; mi_id < m_meshInstances.size(); ++mi_id )
{
ltr_MeshInstance* mi = m_meshInstances[ mi_id ];
for( size_t i = 0; i < mi->m_lightmap.size(); ++i )
{
ltr_Mesh* mesh = mi->mesh;
const Vec3& P = mi->m_samples_pos[ i ];
const Vec3& N = mi->m_samples_nrm[ i ].Normalized();
ltr_RadSampleGeom RSG = { P, N };
m_radSampleGeoms.push_back( RSG );
Vec3 s_diff = {1,1,1};
Vec3 s_emit = mi->m_lightmap[ i ];
float s_area = mi->m_samplecont ? 0 : mi->m_samples_radinfo[ i ].w;
if( mi->m_samplecont )
{
s_diff = Vec3::Create(0);
}
else if( config.sample_fn )
{
const size_t L = mi->m_samples_loc[ i ];
int LMX = L % mi->lm_width;
int LMY = L / mi->lm_width;
ltr_SampleRequest REQ =
{
{ P.x, P.y, P.z },
{ N.x, N.y, N.z },
mi->m_samples_radinfo[ i ].x, mi->m_samples_radinfo[ i ].y,
( LMX + 0.5f ) / mi->lm_width, ( LMY + 0.5f ) / mi->lm_height,
(uint32_t) mi->m_samples_radinfo[ i ].z, // should not be interpolated between triangles
mesh->m_ident.c_str(), mesh->m_ident.size(),
mi->m_ident.c_str(), mi->m_ident.size(),
{ 1, 1, 1 },
{ 0, 0, 0 },
};
if( config.sample_fn( &config, &REQ ) )
{
s_diff = Vec3::CreateFromPtr( REQ.out_diffuse_color );
s_emit += Vec3::CreateFromPtr( REQ.out_emissive_color );
}
}
ltr_RadSampleColors RSC = { s_diff, s_emit, s_emit, Vec3::Create(0), s_area };
m_radSampleColors.push_back( RSC );
}
}
#ifdef LTRDEBUG
double t1 = ltr_gettime();
printf( "RAD sample concat: %g seconds\n", t1 - t0 );
double t2 = ltr_gettime();
#endif
for( size_t i = 0; i < m_radSampleGeoms.size(); ++i )
{
m_radLinkMap.push_back( m_radLinks.size() ); // offset
m_radLinkMap.push_back( 0 ); // count
const Vec3& A_SP = m_radSampleGeoms[ i ].pos;
const Vec3& A_SN = m_radSampleGeoms[ i ].normal;
for( size_t j = i + 1; j < m_radSampleGeoms.size(); ++j )
{
const Vec3& B_SP = m_radSampleGeoms[ j ].pos;
const Vec3& B_SN = m_radSampleGeoms[ j ].normal;
Vec3 posdiff = B_SP - A_SP;
float dotA = Vec3Dot( A_SN, posdiff );
float dotB = Vec3Dot( B_SN, -posdiff );
if( dotA <= SMALL_FLOAT || dotB <= SMALL_FLOAT )
continue;
float lensq = posdiff.LengthSq();
float factor = dotA * dotB / ( lensq * lensq * (float) M_PI );
if( factor < SMALL_FLOAT )
continue;
if( VisibilityTest( A_SP, B_SP ) == false )
continue;
// add sample
ltr_RadLink RL = { (uint32_t) j, factor };
m_radLinks.push_back( RL );
m_radLinkMap.back()++;
}
}
#ifdef LTRDEBUG
double t3 = ltr_gettime();
printf( "RAD sample processing: %g seconds\n", t3 - t2 );
#endif
}
void ltr_Scene::Int_RDBounce()
{
for( size_t i = 0; i < m_radLinkMap.size() / 2; ++i )
{
size_t sidbegin = m_radLinkMap[ i*2+0 ];
size_t sidend = sidbegin + m_radLinkMap[ i*2+1 ];
for( size_t sid = sidbegin; sid < sidend; ++sid )
{
size_t j = m_radLinks[ sid ].other;
float f = m_radLinks[ sid ].factor;
ltr_RadSampleColors& A_RSC = m_radSampleColors[ i ];
ltr_RadSampleColors& B_RSC = m_radSampleColors[ j ];
Vec3 A_out = ( A_RSC.outputEnergy * A_RSC.diffuseColor ) * A_RSC.area * f;
Vec3 B_out = ( B_RSC.outputEnergy * B_RSC.diffuseColor ) * B_RSC.area * f;
A_RSC.totalLight += B_out;
B_RSC.totalLight += A_out;
A_RSC.inputEnergy += B_out;
B_RSC.inputEnergy += A_out;
}
}
for( size_t i = 0; i < m_radSampleColors.size(); ++i )
{
ltr_RadSampleColors& RSC = m_radSampleColors[ i ];
RSC.outputEnergy = RSC.inputEnergy;
RSC.inputEnergy = Vec3::Create(0);
}
}
void ltr_Scene::Job_AORender_Inner( ltr_MeshInstance* mi, size_t i )
{
// float ao_divergence = config.ao_divergence * 0.5f + 0.5f;
float ao_distance = config.ao_distance,
ao_falloff = config.ao_falloff,
ao_multiplier = config.ao_multiplier,
ao_effect = config.ao_effect;
int num_samples = config.ao_num_samples;
Vec3 ao_color = Vec3::CreateFromPtr( config.ao_color_rgb );
// MAY BE THREADED
// for( size_t i = 0; i < mi->m_lightmap.size(); ++i )
{
Vec3& SP = mi->m_samples_pos[ i ];
Vec3& SN = mi->m_samples_nrm[ i ];
Vec3& OutColor = mi->m_lightmap[ i ];
Vec3 ray_origin = SP + SN * ( SMALL_FLOAT * 2 );
float ao_factor = 0;
float randoff = randf();
for( int s = 0; s < num_samples; ++s )
{
Vec3 ray_dir = Vec3::CreateSpiralDirVector( SN, randoff, s, num_samples ) * ao_distance;
float hit = DistanceTestBBT( ray_origin, ray_origin + ray_dir );
if( hit < 1.0f )
ao_factor += 1.0f - hit;
}
ao_factor /= num_samples;
ao_factor = TMIN( ao_factor * ao_multiplier, 1.0f );
if( ao_falloff )
ao_factor = pow( ao_factor, ao_falloff );
if( ao_effect >= 0 )
{
OutColor = OutColor * ( 1 - ao_factor * ( 1 - ao_effect ) ) + ao_color * ao_factor;
}
else
{
OutColor = TLERP( OutColor, TLERP( ao_color, ao_color * OutColor, -ao_effect ), ao_factor );
}
}
}
void ltr_Scene::Job_AORender( LTRWorker::IO* io )
{
ltr_Scene* S = (ltr_Scene*) io->shared;
S->Job_AORender_Inner( (ltr_MeshInstance*) io->item, io->i );
}
void ltr_Scene::Int_Finalize()
{
for( size_t mid = 0; mid < m_meshInstances.size(); ++mid )
{
ltr_MeshInstance* mi = m_meshInstances[ mid ];
if( mi->m_samplecont )
{
for( size_t i = 0; i < mi->m_lightmap.size(); ++i )
{
m_samples[ i ].out_color[0] = mi->m_lightmap[ i ].x;
m_samples[ i ].out_color[1] = mi->m_lightmap[ i ].y;
m_samples[ i ].out_color[2] = mi->m_lightmap[ i ].z;
}
continue;
}
ltr_Mesh* mesh = mi->mesh;
float* image_rgb = new float[ mi->lm_width * mi->lm_height * 3 ];
char* image_set = new char[ mi->lm_width * mi->lm_height * 2 ];
TMEMSET( image_rgb, mi->lm_width * mi->lm_height * 3, 0.0f );
TMEMSET( image_set, mi->lm_width * mi->lm_height * 2, (char) 0 );
for( size_t i = 0; i < mi->m_samples_loc.size(); ++i )
{
size_t loc = mi->m_samples_loc[ i ] * 3;
Vec3& LMC = mi->m_lightmap[ i ];
image_rgb[ loc+0 ] = LMC.x;
image_rgb[ loc+1 ] = LMC.y;
image_rgb[ loc+2 ] = LMC.z;
image_set[ mi->m_samples_loc[ i ] ] = 1;
}
// extrapolate for interpolation
u32 w = mi->lm_width, h = mi->lm_height;
#define PX_ISSET( x, y ) ( (x) < w && (y) < h && image_set[ (x) + (y) * w ] )
#define PX_GETCOL( x, y ) Vec3::Create(image_rgb[((x)+(y)*w)*3+0],image_rgb[((x)+(y)*w)*3+1],image_rgb[((x)+(y)*w)*3+2])
for( int its = 1; its <= 3; ++its )
{
memcpy( image_set + w*h, image_set, w*h );
for( u32 y = 0; y < h; ++y )
{
for( u32 x = 0; x < w; ++x )
{
if( image_set[ x + y * w ] )
continue;
Vec3 col = {0,0,0};
int count = 0;
// H
if( PX_ISSET( x-1, y ) )
{
if( PX_ISSET( x-2, y ) )
col += TLERP( PX_GETCOL( x-2, y ), PX_GETCOL( x-1, y ), 2.0f );
else
col += PX_GETCOL( x-1, y );
count++;
}
if( PX_ISSET( x+1, y ) )
{
if( PX_ISSET( x+2, y ) )
col += TLERP( PX_GETCOL( x+2, y ), PX_GETCOL( x+1, y ), 2.0f );
else
col += PX_GETCOL( x+1, y );
count++;
}
// V
if( PX_ISSET( x, y-1 ) )
{
if( PX_ISSET( x, y-2 ) )
col += TLERP( PX_GETCOL( x, y-2 ), PX_GETCOL( x, y-1 ), 2.0f );
else
col += PX_GETCOL( x, y-1 );
count++;
}
if( PX_ISSET( x, y+1 ) )
{
if( PX_ISSET( x, y+2 ) )
col += TLERP( PX_GETCOL( x, y+2 ), PX_GETCOL( x, y+1 ), 2.0f );
else
col += PX_GETCOL( x, y+1 );
count++;
}
if( count )
{
col /= (float) count;
u32 off = ( x + y * w ) * 3;
image_rgb[ off+0 ] = TMAX( col.x, 0.0f );
image_rgb[ off+1 ] = TMAX( col.y, 0.0f );
image_rgb[ off+2 ] = TMAX( col.z, 0.0f );
image_set[ x + y * w + w*h ] = 1;
}
}
}
memcpy( image_set, image_set + w*h, w*h );
}
#undef PX_ISSET
#undef PX_GETCOL
if( config.blur_size )
{
int blur_ext = (int) ceil( config.blur_size );
int blurbuf_size = ( TMAX( mi->lm_width, mi->lm_height ) + blur_ext * 2 ) * 3;
int kernel_size = blur_ext * 2 + 1;
float* image_tmp_rgb = new float[ mi->lm_width * mi->lm_height * 3 + blurbuf_size + kernel_size ];
float* blur_tmp_rgb = image_tmp_rgb + mi->lm_width * mi->lm_height * 3;
float* kernel_rgb = blur_tmp_rgb + blurbuf_size;
Generate_Gaussian_Kernel( kernel_rgb, blur_ext, config.blur_size );
Convolve_Transpose( image_rgb, image_tmp_rgb, mi->lm_width, mi->lm_height, blur_ext, kernel_rgb, blur_tmp_rgb );
Convolve_Transpose( image_tmp_rgb, image_rgb, mi->lm_height, mi->lm_width, blur_ext, kernel_rgb, blur_tmp_rgb );
delete [] image_tmp_rgb;
}
if( config.ds2x )
{
int hw = TMAX( mi->lm_width / 2, u32(1) );
int hh = TMAX( mi->lm_height / 2, u32(1) );
float* image_ds2x = new float[ hw * hh * 3 ];
Downsample2X( image_ds2x, hw, hh, image_rgb, mi->lm_width, mi->lm_height );
delete [] image_rgb;
image_rgb = image_ds2x;
mi->lm_width = hw;
mi->lm_height = hh;
}
float* normals_xyzf = NULL;
if( config.generate_normalmap_data )
{
std::vector<ltr_TmpContribSum> contribs;
// - prepare temp. data store
contribs.resize( mi->m_samples_loc.size() );
ltr_TmpContribSum tmpl = { V3(0), 1, 1 };
TMEMSET( VDATA( contribs ), contribs.size(), tmpl );
// - load default contribution
float ambbrightness = CalcBrightness( V3P( config.ambient_color ) );
for( size_t i = 0; i < mi->m_samples_nrm.size(); ++i )
contribs[ i ].normal = mi->m_samples_nrm[ i ] * ambbrightness;
// - gather contributions and average direction
for( size_t i = 0; i < mi->m_contrib.size(); ++i )
{
ltr_TmpContribSum& TCS = contribs[ mi->m_contrib[ i ].sid ];
TCS.normal += mi->m_contrib[ i ].normal;
TCS.count++;
}
for( size_t i = 0; i < contribs.size(); ++i )
{