-
Notifications
You must be signed in to change notification settings - Fork 405
Expand file tree
/
Copy pathoptixraytracer.cpp
More file actions
1278 lines (1063 loc) · 48.6 KB
/
optixraytracer.cpp
File metadata and controls
1278 lines (1063 loc) · 48.6 KB
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 Contributors to the Open Shading Language project.
// SPDX-License-Identifier: BSD-3-Clause
// https://github.com/AcademySoftwareFoundation/OpenShadingLanguage
#include <vector>
#include <OpenImageIO/filesystem.h>
#include <OpenImageIO/sysutil.h>
#include <OSL/oslconfig.h>
#include "optixraytracer.h"
#include "render_params.h"
#include <cuda.h>
#include <cuda_runtime.h>
#include <optix_function_table_definition.h>
#include <optix_stack_size.h>
#include <optix_stubs.h>
// The pre-compiled renderer support library LLVM bitcode is embedded
// into the executable and made available through these variables.
extern int rend_lib_llvm_compiled_ops_size;
extern unsigned char rend_lib_llvm_compiled_ops_block[];
// The entry point for OptiX Module creation changed in OptiX 7.7
#if OPTIX_VERSION < 70700
const auto optixModuleCreateFn = optixModuleCreateFromPTX;
#else
const auto optixModuleCreateFn = optixModuleCreate;
#endif
OSL_NAMESPACE_BEGIN
#define CUDA_CHECK(call) \
{ \
cudaError_t res = call; \
if (res != cudaSuccess) { \
print(stderr, \
"[CUDA ERROR] Cuda call '{}' failed with error:" \
" {} ({}:{})\n", \
#call, cudaGetErrorString(res), __FILE__, __LINE__); \
} \
}
#define OPTIX_CHECK(call) \
{ \
OptixResult res = call; \
if (res != OPTIX_SUCCESS) { \
print(stderr, \
"[OPTIX ERROR] OptiX call '{}' failed with error:" \
" {} ({}:{})\n", \
#call, optixGetErrorName(res), __FILE__, __LINE__); \
exit(1); \
} \
}
#define OPTIX_CHECK_MSG(call, msg) \
{ \
OptixResult res = call; \
if (res != OPTIX_SUCCESS) { \
print(stderr, \
"[OPTIX ERROR] OptiX call '{}' failed with error:" \
" {} ({}:{})\nMessage: {}\n", \
#call, optixGetErrorName(res), __FILE__, __LINE__, msg); \
exit(1); \
} \
}
#define CUDA_SYNC_CHECK() \
{ \
cudaDeviceSynchronize(); \
cudaError_t error = cudaGetLastError(); \
if (error != cudaSuccess) { \
print(stderr, "error ({}: line {}): {}\n", __FILE__, __LINE__, \
cudaGetErrorString(error)); \
exit(1); \
} \
}
#define DEVICE_ALLOC(size) reinterpret_cast<CUdeviceptr>(device_alloc(size))
#define COPY_TO_DEVICE(dst_device, src_host, size) \
copy_to_device(reinterpret_cast<void*>(dst_device), src_host, size)
static void
context_log_cb(unsigned int level, const char* tag, const char* message,
void* /*cbdata */)
{
// std::cerr << "[ ** LOGCALLBACK** " << std::setw( 2 ) << level << "][" << std::setw( 12 ) << tag << "]: " << message << "\n";
}
OptixRaytracer::OptixRaytracer()
{
// Initialize CUDA
cudaFree(0);
CUcontext cuCtx = nullptr; // zero means take the current context
OptixDeviceContextOptions ctx_options = {};
ctx_options.logCallbackFunction = context_log_cb;
ctx_options.logCallbackLevel = 4;
OPTIX_CHECK(optixInit());
OPTIX_CHECK(optixDeviceContextCreate(cuCtx, &ctx_options, &m_optix_ctx));
CUDA_CHECK(cudaSetDevice(0));
CUDA_CHECK(cudaStreamCreate(&m_cuda_stream));
}
OptixRaytracer::~OptixRaytracer()
{
if (m_optix_ctx)
OPTIX_CHECK(optixDeviceContextDestroy(m_optix_ctx));
for (CUdeviceptr ptr : m_ptrs_to_free)
cudaFree(reinterpret_cast<void*>(ptr));
for (cudaArray_t arr : m_arrays_to_free)
cudaFreeArray(arr);
}
void*
OptixRaytracer::device_alloc(size_t size)
{
void* ptr = nullptr;
cudaError_t res = cudaMalloc(reinterpret_cast<void**>(&ptr), size);
if (res != cudaSuccess) {
errhandler().errorfmt("cudaMalloc({}) failed with error: {}\n", size,
cudaGetErrorString(res));
}
m_ptrs_to_free.push_back(reinterpret_cast<CUdeviceptr>(ptr));
return ptr;
}
void
OptixRaytracer::device_free(void* ptr)
{
cudaError_t res = cudaFree(ptr);
if (res != cudaSuccess) {
errhandler().errorfmt("cudaFree() failed with error: {}\n",
cudaGetErrorString(res));
}
}
void*
OptixRaytracer::copy_to_device(void* dst_device, const void* src_host,
size_t size)
{
cudaError_t res = cudaMemcpy(dst_device, src_host, size,
cudaMemcpyHostToDevice);
if (res != cudaSuccess) {
errhandler().errorfmt(
"cudaMemcpy host->device of size {} failed with error: {}\n", size,
cudaGetErrorString(res));
}
return dst_device;
}
std::string
OptixRaytracer::load_ptx_file(string_view filename)
{
std::vector<std::string> paths
= { OIIO::Filesystem::parent_path(OIIO::Sysutil::this_program_path()),
PTX_PATH };
std::string filepath = OIIO::Filesystem::searchpath_find(filename, paths,
false);
if (OIIO::Filesystem::exists(filepath)) {
std::string ptx_string;
if (OIIO::Filesystem::read_text_file(filepath, ptx_string))
return ptx_string;
}
errhandler().severefmt("Unable to load {}", filename);
return {};
}
bool
OptixRaytracer::init_optix_context(int xres OSL_MAYBE_UNUSED,
int yres OSL_MAYBE_UNUSED)
{
if (!options.get_int("no_rend_lib_bitcode")) {
shadingsys->attribute("lib_bitcode",
{ OSL::TypeDesc::UINT8,
rend_lib_llvm_compiled_ops_size },
rend_lib_llvm_compiled_ops_block);
}
return true;
}
bool
OptixRaytracer::synch_attributes()
{
// FIXME -- this is for testing only
// Make some device strings to test userdata parameters
ustring userdata_str1("ud_str_1");
ustring userdata_str2("userdata string");
// Store the user-data
test_str_1 = userdata_str1.hash();
test_str_2 = userdata_str2.hash();
// Set the maximum groupdata buffer allocation size
shadingsys->attribute("max_optix_groupdata_alloc", 1024);
{
// TODO: utilize opaque shading state uniform data structure
// which has a device friendly representation this data
// and is already accessed directly by opcolor and opmatrix for
// the cpu (just remove optix special casing)
char* colorSys = nullptr;
long long cpuDataSizes[2] = { 0, 0 };
if (!shadingsys->getattribute("colorsystem", TypeDesc::PTR,
(void*)&colorSys)
|| !shadingsys->getattribute("colorsystem:sizes",
TypeDesc(TypeDesc::LONGLONG, 2),
(void*)&cpuDataSizes)
|| !colorSys || !cpuDataSizes[0]) {
errhandler().errorfmt("No colorsystem available.");
return false;
}
auto cpuDataSize = cpuDataSizes[0];
auto numStrings = cpuDataSizes[1];
// Get the size data-size, minus the ustring size
const size_t podDataSize = cpuDataSize
- sizeof(ustringhash) * numStrings;
d_color_system = DEVICE_ALLOC(podDataSize
+ sizeof(ustringhash_pod) * numStrings);
COPY_TO_DEVICE(d_color_system, colorSys, podDataSize);
d_osl_printf_buffer = DEVICE_ALLOC(OSL_PRINTF_BUFFER_SIZE);
CUDA_CHECK(cudaMemset(reinterpret_cast<void*>(d_osl_printf_buffer), 0,
OSL_PRINTF_BUFFER_SIZE));
// then copy the device string to the end, first strings starting at dataPtr - (numStrings)
// FIXME -- Should probably handle alignment better.
const ustringhash* cpuStringHash
= (const ustringhash*)(colorSys
+ (cpuDataSize
- sizeof(ustringhash) * numStrings));
CUdeviceptr gpuStrings = d_color_system + podDataSize;
for (const ustringhash* end = cpuStringHash + numStrings;
cpuStringHash < end; ++cpuStringHash) {
ustringhash_pod devStr = cpuStringHash->hash();
COPY_TO_DEVICE(gpuStrings, &devStr, sizeof(devStr));
gpuStrings += sizeof(ustringhash_pod);
}
}
return true;
}
bool
OptixRaytracer::load_optix_module(
const char* filename,
const OptixModuleCompileOptions* module_compile_options,
const OptixPipelineCompileOptions* pipeline_compile_options,
OptixModule* program_module)
{
char msg_log[8192];
// Load the renderer CUDA source and generate PTX for it
std::string program_ptx = load_ptx_file(filename);
if (program_ptx.empty()) {
errhandler().severefmt("Could not find PTX file: {}", filename);
return false;
}
size_t sizeof_msg_log = sizeof(msg_log);
OPTIX_CHECK_MSG(optixModuleCreateFn(m_optix_ctx, module_compile_options,
pipeline_compile_options,
program_ptx.c_str(), program_ptx.size(),
msg_log, &sizeof_msg_log,
program_module),
fmtformat("Creating Module from PTX-file {}", msg_log));
return true;
}
bool
OptixRaytracer::create_optix_pg(const OptixProgramGroupDesc* pg_desc,
const int num_pg,
OptixProgramGroupOptions* program_options,
OptixProgramGroup* pg)
{
char msg_log[8192];
size_t sizeof_msg_log = sizeof(msg_log);
OPTIX_CHECK_MSG(optixProgramGroupCreate(m_optix_ctx, pg_desc, num_pg,
program_options, msg_log,
&sizeof_msg_log, pg),
fmtformat("Creating program group: {}", msg_log));
return true;
}
bool
OptixRaytracer::make_optix_materials()
{
create_modules();
create_programs();
create_shaders();
create_pipeline();
create_sbt();
cleanup_programs();
return true;
}
void
OptixRaytracer::create_modules()
{
char msg_log[8192];
size_t sizeof_msg_log;
// Set the pipeline compile options
m_pipeline_compile_options.traversableGraphFlags
= OPTIX_TRAVERSABLE_GRAPH_FLAG_ALLOW_ANY;
m_pipeline_compile_options.usesMotionBlur = false;
m_pipeline_compile_options.numPayloadValues = 4;
m_pipeline_compile_options.numAttributeValues = 3;
m_pipeline_compile_options.exceptionFlags
= OPTIX_EXCEPTION_FLAG_STACK_OVERFLOW;
m_pipeline_compile_options.pipelineLaunchParamsVariableName
= "render_params";
#if OPTIX_VERSION >= 70100
m_pipeline_compile_options.usesPrimitiveTypeFlags
= OPTIX_PRIMITIVE_TYPE_FLAGS_TRIANGLE;
#endif
// Set the module compile options
m_module_compile_options.maxRegisterCount
= OPTIX_COMPILE_DEFAULT_MAX_REGISTER_COUNT;
m_module_compile_options.optLevel = OPTIX_COMPILE_OPTIMIZATION_DEFAULT;
#if OPTIX_VERSION >= 70400
m_module_compile_options.debugLevel = OPTIX_COMPILE_DEBUG_LEVEL_MINIMAL;
#else
m_module_compile_options.debugLevel = OPTIX_COMPILE_DEBUG_LEVEL_LINEINFO;
#endif
load_optix_module("optix_raytracer.ptx", &m_module_compile_options,
&m_pipeline_compile_options, &m_program_module);
load_optix_module("rend_lib_testrender.ptx", &m_module_compile_options,
&m_pipeline_compile_options, &m_rend_lib_module);
// Retrieve the compiled shadeops PTX
const char* shadeops_ptx = nullptr;
shadingsys->getattribute("shadeops_cuda_ptx", OSL::TypeDesc::PTR,
&shadeops_ptx);
int shadeops_ptx_size = 0;
shadingsys->getattribute("shadeops_cuda_ptx_size", OSL::TypeDesc::INT,
&shadeops_ptx_size);
if (shadeops_ptx == nullptr || shadeops_ptx_size == 0) {
errhandler().severefmt(
"Could not retrieve PTX for the shadeops library");
exit(EXIT_FAILURE);
}
// Create the shadeops module
sizeof_msg_log = sizeof(msg_log);
OPTIX_CHECK_MSG(optixModuleCreateFn(m_optix_ctx, &m_module_compile_options,
&m_pipeline_compile_options,
shadeops_ptx, shadeops_ptx_size,
msg_log, &sizeof_msg_log,
&m_shadeops_module),
fmtformat("Creating module for shadeops library: {}",
msg_log));
}
void
OptixRaytracer::create_programs()
{
char msg_log[8192];
size_t sizeof_msg_log;
// Raygen group
OptixProgramGroupDesc raygen_desc = {};
raygen_desc.kind = OPTIX_PROGRAM_GROUP_KIND_RAYGEN;
raygen_desc.raygen.module = m_program_module;
raygen_desc.raygen.entryFunctionName = "__raygen__deferred";
create_optix_pg(&raygen_desc, 1, &m_program_options, &m_raygen_group);
// Set Globals Raygen group
OptixProgramGroupDesc setglobals_raygen_desc = {};
setglobals_raygen_desc.kind = OPTIX_PROGRAM_GROUP_KIND_RAYGEN;
setglobals_raygen_desc.raygen.module = m_program_module;
setglobals_raygen_desc.raygen.entryFunctionName = "__raygen__setglobals";
sizeof_msg_log = sizeof(msg_log);
OPTIX_CHECK_MSG(
optixProgramGroupCreate(m_optix_ctx, &setglobals_raygen_desc,
1, // number of program groups
&m_program_options, // program options
msg_log, &sizeof_msg_log,
&m_setglobals_raygen_group),
fmtformat("Creating set-globals 'ray-gen' program group: {}", msg_log));
// Miss group
OptixProgramGroupDesc miss_desc = {};
miss_desc.kind = OPTIX_PROGRAM_GROUP_KIND_MISS;
miss_desc.miss.module
= m_program_module; // raygen file/module contains miss program
miss_desc.miss.entryFunctionName = "__miss__";
create_optix_pg(&miss_desc, 1, &m_program_options, &m_miss_group);
// Set Globals Miss group
OptixProgramGroupDesc setglobals_miss_desc = {};
setglobals_miss_desc.kind = OPTIX_PROGRAM_GROUP_KIND_MISS;
setglobals_miss_desc.miss.module = m_program_module;
setglobals_miss_desc.miss.entryFunctionName = "__miss__setglobals";
create_optix_pg(&setglobals_miss_desc, 1, &m_program_options,
&m_setglobals_miss_group);
// Hitgroup -- triangles
OptixProgramGroupDesc tri_hitgroup_desc = {};
tri_hitgroup_desc.kind = OPTIX_PROGRAM_GROUP_KIND_HITGROUP;
tri_hitgroup_desc.hitgroup.moduleCH = m_program_module;
tri_hitgroup_desc.hitgroup.entryFunctionNameCH = "__closesthit__deferred";
create_optix_pg(&tri_hitgroup_desc, 1, &m_program_options,
&m_closesthit_group);
// Direct-callable -- renderer-specific support functions for OSL on the device
OptixProgramGroupDesc rend_lib_desc = {};
rend_lib_desc.kind = OPTIX_PROGRAM_GROUP_KIND_CALLABLES;
rend_lib_desc.callables.moduleDC = m_rend_lib_module;
rend_lib_desc.callables.entryFunctionNameDC
= "__direct_callable__dummy_rend_lib";
rend_lib_desc.callables.moduleCC = 0;
rend_lib_desc.callables.entryFunctionNameCC = nullptr;
create_optix_pg(&rend_lib_desc, 1, &m_program_options, &m_rend_lib_group);
// Direct-callable -- built-in support functions for OSL on the device
OptixProgramGroupDesc shadeops_desc = {};
shadeops_desc.kind = OPTIX_PROGRAM_GROUP_KIND_CALLABLES;
shadeops_desc.callables.moduleDC = m_shadeops_module;
shadeops_desc.callables.entryFunctionNameDC
= "__direct_callable__dummy_shadeops";
shadeops_desc.callables.moduleCC = 0;
shadeops_desc.callables.entryFunctionNameCC = nullptr;
create_optix_pg(&shadeops_desc, 1, &m_program_options, &m_shadeops_group);
}
void
OptixRaytracer::create_shaders()
{
// Space for message logging
char msg_log[8192];
size_t sizeof_msg_log;
// Stand-in: names of shader outputs to preserve
std::vector<const char*> outputs { "Cout" };
int mtl_id = 0;
std::vector<void*> material_interactive_params;
for (const auto& groupref : shaders()) {
std::string group_name, fused_name;
shadingsys->getattribute(groupref.surf.get(), "groupname", group_name);
shadingsys->getattribute(groupref.surf.get(), "group_fused_name",
fused_name);
shadingsys->attribute(groupref.surf.get(), "renderer_outputs",
TypeDesc(TypeDesc::STRING, outputs.size()),
outputs.data());
shadingsys->optimize_group(groupref.surf.get(), nullptr);
if (!shadingsys->find_symbol(*groupref.surf.get(),
ustring(outputs[0]))) {
// FIXME: This is for cases where testshade is run with 1x1 resolution
// Those tests may not have a Cout parameter to write to.
if (m_xres > 1 && m_yres > 1) {
errhandler().warningfmt(
"Requested output '{}', which wasn't found", outputs[0]);
}
}
// Retrieve the compiled ShaderGroup PTX
std::string osl_ptx;
shadingsys->getattribute(groupref.surf.get(), "ptx_compiled_version",
OSL::TypeDesc::PTR, &osl_ptx);
if (osl_ptx.empty()) {
errhandler().errorfmt("Failed to generate PTX for ShaderGroup {}",
group_name);
exit(EXIT_FAILURE);
}
if (options.get_int("saveptx")) {
std::string filename = fmtformat("{}_{}.ptx", group_name, mtl_id++);
OIIO::Filesystem::write_text_file(filename, osl_ptx);
}
void* interactive_params = nullptr;
shadingsys->getattribute(groupref.surf.get(),
"device_interactive_params", TypeDesc::PTR,
&interactive_params);
material_interactive_params.push_back(interactive_params);
OptixModule optix_module;
// Create Programs from the init and group_entry functions,
// and set the OSL functions as Callable Programs so that they
// can be executed by the closest hit program.
sizeof_msg_log = sizeof(msg_log);
OPTIX_CHECK_MSG(optixModuleCreateFn(m_optix_ctx,
&m_module_compile_options,
&m_pipeline_compile_options,
osl_ptx.c_str(), osl_ptx.size(),
msg_log, &sizeof_msg_log,
&optix_module),
fmtformat("Creating module for PTX group {}: {}",
group_name, msg_log));
m_shader_modules.push_back(optix_module);
// Create program groups (for direct callables)
OptixProgramGroupDesc pgDesc[1] = {};
pgDesc[0].kind = OPTIX_PROGRAM_GROUP_KIND_CALLABLES;
pgDesc[0].callables.moduleDC = optix_module;
pgDesc[0].callables.entryFunctionNameDC = fused_name.c_str();
pgDesc[0].callables.moduleCC = 0;
pgDesc[0].callables.entryFunctionNameCC = nullptr;
m_shader_groups.resize(m_shader_groups.size() + 1);
sizeof_msg_log = sizeof(msg_log);
OPTIX_CHECK_MSG(optixProgramGroupCreate(
m_optix_ctx, &pgDesc[0], 1, &m_program_options,
msg_log, &sizeof_msg_log,
&m_shader_groups[m_shader_groups.size() - 1]),
fmtformat("Creating 'shader' group for group {}: {}",
group_name, msg_log));
}
// Upload per-material interactive buffer table
d_interactive_params = DEVICE_ALLOC(sizeof(void*)
* material_interactive_params.size());
COPY_TO_DEVICE(d_interactive_params, material_interactive_params.data(),
sizeof(void*) * material_interactive_params.size());
}
void
OptixRaytracer::create_pipeline()
{
char msg_log[8192];
size_t sizeof_msg_log;
// Set the pipeline link options
m_pipeline_link_options.maxTraceDepth = 1;
#if (OPTIX_VERSION < 70700)
m_pipeline_link_options.debugLevel = OPTIX_COMPILE_DEBUG_LEVEL_FULL;
#endif
#if (OPTIX_VERSION < 70100)
m_pipeline_link_options.overrideUsesMotionBlur = false;
#endif
// Gather all of the program groups
m_final_groups.push_back(m_raygen_group);
m_final_groups.push_back(m_miss_group);
m_final_groups.push_back(m_closesthit_group);
m_final_groups.push_back(m_rend_lib_group);
m_final_groups.push_back(m_shadeops_group);
m_final_groups.push_back(m_setglobals_raygen_group);
m_final_groups.push_back(m_setglobals_miss_group);
m_final_groups.insert(m_final_groups.end(), m_shader_groups.begin(),
m_shader_groups.end());
sizeof_msg_log = sizeof(msg_log);
OPTIX_CHECK_MSG(optixPipelineCreate(m_optix_ctx,
&m_pipeline_compile_options,
&m_pipeline_link_options,
m_final_groups.data(),
int(m_final_groups.size()), msg_log,
&sizeof_msg_log, &m_optix_pipeline),
fmtformat("Creating optix pipeline: {}", msg_log));
// Set the pipeline stack size
OptixStackSizes stack_sizes = {};
for (OptixProgramGroup& program_group : m_final_groups) {
#if (OPTIX_VERSION < 70700)
OPTIX_CHECK(optixUtilAccumulateStackSizes(program_group, &stack_sizes));
#else
// OptiX 7.7+ is able to take the whole pipeline into account
// when calculating the stack requirements.
OPTIX_CHECK(optixUtilAccumulateStackSizes(program_group, &stack_sizes,
m_optix_pipeline));
#endif
}
uint32_t max_trace_depth = 1;
uint32_t max_cc_depth = 1;
uint32_t max_dc_depth = 1;
uint32_t direct_callable_stack_size_from_traversal;
uint32_t direct_callable_stack_size_from_state;
uint32_t continuation_stack_size;
OPTIX_CHECK(optixUtilComputeStackSizes(
&stack_sizes, max_trace_depth, max_cc_depth, max_dc_depth,
&direct_callable_stack_size_from_traversal,
&direct_callable_stack_size_from_state, &continuation_stack_size));
#if (OPTIX_VERSION < 70700)
// NB: Older versions of OptiX are unable to compute the stack requirements
// for extern functions (e.g., the shadeops functions), so we need to
// pad the direct callable stack size to accommodate these functions.
direct_callable_stack_size_from_state += 512;
#endif
const uint32_t max_traversal_depth = 1;
OPTIX_CHECK(optixPipelineSetStackSize(
m_optix_pipeline, direct_callable_stack_size_from_traversal,
direct_callable_stack_size_from_state, continuation_stack_size,
max_traversal_depth));
}
void
OptixRaytracer::create_sbt()
{
// Raygen
{
GenericRecord raygen_record;
CUdeviceptr d_raygen_record;
OPTIX_CHECK(optixSbtRecordPackHeader(m_raygen_group, &raygen_record));
d_raygen_record = DEVICE_ALLOC(sizeof(GenericRecord));
COPY_TO_DEVICE(d_raygen_record, &raygen_record, sizeof(GenericRecord));
m_optix_sbt.raygenRecord = d_raygen_record;
}
// Miss
{
GenericRecord miss_record;
CUdeviceptr d_miss_record;
OPTIX_CHECK(optixSbtRecordPackHeader(m_miss_group, &miss_record));
d_miss_record = DEVICE_ALLOC(sizeof(GenericRecord));
COPY_TO_DEVICE(d_miss_record, &miss_record, sizeof(GenericRecord));
m_optix_sbt.missRecordBase = d_miss_record;
m_optix_sbt.missRecordStrideInBytes = sizeof(GenericRecord);
m_optix_sbt.missRecordCount = 1;
}
// Hitgroups
{
const int nhitgroups = 1;
GenericRecord hitgroup_records[nhitgroups];
CUdeviceptr d_hitgroup_records;
OPTIX_CHECK(
optixSbtRecordPackHeader(m_closesthit_group, &hitgroup_records[0]));
d_hitgroup_records = DEVICE_ALLOC(nhitgroups * sizeof(GenericRecord));
COPY_TO_DEVICE(d_hitgroup_records, &hitgroup_records[0],
nhitgroups * sizeof(GenericRecord));
m_optix_sbt.hitgroupRecordBase = d_hitgroup_records;
m_optix_sbt.hitgroupRecordStrideInBytes = sizeof(GenericRecord);
m_optix_sbt.hitgroupRecordCount = nhitgroups;
}
// Callable programs
{
const int nshaders = int(m_shader_groups.size());
std::vector<GenericRecord> callable_records(nshaders);
CUdeviceptr d_callable_records;
for (size_t idx = 0; idx < m_shader_groups.size(); ++idx) {
OPTIX_CHECK(optixSbtRecordPackHeader(m_shader_groups[idx],
&callable_records[idx]));
}
d_callable_records = DEVICE_ALLOC((nshaders) * sizeof(GenericRecord));
COPY_TO_DEVICE(d_callable_records, callable_records.data(),
(nshaders) * sizeof(GenericRecord));
m_optix_sbt.callablesRecordBase = d_callable_records;
m_optix_sbt.callablesRecordStrideInBytes = sizeof(GenericRecord);
m_optix_sbt.callablesRecordCount = nshaders;
m_setglobals_optix_sbt.callablesRecordBase = d_callable_records;
m_setglobals_optix_sbt.callablesRecordStrideInBytes = sizeof(
GenericRecord);
m_setglobals_optix_sbt.callablesRecordCount = nshaders;
}
// SetGlobals raygen
{
GenericRecord record;
CUdeviceptr d_setglobals_raygen_record;
OPTIX_CHECK(
optixSbtRecordPackHeader(m_setglobals_raygen_group, &record));
d_setglobals_raygen_record = DEVICE_ALLOC(sizeof(GenericRecord));
COPY_TO_DEVICE(d_setglobals_raygen_record, &record,
sizeof(GenericRecord));
m_setglobals_optix_sbt.raygenRecord = d_setglobals_raygen_record;
}
// SetGlobals miss
{
GenericRecord record;
CUdeviceptr d_setglobals_miss_record;
OPTIX_CHECK(optixSbtRecordPackHeader(m_setglobals_miss_group, &record));
d_setglobals_miss_record = DEVICE_ALLOC(sizeof(GenericRecord));
COPY_TO_DEVICE(d_setglobals_miss_record, &record,
sizeof(GenericRecord));
m_setglobals_optix_sbt.missRecordBase = d_setglobals_miss_record;
m_setglobals_optix_sbt.missRecordStrideInBytes = sizeof(GenericRecord);
m_setglobals_optix_sbt.missRecordCount = 1;
}
}
void
OptixRaytracer::cleanup_programs()
{
for (auto&& i : m_final_groups) {
optixProgramGroupDestroy(i);
}
for (auto&& i : m_shader_modules) {
optixModuleDestroy(i);
}
m_shader_modules.clear();
optixModuleDestroy(m_program_module);
optixModuleDestroy(m_rend_lib_module);
optixModuleDestroy(m_shadeops_module);
}
void
OptixRaytracer::build_accel()
{
// TODO: Determine if this assert is needed or useful
OSL_ASSERT(scene.triangles.size() == scene.shaderids.size()
&& "We're assuming one shader ID per triangle...");
OptixAccelBuildOptions accel_options = {};
accel_options.buildFlags = OPTIX_BUILD_FLAG_NONE;
accel_options.operation = OPTIX_BUILD_OPERATION_BUILD;
const size_t vertices_size = sizeof(Vec3) * scene.verts.size();
d_vertices = DEVICE_ALLOC(vertices_size);
COPY_TO_DEVICE(d_vertices, scene.verts.data(), vertices_size);
const size_t indices_size = scene.triangles.size() * sizeof(int32_t) * 3;
d_vert_indices = DEVICE_ALLOC(indices_size);
COPY_TO_DEVICE(d_vert_indices, scene.triangles.data(), indices_size);
const uint32_t triangle_input_flags[1] = { OPTIX_GEOMETRY_FLAG_NONE };
OptixBuildInput triangle_input = {};
triangle_input.type = OPTIX_BUILD_INPUT_TYPE_TRIANGLES;
triangle_input.triangleArray.vertexFormat = OPTIX_VERTEX_FORMAT_FLOAT3;
triangle_input.triangleArray.numVertices = static_cast<uint32_t>(
scene.verts.size());
triangle_input.triangleArray.vertexBuffers = &d_vertices;
triangle_input.triangleArray.flags = triangle_input_flags;
triangle_input.triangleArray.numSbtRecords = 1;
triangle_input.triangleArray.indexFormat
= OPTIX_INDICES_FORMAT_UNSIGNED_INT3;
triangle_input.triangleArray.indexStrideInBytes = sizeof(TriangleIndices);
triangle_input.triangleArray.numIndexTriplets = scene.triangles.size();
triangle_input.triangleArray.indexBuffer = d_vert_indices;
OptixAccelBufferSizes gas_buffer_sizes;
OPTIX_CHECK(optixAccelComputeMemoryUsage(m_optix_ctx, &accel_options,
&triangle_input, 1,
&gas_buffer_sizes));
CUdeviceptr d_temp_buffer;
CUDA_CHECK(cudaMalloc(reinterpret_cast<void**>(&d_temp_buffer),
gas_buffer_sizes.tempSizeInBytes));
d_accel_output_buffer = DEVICE_ALLOC(gas_buffer_sizes.outputSizeInBytes);
OPTIX_CHECK(optixAccelBuild(
m_optix_ctx, 0, &accel_options, &triangle_input, 1, d_temp_buffer,
gas_buffer_sizes.tempSizeInBytes, d_accel_output_buffer,
gas_buffer_sizes.outputSizeInBytes, &m_travHandle, nullptr, 0));
CUDA_CHECK(cudaFree(reinterpret_cast<void*>(d_temp_buffer)));
}
void
OptixRaytracer::prepare_background()
{
if (getBackgroundShaderID() >= 0) {
const int bg_res = std::max<int>(32, getBackgroundResolution());
d_bg_values = DEVICE_ALLOC(3 * sizeof(float) * bg_res * bg_res);
d_bg_rows = DEVICE_ALLOC(sizeof(float) * bg_res);
d_bg_cols = DEVICE_ALLOC(sizeof(float) * bg_res * bg_res);
}
}
void
OptixRaytracer::upload_mesh_data()
{
// Upload the extra geometry data to the device
const size_t uvs_size = sizeof(Vec2) * scene.uvs.size();
d_uvs = DEVICE_ALLOC(uvs_size);
COPY_TO_DEVICE(d_uvs, scene.uvs.data(), uvs_size);
const size_t uv_indices_size = scene.uv_triangles.size() * sizeof(int32_t)
* 3;
d_uv_indices = DEVICE_ALLOC(uv_indices_size);
COPY_TO_DEVICE(d_uv_indices, scene.uv_triangles.data(), uv_indices_size);
const size_t normals_size = sizeof(Vec3) * scene.normals.size();
if (normals_size > 0) {
d_normals = DEVICE_ALLOC(normals_size);
COPY_TO_DEVICE(d_normals, scene.normals.data(), normals_size);
}
const size_t normal_indices_size = scene.n_triangles.size()
* sizeof(int32_t) * 3;
d_normal_indices = DEVICE_ALLOC(normal_indices_size);
COPY_TO_DEVICE(d_normal_indices, scene.n_triangles.data(),
normal_indices_size);
const size_t shader_ids_size = scene.shaderids.size() * sizeof(int);
d_shader_ids = DEVICE_ALLOC(shader_ids_size);
COPY_TO_DEVICE(d_shader_ids, scene.shaderids.data(), shader_ids_size);
// TODO: These could be packed, but for now just use ints instead of bools
std::vector<int32_t> shader_is_light;
for (const bool& is_light : OptixRaytracer::shader_is_light())
shader_is_light.push_back(is_light);
const size_t shader_is_light_size = shader_is_light.size()
* sizeof(int32_t);
d_shader_is_light = DEVICE_ALLOC(shader_is_light_size);
COPY_TO_DEVICE(d_shader_is_light, shader_is_light.data(),
shader_is_light_size);
const size_t lightprims_size = OptixRaytracer::lightprims().size()
* sizeof(uint32_t);
d_lightprims = DEVICE_ALLOC(lightprims_size);
COPY_TO_DEVICE(d_lightprims, OptixRaytracer::lightprims().data(),
lightprims_size);
// Copy the mesh ID for each triangle to the device
std::vector<int> mesh_ids;
for (size_t triIdx = 0; triIdx < scene.triangles.size(); ++triIdx) {
const int meshid = std::upper_bound(scene.last_index.begin(),
scene.last_index.end(), triIdx)
- scene.last_index.begin();
mesh_ids.push_back(meshid);
}
const size_t mesh_ids_size = mesh_ids.size() * sizeof(int32_t);
d_mesh_ids = DEVICE_ALLOC(mesh_ids_size);
COPY_TO_DEVICE(d_mesh_ids, mesh_ids.data(), mesh_ids_size);
// Copy the mesh surface areas to the device
std::vector<float> mesh_surfacearea;
mesh_surfacearea.reserve(scene.last_index.size());
// measure the total surface area of each mesh
int first_index = 0;
for (int last_index : scene.last_index) {
float area = 0;
for (int index = first_index; index < last_index; index++) {
area += scene.primitivearea(index);
}
mesh_surfacearea.emplace_back(area);
first_index = last_index;
}
const size_t mesh_surfacearea_size = mesh_surfacearea.size()
* sizeof(float);
d_surfacearea = DEVICE_ALLOC(mesh_surfacearea_size);
COPY_TO_DEVICE(d_surfacearea, mesh_surfacearea.data(),
mesh_surfacearea_size);
}
/// Return true if the texture handle (previously returned by
/// get_texture_handle()) is a valid texture that can be subsequently
/// read or sampled.
bool
OptixRaytracer::good(TextureHandle* handle OSL_MAYBE_UNUSED)
{
return handle != nullptr;
}
/// Given the name of a texture, return an opaque handle that can be
/// used with texture calls to avoid the name lookups.
RendererServices::TextureHandle*
OptixRaytracer::get_texture_handle(ustring filename,
ShadingContext* /*shading_context*/,
const TextureOpt* /*options*/)
{
auto itr = m_samplers.find(filename);
if (itr == m_samplers.end()) {
// Open image to check the number of mip levels
OIIO::ImageBuf image;
if (!image.init_spec(filename, 0, 0)) {
errhandler().errorfmt("Could not load: {} (hash {})", filename,
filename);
return (TextureHandle*)nullptr;
}
int32_t nmiplevels = std::max(image.nmiplevels(), 1);
int32_t img_width = image.xmax() + 1;
int32_t img_height = image.ymax() + 1;
// hard-code textures to 4 channels
cudaChannelFormatDesc channel_desc
= cudaCreateChannelDesc(32, 32, 32, 32, cudaChannelFormatKindFloat);
cudaMipmappedArray_t mipmapArray;
cudaExtent extent = make_cudaExtent(img_width, img_height, 0);
CUDA_CHECK(cudaMallocMipmappedArray(&mipmapArray, &channel_desc, extent,
nmiplevels));
// Copy the pixel data for each mip level
std::vector<std::vector<float>> level_pixels(nmiplevels);
for (int32_t level = 0; level < nmiplevels; ++level) {
image.reset(filename, 0, level);
OIIO::ROI roi = OIIO::get_roi_full(image.spec());
if (!roi.defined()) {
errhandler().errorfmt(
"Could not load mip level {}: {} (hash {})", level,
filename, filename);
return (TextureHandle*)nullptr;
}
int32_t width = roi.width(), height = roi.height();
level_pixels[level].resize(width * height * 4);
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++) {
image.getpixel(i, j, 0,
&level_pixels[level][((j * width) + i) * 4]);
}
}
cudaArray_t miplevelArray;
CUDA_CHECK(
cudaGetMipmappedArrayLevel(&miplevelArray, mipmapArray, level));
// Copy the texel data into the miplevel array
int32_t pitch = width * 4 * sizeof(float);
CUDA_CHECK(cudaMemcpy2DToArray(miplevelArray, 0, 0,
level_pixels[level].data(), pitch,
pitch, height,
cudaMemcpyHostToDevice));
}
int32_t pitch = img_width * 4 * sizeof(float);
cudaArray_t pixelArray;
CUDA_CHECK(
cudaMallocArray(&pixelArray, &channel_desc, img_width, img_height));
CUDA_CHECK(cudaMemcpy2DToArray(pixelArray, 0, 0, level_pixels[0].data(),
pitch, pitch, img_height,
cudaMemcpyHostToDevice));
m_arrays_to_free.push_back(pixelArray);
cudaResourceDesc res_desc = {};
res_desc.resType = cudaResourceTypeMipmappedArray;
res_desc.res.mipmap.mipmap = mipmapArray;
cudaTextureDesc tex_desc = {};
tex_desc.addressMode[0] = cudaAddressModeWrap;
tex_desc.addressMode[1] = cudaAddressModeWrap;