-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathyocto_pathtrace.cpp
2265 lines (2012 loc) · 75.1 KB
/
yocto_pathtrace.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
//
// Implementation for Yocto/RayTrace.
//
//
// LICENSE:
//
// Copyright (c) 2016 -- 2020 Fabio Pellacini
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#include "yocto_pathtrace.h"
#include <yocto/yocto_shape.h>
#include <atomic>
#include <deque>
#include <future>
#include <memory>
#include <mutex>
using namespace std::string_literals;
#ifdef YOCTO_EMBREE
#include <embree3/rtcore.h>
#include <cstring>
#endif
// -----------------------------------------------------------------------------
// MATH FUNCTIONS
// -----------------------------------------------------------------------------
namespace yocto::pathtrace {
// import math symbols for use
using math::abs;
using math::acos;
using math::atan2;
using math::clamp;
using math::cos;
using math::exp;
using math::flt_max;
using math::fmod;
using math::fresnel_conductor;
using math::fresnel_dielectric;
using math::identity3x3f;
using math::invalidb3f;
using math::log;
using math::make_rng;
using math::max;
using math::min;
using math::pif;
using math::pow;
using math::sample_discrete_cdf;
using math::sample_discrete_cdf_pdf;
using math::sample_uniform;
using math::sample_uniform_pdf;
using math::sin;
using math::sqrt;
using math::zero2f;
using math::zero2i;
using math::zero3f;
using math::zero3i;
using math::zero4f;
using math::zero4i;
using yocto::shape::compute_normals;
using yocto::shape::make_edge_map;
using yocto::shape::quads_to_triangles;
using yocto::shape::split_facevarying;
using yocto::extension::eval_hair_brdf;
using yocto::extension::eval_hair_scattering;
using yocto::extension::hair_brdf;
using yocto::extension::hair_material;
using yocto::extension::sample_hair_scattering;
using yocto::extension::sample_hair_scattering_pdf;
} // namespace yocto::pathtrace
// -----------------------------------------------------------------------------
// IMPLEMENTATION FOR SCENE EVALUATION
// -----------------------------------------------------------------------------
namespace yocto::pathtrace {
#ifdef YOCTO_EMBREE
static RTCDevice embree_device() {
static RTCDevice device = nullptr;
if (!device) {
device = rtcNewDevice("");
rtcSetDeviceErrorFunction(
device,
[](void* ctx, RTCError code, const char* str) {
switch (code) {
case RTC_ERROR_UNKNOWN:
throw std::runtime_error("RTC_ERROR_UNKNOWN: "s + str);
case RTC_ERROR_INVALID_ARGUMENT:
throw std::runtime_error("RTC_ERROR_INVALID_ARGUMENT: "s + str);
case RTC_ERROR_INVALID_OPERATION:
throw std::runtime_error("RTC_ERROR_INVALID_OPERATION: "s + str);
case RTC_ERROR_OUT_OF_MEMORY:
throw std::runtime_error("RTC_ERROR_OUT_OF_MEMORY: "s + str);
case RTC_ERROR_UNSUPPORTED_CPU:
throw std::runtime_error("RTC_ERROR_UNSUPPORTED_CPU: "s + str);
case RTC_ERROR_CANCELLED:
throw std::runtime_error("RTC_ERROR_CANCELLED: "s + str);
default: throw std::runtime_error("invalid error code");
}
},
nullptr);
}
return device;
}
#endif
// Check texture size
static vec2i texture_size(const ptr::texture* texture) {
if (!texture->colorf.empty()) {
return texture->colorf.size();
} else if (!texture->colorb.empty()) {
return texture->colorb.size();
} else if (!texture->scalarf.empty()) {
return texture->scalarf.size();
} else if (!texture->scalarb.empty()) {
return texture->scalarb.size();
} else {
return zero2i;
}
}
// Evaluate a texture
static vec3f lookup_texture(
const ptr::texture* texture, const vec2i& ij, bool ldr_as_linear = false) {
if (!texture->colorf.empty()) {
return texture->colorf[ij];
} else if (!texture->colorb.empty()) {
return ldr_as_linear ? byte_to_float(texture->colorb[ij])
: srgb_to_rgb(byte_to_float(texture->colorb[ij]));
} else if (!texture->scalarf.empty()) {
return vec3f{texture->scalarf[ij]};
} else if (!texture->scalarb.empty()) {
return ldr_as_linear
? byte_to_float(vec3b{texture->scalarb[ij]})
: srgb_to_rgb(byte_to_float(vec3b{texture->scalarb[ij]}));
} else {
return {1, 1, 1};
}
}
// Evaluate a texture
static vec3f eval_texture(const ptr::texture* texture, const vec2f& uv,
bool ldr_as_linear = false, bool no_interpolation = false,
bool clamp_to_edge = false) {
// get texture
if (!texture) return {1, 1, 1};
// get yimg::image width/height
auto size = texture_size(texture);
// get coordinates normalized for tiling
auto s = 0.0f, t = 0.0f;
if (clamp_to_edge) {
s = clamp(uv.x, 0.0f, 1.0f) * size.x;
t = clamp(uv.y, 0.0f, 1.0f) * size.y;
} else {
s = fmod(uv.x, 1.0f) * size.x;
if (s < 0) s += size.x;
t = fmod(uv.y, 1.0f) * size.y;
if (t < 0) t += size.y;
}
// get yimg::image coordinates and residuals
auto i = clamp((int)s, 0, size.x - 1), j = clamp((int)t, 0, size.y - 1);
auto ii = (i + 1) % size.x, jj = (j + 1) % size.y;
auto u = s - i, v = t - j;
if (no_interpolation) return lookup_texture(texture, {i, j}, ldr_as_linear);
// handle interpolation
return lookup_texture(texture, {i, j}, ldr_as_linear) * (1 - u) * (1 - v) +
lookup_texture(texture, {i, jj}, ldr_as_linear) * (1 - u) * v +
lookup_texture(texture, {ii, j}, ldr_as_linear) * u * (1 - v) +
lookup_texture(texture, {ii, jj}, ldr_as_linear) * u * v;
}
static float eval_texturef(const ptr::texture* texture, const vec2f& uv,
bool ldr_as_linear = false, bool no_interpolation = false,
bool clamp_to_edge = false) {
return eval_texture(
texture, uv, ldr_as_linear, no_interpolation, clamp_to_edge)
.x;
}
// Generates a ray from a camera for yimg::image plane coordinate uv and
// the lens coordinates luv.
static ray3f eval_camera(
const ptr::camera* camera, const vec2f& image_uv, const vec2f& lens_uv) {
auto q = vec3f{camera->film.x * (0.5f - image_uv.x),
camera->film.y * (image_uv.y - 0.5f), camera->lens};
auto dc = -normalize(q);
auto e = vec3f{
lens_uv.x * camera->aperture / 2, lens_uv.y * camera->aperture / 2, 0};
auto p = dc * camera->focus / abs(dc.z);
auto d = normalize(p - e);
return ray3f{
transform_point(camera->frame, e), transform_direction(camera->frame, d)};
}
// Samples a camera ray at pixel ij of an image of size size with puv and luv
// as random numbers for pixel and lens respectively
static ray3f sample_camera(const ptr::camera* camera, const vec2i& ij,
const vec2i& size, const vec2f& puv, const vec2f& luv) {
return eval_camera(camera, ((vec2f)ij + puv) / (vec2f)size, sample_disk(luv));
}
// Eval position
static vec3f eval_position(
const ptr::object* object, int element, const vec2f& uv) {
auto shape = object->shape;
if (!shape->triangles.empty()) {
auto t = shape->triangles[element];
return transform_point(
object->frame, interpolate_triangle(shape->positions[t.x],
shape->positions[t.y], shape->positions[t.z], uv));
} else if (!shape->lines.empty()) {
auto l = shape->lines[element];
return transform_point(object->frame,
interpolate_line(shape->positions[l.x], shape->positions[l.y], uv.x));
} else if (!shape->points.empty()) {
return transform_point(
object->frame, shape->positions[shape->points[element]]);
} else {
return zero3f;
}
}
// Shape element normal.
static vec3f eval_element_normal(const ptr::object* object, int element) {
auto shape = object->shape;
if (!shape->triangles.empty()) {
auto t = shape->triangles[element];
return transform_normal(
object->frame, triangle_normal(shape->positions[t.x],
shape->positions[t.y], shape->positions[t.z]));
} else if (!shape->lines.empty()) {
auto l = shape->lines[element];
return transform_normal(object->frame,
line_tangent(shape->positions[l.x], shape->positions[l.y]));
} else if (!shape->points.empty()) {
return {0, 0, 1};
} else {
return {0, 0, 0};
}
}
// Eval normal
static vec3f eval_normal(
const ptr::object* object, int element, const vec2f& uv) {
auto shape = object->shape;
if (shape->normals.empty()) return eval_element_normal(object, element);
if (!shape->triangles.empty()) {
auto t = shape->triangles[element];
return transform_normal(
object->frame, normalize(interpolate_triangle(shape->normals[t.x],
shape->normals[t.y], shape->normals[t.z], uv)));
} else if (!shape->lines.empty()) {
auto l = shape->lines[element];
return transform_normal(object->frame,
normalize(
interpolate_line(shape->normals[l.x], shape->normals[l.y], uv.x)));
} else if (!shape->points.empty()) {
return transform_normal(
object->frame, normalize(shape->normals[shape->points[element]]));
} else {
return zero3f;
}
}
// Eval texcoord
static vec2f eval_texcoord(
const ptr::object* object, int element, const vec2f& uv) {
auto shape = object->shape;
if (shape->texcoords.empty()) return uv;
if (!shape->triangles.empty()) {
auto t = shape->triangles[element];
return interpolate_triangle(shape->texcoords[t.x], shape->texcoords[t.y],
shape->texcoords[t.z], uv);
} else if (!shape->lines.empty()) {
auto l = shape->lines[element];
return interpolate_line(shape->texcoords[l.x], shape->texcoords[l.y], uv.x);
} else if (!shape->points.empty()) {
return shape->texcoords[shape->points[element]];
} else {
return zero2f;
}
}
// Shape element normal.
static std::pair<vec3f, vec3f> eval_element_tangents(
const ptr::object* object, int element) {
auto shape = object->shape;
if (!shape->triangles.empty() && !shape->texcoords.empty()) {
auto t = shape->triangles[element];
auto [tu, tv] = triangle_tangents_fromuv(shape->positions[t.x],
shape->positions[t.y], shape->positions[t.z], shape->texcoords[t.x],
shape->texcoords[t.y], shape->texcoords[t.z]);
return {transform_direction(object->frame, tu),
transform_direction(object->frame, tv)};
} else {
return {};
}
}
static vec3f eval_normalmap(
const ptr::object* object, int element, const vec2f& uv) {
auto shape = object->shape;
auto normal_tex = object->material->normal_tex;
// apply normal mapping
auto normal = eval_normal(object, element, uv);
auto texcoord = eval_texcoord(object, element, uv);
if (normal_tex && !shape->triangles.empty()) {
auto normalmap = -1 + 2 * eval_texture(normal_tex, texcoord, true);
auto [tu, tv] = eval_element_tangents(object, element);
auto frame = frame3f{tu, tv, normal, zero3f};
frame.x = orthonormalize(frame.x, frame.z);
frame.y = normalize(cross(frame.z, frame.x));
auto flip_v = dot(frame.y, tv) < 0;
normalmap.y *= flip_v ? 1 : -1; // flip vertical axis
normal = transform_normal(frame, normalmap);
}
return normal;
}
// Eval shading normal
static vec3f eval_shading_normal(const ptr::object* object, int element,
const vec2f& uv, const vec3f& outgoing) {
auto shape = object->shape;
auto material = object->material;
if (!shape->triangles.empty()) {
auto normal = eval_normal(object, element, uv);
if (material->normal_tex) {
normal = eval_normalmap(object, element, uv);
}
if (!material->thin) return normal;
return dot(normal, outgoing) >= 0 ? normal : -normal;
} else if (!shape->lines.empty()) {
auto normal = eval_normal(object, element, uv);
return orthonormalize(outgoing, normal);
} else if (!shape->points.empty()) {
return -outgoing;
} else {
return zero3f;
}
}
// Brdf
struct brdf {
// brdf lobes
vec3f diffuse = {0, 0, 0};
vec3f specular = {0, 0, 0};
vec3f metal = {0, 0, 0};
vec3f transmission = {0, 0, 0};
vec3f refraction = {0, 0, 0};
float roughness = 0;
float opacity = 1;
float ior = 1;
vec3f meta = {0, 0, 0};
vec3f metak = {0, 0, 0};
// weights
float diffuse_pdf = 0;
float specular_pdf = 0;
float metal_pdf = 0;
float transmission_pdf = 0;
float refraction_pdf = 0;
// hair brdf
bool hair = false;
extension::hair_brdf hair_brdf;
};
// Eval material to obatain emission, brdf and opacity.
static vec3f eval_emission(const ptr::object* object, int element,
const vec2f& uv, const vec3f& normal, const vec3f& outgoing) {
auto material = object->material;
auto texcoord = eval_texcoord(object, element, uv);
return material->emission * eval_texture(material->emission_tex, texcoord);
}
// Eval material to obatain emission, brdf and opacity.
static brdf eval_brdf(const ptr::object* object, int element, const vec2f& uv,
const vec3f& normal, const vec3f& outgoing) {
// material -------
// initialize factors
auto material = object->material;
auto texcoord = eval_texcoord(object, element, uv);
auto base = material->color *
eval_texture(material->color_tex, texcoord, false);
auto specular = material->specular *
eval_texture(material->specular_tex, texcoord, true).x;
auto metallic = material->metallic *
eval_texture(material->metallic_tex, texcoord, true).x;
auto roughness = material->roughness *
eval_texture(material->roughness_tex, texcoord, true).x;
auto ior = material->ior;
auto transmission = material->transmission *
eval_texture(material->emission_tex, texcoord, true).x;
auto opacity = material->opacity *
mean(eval_texture(material->opacity_tex, texcoord, true));
auto thin = material->thin || !material->transmission;
// factors
auto brdf = ptr::brdf{};
auto weight = vec3f{1, 1, 1};
brdf.metal = weight * metallic;
weight *= 1 - metallic;
brdf.refraction = thin ? zero3f : (weight * transmission);
weight *= 1 - (thin ? 0 : transmission);
brdf.specular = weight * specular;
weight *= 1 - specular * fresnel_dielectric(ior, outgoing, normal);
brdf.transmission = thin ? (weight * transmission * base) : zero3f;
weight *= 1 - (thin ? transmission : 0);
brdf.diffuse = weight * base;
brdf.meta = reflectivity_to_eta(base);
brdf.metak = zero3f;
brdf.roughness = roughness * roughness;
brdf.ior = ior;
brdf.opacity = opacity;
// textures
if (brdf.diffuse != zero3f || brdf.roughness) {
brdf.roughness = clamp(brdf.roughness, 0.03f * 0.03f, 1.0f);
}
if (brdf.specular == zero3f && brdf.metal == zero3f &&
brdf.transmission == zero3f && brdf.refraction == zero3f) {
brdf.roughness = 1;
}
if (brdf.opacity > 0.999f) brdf.opacity = 1;
// weights
brdf.diffuse_pdf = max(brdf.diffuse);
brdf.specular_pdf = max(
brdf.specular * fresnel_dielectric(brdf.ior, normal, outgoing));
brdf.metal_pdf = max(
brdf.metal * fresnel_conductor(brdf.meta, brdf.metak, normal, outgoing));
brdf.transmission_pdf = max(brdf.transmission);
brdf.refraction_pdf = max(brdf.refraction);
auto pdf_sum = brdf.diffuse_pdf + brdf.specular_pdf + brdf.metal_pdf +
brdf.transmission_pdf + brdf.refraction_pdf;
if (pdf_sum) {
brdf.diffuse_pdf /= pdf_sum;
brdf.specular_pdf /= pdf_sum;
brdf.metal_pdf /= pdf_sum;
brdf.transmission_pdf /= pdf_sum;
brdf.refraction_pdf /= pdf_sum;
}
// hair brdf
brdf.hair = !object->shape->lines.empty();
if (brdf.hair) {
auto hair_material = extension::hair_material{};
hair_material.sigma_a = material->sigma_a;
hair_material.beta_m = material->beta_m;
hair_material.beta_n = material->beta_n;
hair_material.alpha = material->alpha;
hair_material.eta = material->eta;
hair_material.color = material->color;
hair_material.eumelanin = material->eumelanin;
hair_material.pheomelanin = material->pheomelanin;
auto v = uv.y;
auto tangent = eval_normal(object, element, uv);
brdf.hair_brdf = eval_hair_brdf(hair_material, v, normal, tangent);
}
return brdf;
}
// check if a brdf is a delta
static bool is_delta(const ptr::brdf& brdf) { return !brdf.roughness; }
// vsdf
struct vsdf {
vec3f density = {0, 0, 0};
vec3f scatter = {0, 0, 0};
float anisotropy = 0;
};
// evaluate volume
static vsdf eval_vsdf(const ptr::object* object, int element, const vec2f& uv) {
auto material = object->material;
// initialize factors
auto texcoord = eval_texcoord(object, element, uv);
auto base = material->color *
eval_texture(material->color_tex, texcoord, false);
auto transmission = material->transmission *
eval_texture(material->emission_tex, texcoord, true).x;
auto thin = material->thin || !material->transmission;
auto scattering = material->scattering *
eval_texture(material->scattering_tex, texcoord, false);
auto scanisotropy = material->scanisotropy;
auto trdepth = material->trdepth;
// factors
auto vsdf = ptr::vsdf{};
vsdf.density = (transmission && !thin)
? -log(clamp(base, 0.0001f, 1.0f)) / trdepth
: zero3f;
vsdf.scatter = scattering;
vsdf.anisotropy = scanisotropy;
return vsdf;
}
// check if we have a volume
static bool has_volume(const ptr::object* object) {
return !object->material->thin && object->material->transmission;
}
// Evaluate all environment color.
static vec3f eval_environment(const ptr::scene* scene, const ray3f& ray) {
auto emission = zero3f;
for (auto environment : scene->environments) {
auto wl = transform_direction(inverse(environment->frame), ray.d);
auto texcoord = vec2f{
atan2(wl.z, wl.x) / (2 * pif), acos(clamp(wl.y, -1.0f, 1.0f)) / pif};
if (texcoord.x < 0) texcoord.x += 1;
emission += environment->emission *
eval_texture(environment->emission_tex, texcoord);
}
return emission;
}
} // namespace yocto::pathtrace
// -----------------------------------------------------------------------------
// IMPLEMENTATION FOR SHAPE/SCENE BVH
// -----------------------------------------------------------------------------
namespace yocto::pathtrace {
// primitive used to sort bvh entries
struct bvh_primitive {
bbox3f bbox = invalidb3f;
vec3f center = zero3f;
int primitive = 0;
};
// Splits a BVH node. Returns split position and axis.
static std::pair<int, int> split_middle(
std::vector<bvh_primitive>& primitives, int start, int end) {
// initialize split axis and position
auto axis = 0;
auto mid = (start + end) / 2;
// compute primintive bounds and size
auto cbbox = invalidb3f;
for (auto i = start; i < end; i++) cbbox = merge(cbbox, primitives[i].center);
auto csize = cbbox.max - cbbox.min;
if (csize == zero3f) return {mid, axis};
// split along largest
if (csize.x >= csize.y && csize.x >= csize.z) axis = 0;
if (csize.y >= csize.x && csize.y >= csize.z) axis = 1;
if (csize.z >= csize.x && csize.z >= csize.y) axis = 2;
// split the space in the middle along the largest axis
mid = (int)(std::partition(primitives.data() + start, primitives.data() + end,
[axis, middle = center(cbbox)[axis]](auto& primitive) {
return primitive.center[axis] < middle;
}) -
primitives.data());
// if we were not able to split, just break the primitives in half
if (mid == start || mid == end) {
// throw std::runtime_error("bad bvh split");
mid = (start + end) / 2;
}
return {mid, axis};
}
// Maximum number of primitives per BVH node.
const int bvh_max_prims = 4;
// Build BVH nodes
static void build_bvh(
std::vector<bvh_node>& nodes, std::vector<bvh_primitive>& primitives) {
// prepare to build nodes
nodes.clear();
nodes.reserve(primitives.size() * 2);
// queue up first node
auto queue = std::deque<vec3i>{{0, 0, (int)primitives.size()}};
nodes.emplace_back();
// create nodes until the queue is empty
while (!queue.empty()) {
// grab node to work on
auto next = queue.front();
queue.pop_front();
auto nodeid = next.x, start = next.y, end = next.z;
// grab node
auto& node = nodes[nodeid];
// compute bounds
node.bbox = invalidb3f;
for (auto i = start; i < end; i++)
node.bbox = merge(node.bbox, primitives[i].bbox);
// split into two children
if (end - start > bvh_max_prims) {
// get split
auto [mid, axis] = split_middle(primitives, start, end);
// make an internal node
node.internal = true;
node.axis = axis;
node.num = 2;
node.start = (int)nodes.size();
nodes.emplace_back();
nodes.emplace_back();
queue.push_back({node.start + 0, start, mid});
queue.push_back({node.start + 1, mid, end});
} else {
// Make a leaf node
node.internal = false;
node.num = end - start;
node.start = start;
}
}
// cleanup
nodes.shrink_to_fit();
}
static void init_bvh(ptr::shape* shape, const trace_params& params) {
#ifdef YOCTO_EMBREE
auto edevice = embree_device();
shape->embree_bvh = rtcNewScene(edevice);
rtcSetSceneBuildQuality(shape->embree_bvh, RTC_BUILD_QUALITY_HIGH);
if (!shape->lines.empty()) {
auto elines = std::vector<int>{};
auto epositions = std::vector<vec4f>{};
auto last_index = -1;
for (auto& l : shape->lines) {
if (last_index == l.x) {
elines.push_back((int)epositions.size() - 1);
epositions.push_back({shape->positions[l.y], shape->radius[l.y]});
} else {
elines.push_back((int)epositions.size());
epositions.push_back({shape->positions[l.x], shape->radius[l.x]});
epositions.push_back({shape->positions[l.y], shape->radius[l.y]});
}
last_index = l.y;
}
auto egeometry = rtcNewGeometry(
edevice, RTC_GEOMETRY_TYPE_FLAT_LINEAR_CURVE);
rtcSetGeometryVertexAttributeCount(egeometry, 1);
auto embree_positions = rtcSetNewGeometryBuffer(egeometry,
RTC_BUFFER_TYPE_VERTEX, 0, RTC_FORMAT_FLOAT4, 16, epositions.size());
auto embree_lines = rtcSetNewGeometryBuffer(
egeometry, RTC_BUFFER_TYPE_INDEX, 0, RTC_FORMAT_UINT, 4, elines.size());
memcpy(embree_positions, epositions.data(), epositions.size() * 16);
memcpy(embree_lines, elines.data(), elines.size() * 4);
rtcCommitGeometry(egeometry);
rtcAttachGeometryByID(shape->embree_bvh, egeometry, 0);
} else if (!shape->triangles.empty()) {
auto egeometry = rtcNewGeometry(edevice, RTC_GEOMETRY_TYPE_TRIANGLE);
rtcSetGeometryVertexAttributeCount(egeometry, 1);
auto embree_positions = rtcSetNewGeometryBuffer(egeometry,
RTC_BUFFER_TYPE_VERTEX, 0, RTC_FORMAT_FLOAT3, 12,
shape->positions.size());
auto embree_triangles = rtcSetNewGeometryBuffer(egeometry,
RTC_BUFFER_TYPE_INDEX, 0, RTC_FORMAT_UINT3, 12,
shape->triangles.size());
memcpy(embree_positions, shape->positions.data(),
shape->positions.size() * 12);
memcpy(embree_triangles, shape->triangles.data(),
shape->triangles.size() * 12);
rtcCommitGeometry(egeometry);
rtcAttachGeometryByID(shape->embree_bvh, egeometry, 0);
}
return rtcCommitScene(shape->embree_bvh);
#endif
// build primitives
auto primitives = std::vector<bvh_primitive>{};
if (!shape->points.empty()) {
for (auto idx = 0; idx < shape->points.size(); idx++) {
auto& p = shape->points[idx];
auto& primitive = primitives.emplace_back();
primitive.bbox = point_bounds(shape->positions[p], shape->radius[p]);
primitive.center = center(primitive.bbox);
primitive.primitive = idx;
}
} else if (!shape->lines.empty()) {
for (auto idx = 0; idx < shape->lines.size(); idx++) {
auto& l = shape->lines[idx];
auto& primitive = primitives.emplace_back();
primitive.bbox = line_bounds(shape->positions[l.x], shape->positions[l.y],
shape->radius[l.x], shape->radius[l.y]);
primitive.center = center(primitive.bbox);
primitive.primitive = idx;
}
} else if (!shape->triangles.empty()) {
for (auto idx = 0; idx < shape->triangles.size(); idx++) {
auto& primitive = primitives.emplace_back();
auto& t = shape->triangles[idx];
primitive.bbox = triangle_bounds(
shape->positions[t.x], shape->positions[t.y], shape->positions[t.z]);
primitive.center = center(primitive.bbox);
primitive.primitive = idx;
}
}
// build nodes
if (shape->bvh) delete shape->bvh;
shape->bvh = new bvh_tree{};
build_bvh(shape->bvh->nodes, primitives);
// set bvh primitives
shape->bvh->primitives.reserve(primitives.size());
for (auto& primitive : primitives) {
shape->bvh->primitives.push_back(primitive.primitive);
}
}
void init_bvh(ptr::scene* scene, const trace_params& params,
progress_callback progress_cb) {
// handle progress
auto progress = vec2i{0, 1 + (int)scene->shapes.size()};
// shapes
for (auto idx = 0; idx < scene->shapes.size(); idx++) {
if (progress_cb) progress_cb("build shape bvh", progress.x++, progress.y);
init_bvh(scene->shapes[idx], params);
}
// handle progress
if (progress_cb) progress_cb("build scene bvh", progress.x++, progress.y);
#ifdef YOCTO_EMBREE
auto edevice = embree_device();
scene->embree_bvh = rtcNewScene(edevice);
rtcSetSceneBuildQuality(scene->embree_bvh, RTC_BUILD_QUALITY_HIGH);
for (auto idx = 0; idx < scene->objects.size(); idx++) {
auto object = scene->objects[idx];
auto egeometry = rtcNewGeometry(edevice, RTC_GEOMETRY_TYPE_INSTANCE);
rtcSetGeometryInstancedScene(egeometry, object->shape->embree_bvh);
rtcSetGeometryTransform(
egeometry, 0, RTC_FORMAT_FLOAT3X4_COLUMN_MAJOR, &object->frame);
rtcCommitGeometry(egeometry);
rtcAttachGeometryByID(scene->embree_bvh, egeometry, idx);
}
// handle progress
if (progress_cb) progress_cb("build bvh", progress.x++, progress.y);
return rtcCommitScene(scene->embree_bvh);
#endif
// instance bboxes
auto primitives = std::vector<bvh_primitive>{};
auto object_id = 0;
for (auto object : scene->objects) {
auto& primitive = primitives.emplace_back();
primitive.bbox =
object->shape->bvh->nodes.empty()
? invalidb3f
: transform_bbox(object->frame, object->shape->bvh->nodes[0].bbox);
primitive.center = center(primitive.bbox);
primitive.primitive = object_id++;
}
// build nodes
if (scene->bvh) delete scene->bvh;
scene->bvh = new bvh_tree{};
build_bvh(scene->bvh->nodes, primitives);
// set bvh primitives
scene->bvh->primitives.reserve(primitives.size());
for (auto& primitive : primitives) {
scene->bvh->primitives.push_back(primitive.primitive);
}
// handle progress
if (progress_cb) progress_cb("build bvh", progress.x++, progress.y);
}
// Intersect ray with a bvh->
static bool intersect_shape_bvh(ptr::shape* shape, const ray3f& ray_,
int& element, vec2f& uv, float& distance, bool find_any) {
#ifdef YOCTO_EMBREE
RTCRayHit eray;
eray.ray.org_x = ray_.o.x;
eray.ray.org_y = ray_.o.y;
eray.ray.org_z = ray_.o.z;
eray.ray.dir_x = ray_.d.x;
eray.ray.dir_y = ray_.d.y;
eray.ray.dir_z = ray_.d.z;
eray.ray.tnear = ray_.tmin;
eray.ray.tfar = ray_.tmax;
eray.ray.flags = 0;
eray.hit.geomID = RTC_INVALID_GEOMETRY_ID;
eray.hit.instID[0] = RTC_INVALID_GEOMETRY_ID;
RTCIntersectContext ctx;
rtcInitIntersectContext(&ctx);
rtcIntersect1(shape->embree_bvh, &ctx, &eray);
if (eray.hit.geomID == RTC_INVALID_GEOMETRY_ID) return false;
element = (int)eray.hit.primID;
uv = {eray.hit.u, eray.hit.v};
distance = eray.ray.tfar;
return true;
#endif
// get bvh and shape pointers for fast access
auto bvh = shape->bvh;
// check empty
if (bvh->nodes.empty()) return false;
// node stack
int node_stack[128];
auto node_cur = 0;
node_stack[node_cur++] = 0;
// shared variables
auto hit = false;
// copy ray to modify it
auto ray = ray_;
// prepare ray for fast queries
auto ray_dinv = vec3f{1 / ray.d.x, 1 / ray.d.y, 1 / ray.d.z};
auto ray_dsign = vec3i{(ray_dinv.x < 0) ? 1 : 0, (ray_dinv.y < 0) ? 1 : 0,
(ray_dinv.z < 0) ? 1 : 0};
// walking stack
while (node_cur) {
// grab node
auto& node = bvh->nodes[node_stack[--node_cur]];
// intersect bbox
// if (!intersect_bbox(ray, ray_dinv, ray_dsign, node.bbox)) continue;
if (!intersect_bbox(ray, ray_dinv, node.bbox)) continue;
// intersect node, switching based on node type
// for each type, iterate over the the primitive list
if (node.internal) {
// for internal nodes, attempts to proceed along the
// split axis from smallest to largest nodes
if (ray_dsign[node.axis]) {
node_stack[node_cur++] = node.start + 0;
node_stack[node_cur++] = node.start + 1;
} else {
node_stack[node_cur++] = node.start + 1;
node_stack[node_cur++] = node.start + 0;
}
} else if (!shape->points.empty()) {
for (auto idx = node.start; idx < node.start + node.num; idx++) {
auto& p = shape->points[shape->bvh->primitives[idx]];
if (intersect_point(
ray, shape->positions[p], shape->radius[p], uv, distance)) {
hit = true;
element = shape->bvh->primitives[idx];
ray.tmax = distance;
}
}
} else if (!shape->lines.empty()) {
for (auto idx = node.start; idx < node.start + node.num; idx++) {
auto& l = shape->lines[shape->bvh->primitives[idx]];
if (intersect_line(ray, shape->positions[l.x], shape->positions[l.y],
shape->radius[l.x], shape->radius[l.y], uv, distance)) {
hit = true;
element = shape->bvh->primitives[idx];
ray.tmax = distance;
}
}
} else if (!shape->triangles.empty()) {
for (auto idx = node.start; idx < node.start + node.num; idx++) {
auto& t = shape->triangles[shape->bvh->primitives[idx]];
if (intersect_triangle(ray, shape->positions[t.x],
shape->positions[t.y], shape->positions[t.z], uv, distance)) {
hit = true;
element = shape->bvh->primitives[idx];
ray.tmax = distance;
}
}
}
// check for early exit
if (find_any && hit) return hit;
}
return hit;
}
// Intersect ray with a bvh->
static bool intersect_scene_bvh(const ptr::scene* scene, const ray3f& ray_,
int& object, int& element, vec2f& uv, float& distance, bool find_any,
bool non_rigid_frames) {
#ifdef YOCTO_EMBREE
RTCRayHit eray;
eray.ray.org_x = ray_.o.x;
eray.ray.org_y = ray_.o.y;
eray.ray.org_z = ray_.o.z;
eray.ray.dir_x = ray_.d.x;
eray.ray.dir_y = ray_.d.y;
eray.ray.dir_z = ray_.d.z;
eray.ray.tnear = ray_.tmin;
eray.ray.tfar = ray_.tmax;
eray.ray.flags = 0;
eray.hit.geomID = RTC_INVALID_GEOMETRY_ID;
eray.hit.instID[0] = RTC_INVALID_GEOMETRY_ID;
RTCIntersectContext ctx;
rtcInitIntersectContext(&ctx);
rtcIntersect1(scene->embree_bvh, &ctx, &eray);
if (eray.hit.geomID == RTC_INVALID_GEOMETRY_ID) return false;
object = (int)eray.hit.instID[0];
element = (int)eray.hit.primID;
uv = {eray.hit.u, eray.hit.v};
distance = eray.ray.tfar;
return true;
#endif
// get bvh and scene pointers for fast access
auto bvh = scene->bvh;
// check empty
if (bvh->nodes.empty()) return false;
// node stack
int node_stack[128];
auto node_cur = 0;
node_stack[node_cur++] = 0;
// shared variables
auto hit = false;
// copy ray to modify it
auto ray = ray_;
// prepare ray for fast queries
auto ray_dinv = vec3f{1 / ray.d.x, 1 / ray.d.y, 1 / ray.d.z};
auto ray_dsign = vec3i{(ray_dinv.x < 0) ? 1 : 0, (ray_dinv.y < 0) ? 1 : 0,
(ray_dinv.z < 0) ? 1 : 0};
// walking stack
while (node_cur) {
// grab node
auto& node = bvh->nodes[node_stack[--node_cur]];
// intersect bbox
// if (!intersect_bbox(ray, ray_dinv, ray_dsign, node.bbox)) continue;
if (!intersect_bbox(ray, ray_dinv, node.bbox)) continue;
// intersect node, switching based on node type
// for each type, iterate over the the primitive list
if (node.internal) {
// for internal nodes, attempts to proceed along the