26# define __KERNEL_OPTIX__
31static void execute_optix_task(
TaskPool &pool, OptixTask task, OptixResult &failure_reason)
33 OptixTask additional_tasks[16];
34 unsigned int num_additional_tasks = 0;
36 const OptixResult
result = optixTaskExecute(task, additional_tasks, 16, &num_additional_tasks);
37 if (
result == OPTIX_SUCCESS) {
38 for (
unsigned int i = 0;
i < num_additional_tasks; ++
i) {
39 pool.
push([&pool, additional_task = additional_tasks[
i], &failure_reason] {
40 execute_optix_task(pool, additional_task, failure_reason);
50 : CUDADevice(info, stats, profiler, headless),
55 launch_params(
this,
"kernel_params",
false)
62 const CUDAContextScope scope(
this);
65 OptixDeviceContextOptions
options = {};
66# ifdef WITH_CYCLES_LOGGING
68 options.logCallbackFunction = [](
unsigned int level,
const char *,
const char *message,
void *) {
89 options.validationMode = OPTIX_DEVICE_CONTEXT_VALIDATION_MODE_ALL;
91 optix_assert(optixDeviceContextCreate(cuContext, &
options, &context));
92# ifdef WITH_CYCLES_LOGGING
93 optix_assert(optixDeviceContextSetLogCallback(
101 launch_params.alloc_to_device(1);
104OptiXDevice::~OptiXDevice()
107 const CUDAContextScope scope(
this);
109 free_bvh_memory_delayed();
113 launch_params.free();
116 if (optix_module !=
nullptr) {
117 optixModuleDestroy(optix_module);
119 for (
int i = 0;
i < 2; ++
i) {
120 if (builtin_modules[
i] !=
nullptr) {
121 optixModuleDestroy(builtin_modules[
i]);
124 for (
int i = 0;
i < NUM_PIPELINES; ++
i) {
125 if (pipelines[
i] !=
nullptr) {
126 optixPipelineDestroy(pipelines[
i]);
129 for (
int i = 0;
i < NUM_PROGRAM_GROUPS; ++
i) {
130 if (groups[
i] !=
nullptr) {
131 optixProgramGroupDestroy(groups[
i]);
136 if (osl_camera_module !=
nullptr) {
137 optixModuleDestroy(osl_camera_module);
139 for (
const OptixModule &
module : osl_modules) {
141 optixModuleDestroy(
module);
144 for (
const OptixProgramGroup &group : osl_groups) {
145 if (group !=
nullptr) {
146 optixProgramGroupDestroy(group);
149 osl_colorsystem.free();
152 optixDeviceContextDestroy(context);
157 return make_unique<OptiXDeviceQueue>(
this);
166static string get_optix_include_dir()
168 const char *env_dir = getenv(
"OPTIX_ROOT_DIR");
169 const char *default_dir = CYCLES_RUNTIME_OPTIX_ROOT_DIR;
171 if (env_dir && env_dir[0]) {
172 const string env_include_dir =
path_join(env_dir,
"include");
173 return env_include_dir;
175 if (default_dir[0]) {
176 const string default_include_dir =
path_join(default_dir,
"include");
177 return default_include_dir;
183string OptiXDevice::compile_kernel_get_common_cflags(
const uint kernel_features)
185 string common_cflags = CUDADevice::compile_kernel_get_common_cflags(kernel_features);
188 common_cflags +=
string_printf(
" -I\"%s\"", get_optix_include_dir().c_str());
192 common_cflags +=
" --keep-device-functions";
195 return common_cflags;
198void OptiXDevice::create_optix_module(
TaskPool &pool,
199 OptixModuleCompileOptions &module_options,
204 OptixTask task =
nullptr;
205 result = optixModuleCreateWithTasks(context,
214 if (
result == OPTIX_SUCCESS) {
215 execute_optix_task(pool, task,
result);
219bool OptiXDevice::load_kernels(
const uint kernel_features)
231 const bool use_osl_shading =
false;
232 const bool use_osl_camera =
false;
236 const bool need_optix_kernels = (kernel_features &
242 string suffix = use_osl_shading ?
"_osl" :
247 if (need_optix_kernels) {
248 ptx_filename =
path_get(
"lib/kernel_optix" + suffix +
".ptx.zst");
249 if (use_adaptive_compilation() ||
path_file_size(ptx_filename) == -1) {
250 std::string optix_include_dir = get_optix_include_dir();
251 if (optix_include_dir.empty()) {
253 "Unable to compile OptiX kernels at runtime. Set OPTIX_ROOT_DIR environment variable "
254 "to a directory containing the OptiX SDK.");
259 "OptiX headers not found at %s, unable to compile OptiX kernels at runtime. Install "
260 "OptiX SDK in the specified location, or set OPTIX_ROOT_DIR environment variable to a "
261 "directory containing the OptiX SDK.",
262 optix_include_dir.c_str()));
269 if (!CUDADevice::load_kernels(kernel_features)) {
273 if (!need_optix_kernels) {
277 const CUDAContextScope scope(
this);
280 if (optix_module !=
nullptr) {
281 optixModuleDestroy(optix_module);
282 optix_module =
nullptr;
284 for (
int i = 0;
i < 2; ++
i) {
285 if (builtin_modules[
i] !=
nullptr) {
286 optixModuleDestroy(builtin_modules[
i]);
287 builtin_modules[
i] =
nullptr;
290 for (
int i = 0;
i < NUM_PIPELINES; ++
i) {
291 if (pipelines[
i] !=
nullptr) {
292 optixPipelineDestroy(pipelines[
i]);
293 pipelines[
i] =
nullptr;
296 for (
int i = 0;
i < NUM_PROGRAM_GROUPS; ++
i) {
297 if (groups[
i] !=
nullptr) {
298 optixProgramGroupDestroy(groups[
i]);
304 if (osl_camera_module !=
nullptr) {
305 optixModuleDestroy(osl_camera_module);
306 osl_camera_module =
nullptr;
310 for (
const OptixModule &
module : osl_modules) {
312 optixModuleDestroy(
module);
317 for (
const OptixProgramGroup &group : osl_groups) {
318 if (group !=
nullptr) {
319 optixProgramGroupDestroy(group);
325 OptixModuleCompileOptions module_options = {};
326 module_options.maxRegisterCount = 0;
329 module_options.optLevel = OPTIX_COMPILE_OPTIMIZATION_LEVEL_0;
330 module_options.debugLevel = OPTIX_COMPILE_DEBUG_LEVEL_FULL;
333 module_options.optLevel = OPTIX_COMPILE_OPTIMIZATION_LEVEL_3;
334 module_options.debugLevel = OPTIX_COMPILE_DEBUG_LEVEL_NONE;
337 module_options.boundValues =
nullptr;
338 module_options.numBoundValues = 0;
339 module_options.payloadTypes =
nullptr;
340 module_options.numPayloadTypes = 0;
343 pipeline_options.usesMotionBlur =
false;
344 pipeline_options.traversableGraphFlags =
345 OPTIX_TRAVERSABLE_GRAPH_FLAG_ALLOW_SINGLE_LEVEL_INSTANCING;
346 pipeline_options.numPayloadValues = 8;
347 pipeline_options.numAttributeValues = 2;
348 pipeline_options.exceptionFlags = OPTIX_EXCEPTION_FLAG_NONE;
349 pipeline_options.pipelineLaunchParamsVariableName =
"kernel_params";
351 pipeline_options.usesPrimitiveTypeFlags = OPTIX_PRIMITIVE_TYPE_FLAGS_TRIANGLE;
354 pipeline_options.usesPrimitiveTypeFlags |= OPTIX_PRIMITIVE_TYPE_FLAGS_ROUND_CATMULLROM;
357 pipeline_options.usesPrimitiveTypeFlags |= OPTIX_PRIMITIVE_TYPE_FLAGS_CUSTOM;
361 pipeline_options.usesPrimitiveTypeFlags |= OPTIX_PRIMITIVE_TYPE_FLAGS_CUSTOM;
368 pipeline_options.usesMotionBlur =
true;
371 pipeline_options.traversableGraphFlags = OPTIX_TRAVERSABLE_GRAPH_FLAG_ALLOW_ANY;
376 if (use_adaptive_compilation() ||
path_file_size(ptx_filename) == -1) {
377 string cflags = compile_kernel_get_common_cflags(kernel_features);
378 ptx_filename = compile_kernel(cflags, (
"kernel" + suffix).c_str(),
"optix",
true);
381 set_error(
string_printf(
"Failed to load OptiX kernel from '%s'", ptx_filename.c_str()));
387 create_optix_module(pool, module_options, ptx_data, optix_module,
result);
389 if (
result != OPTIX_SUCCESS) {
390 set_error(
string_printf(
"Failed to load OptiX kernel from '%s' (%s)",
391 ptx_filename.c_str(),
392 optixGetErrorName(
result)));
398 OptixProgramGroupDesc group_descs[NUM_PROGRAM_GROUPS] = {};
399 OptixProgramGroupOptions group_options = {};
400 group_descs[PG_RGEN_INTERSECT_CLOSEST].kind = OPTIX_PROGRAM_GROUP_KIND_RAYGEN;
401 group_descs[PG_RGEN_INTERSECT_CLOSEST].raygen.module = optix_module;
402 group_descs[PG_RGEN_INTERSECT_CLOSEST].raygen.entryFunctionName =
403 "__raygen__kernel_optix_integrator_intersect_closest";
404 group_descs[PG_RGEN_INTERSECT_SHADOW].kind = OPTIX_PROGRAM_GROUP_KIND_RAYGEN;
405 group_descs[PG_RGEN_INTERSECT_SHADOW].raygen.module = optix_module;
406 group_descs[PG_RGEN_INTERSECT_SHADOW].raygen.entryFunctionName =
407 "__raygen__kernel_optix_integrator_intersect_shadow";
408 group_descs[PG_RGEN_INTERSECT_SUBSURFACE].kind = OPTIX_PROGRAM_GROUP_KIND_RAYGEN;
409 group_descs[PG_RGEN_INTERSECT_SUBSURFACE].raygen.module = optix_module;
410 group_descs[PG_RGEN_INTERSECT_SUBSURFACE].raygen.entryFunctionName =
411 "__raygen__kernel_optix_integrator_intersect_subsurface";
412 group_descs[PG_RGEN_INTERSECT_VOLUME_STACK].kind = OPTIX_PROGRAM_GROUP_KIND_RAYGEN;
413 group_descs[PG_RGEN_INTERSECT_VOLUME_STACK].raygen.module = optix_module;
414 group_descs[PG_RGEN_INTERSECT_VOLUME_STACK].raygen.entryFunctionName =
415 "__raygen__kernel_optix_integrator_intersect_volume_stack";
416 group_descs[PG_RGEN_INTERSECT_DEDICATED_LIGHT].kind = OPTIX_PROGRAM_GROUP_KIND_RAYGEN;
417 group_descs[PG_RGEN_INTERSECT_DEDICATED_LIGHT].raygen.module = optix_module;
418 group_descs[PG_RGEN_INTERSECT_DEDICATED_LIGHT].raygen.entryFunctionName =
419 "__raygen__kernel_optix_integrator_intersect_dedicated_light";
420 group_descs[PG_MISS].kind = OPTIX_PROGRAM_GROUP_KIND_MISS;
421 group_descs[PG_MISS].miss.module = optix_module;
422 group_descs[PG_MISS].miss.entryFunctionName =
"__miss__kernel_optix_miss";
423 group_descs[PG_HITD].kind = OPTIX_PROGRAM_GROUP_KIND_HITGROUP;
424 group_descs[PG_HITD].hitgroup.moduleCH = optix_module;
425 group_descs[PG_HITD].hitgroup.entryFunctionNameCH =
"__closesthit__kernel_optix_hit";
426 group_descs[PG_HITD].hitgroup.moduleAH = optix_module;
427 group_descs[PG_HITD].hitgroup.entryFunctionNameAH =
"__anyhit__kernel_optix_visibility_test";
428 group_descs[PG_HITS].kind = OPTIX_PROGRAM_GROUP_KIND_HITGROUP;
429 group_descs[PG_HITS].hitgroup.moduleAH = optix_module;
430 group_descs[PG_HITS].hitgroup.entryFunctionNameAH =
"__anyhit__kernel_optix_shadow_all_hit";
431 group_descs[PG_HITV].kind = OPTIX_PROGRAM_GROUP_KIND_HITGROUP;
432 group_descs[PG_HITV].hitgroup.moduleCH = optix_module;
433 group_descs[PG_HITV].hitgroup.entryFunctionNameCH =
"__closesthit__kernel_optix_hit";
434 group_descs[PG_HITV].hitgroup.moduleAH = optix_module;
435 group_descs[PG_HITV].hitgroup.entryFunctionNameAH =
"__anyhit__kernel_optix_volume_test";
437 OptixProgramGroupDesc ignore_desc = {};
438 ignore_desc.kind = OPTIX_PROGRAM_GROUP_KIND_HITGROUP;
439 ignore_desc.hitgroup.moduleCH = optix_module;
440 ignore_desc.hitgroup.entryFunctionNameCH =
"__closesthit__kernel_optix_ignore";
441 ignore_desc.hitgroup.moduleAH = optix_module;
442 ignore_desc.hitgroup.entryFunctionNameAH =
"__anyhit__kernel_optix_ignore";
447 OptixBuiltinISOptions builtin_options = {};
448 builtin_options.builtinISModuleType = OPTIX_PRIMITIVE_TYPE_ROUND_CATMULLROM;
449 builtin_options.buildFlags = OPTIX_BUILD_FLAG_PREFER_FAST_TRACE |
450 OPTIX_BUILD_FLAG_ALLOW_COMPACTION |
451 OPTIX_BUILD_FLAG_ALLOW_UPDATE;
452 builtin_options.curveEndcapFlags = OPTIX_CURVE_ENDCAP_DEFAULT;
453 builtin_options.usesMotionBlur =
false;
455 optix_assert(optixBuiltinISModuleGet(
456 context, &module_options, &pipeline_options, &builtin_options, &builtin_modules[0]));
458 group_descs[PG_HITD].hitgroup.moduleIS = builtin_modules[0];
459 group_descs[PG_HITD].hitgroup.entryFunctionNameIS =
nullptr;
460 group_descs[PG_HITS].hitgroup.moduleIS = builtin_modules[0];
461 group_descs[PG_HITS].hitgroup.entryFunctionNameIS =
nullptr;
463 if (pipeline_options.usesMotionBlur) {
464 builtin_options.usesMotionBlur =
true;
466 optix_assert(optixBuiltinISModuleGet(
467 context, &module_options, &pipeline_options, &builtin_options, &builtin_modules[1]));
469 group_descs[PG_HITD_MOTION] = group_descs[PG_HITD];
470 group_descs[PG_HITD_MOTION].hitgroup.moduleIS = builtin_modules[1];
471 group_descs[PG_HITS_MOTION] = group_descs[PG_HITS];
472 group_descs[PG_HITS_MOTION].hitgroup.moduleIS = builtin_modules[1];
473 group_descs[PG_HITV_MOTION] = ignore_desc;
474 group_descs[PG_HITL_MOTION] = ignore_desc;
479 group_descs[PG_HITD].hitgroup.moduleIS = optix_module;
480 group_descs[PG_HITS].hitgroup.moduleIS = optix_module;
481 group_descs[PG_HITD].hitgroup.entryFunctionNameIS =
"__intersection__curve_ribbon";
482 group_descs[PG_HITS].hitgroup.entryFunctionNameIS =
"__intersection__curve_ribbon";
487 group_descs[PG_HITD_POINTCLOUD] = group_descs[PG_HITD];
488 group_descs[PG_HITD_POINTCLOUD].kind = OPTIX_PROGRAM_GROUP_KIND_HITGROUP;
489 group_descs[PG_HITD_POINTCLOUD].hitgroup.moduleIS = optix_module;
490 group_descs[PG_HITD_POINTCLOUD].hitgroup.entryFunctionNameIS =
"__intersection__point";
491 group_descs[PG_HITS_POINTCLOUD] = group_descs[PG_HITS];
492 group_descs[PG_HITS_POINTCLOUD].kind = OPTIX_PROGRAM_GROUP_KIND_HITGROUP;
493 group_descs[PG_HITS_POINTCLOUD].hitgroup.moduleIS = optix_module;
494 group_descs[PG_HITS_POINTCLOUD].hitgroup.entryFunctionNameIS =
"__intersection__point";
495 group_descs[PG_HITV_POINTCLOUD] = ignore_desc;
496 group_descs[PG_HITL_POINTCLOUD] = ignore_desc;
501 group_descs[PG_HITL].kind = OPTIX_PROGRAM_GROUP_KIND_HITGROUP;
502 group_descs[PG_HITL].hitgroup.moduleAH = optix_module;
503 group_descs[PG_HITL].hitgroup.entryFunctionNameAH =
"__anyhit__kernel_optix_local_hit";
508 group_descs[PG_RGEN_SHADE_SURFACE_RAYTRACE].kind = OPTIX_PROGRAM_GROUP_KIND_RAYGEN;
509 group_descs[PG_RGEN_SHADE_SURFACE_RAYTRACE].raygen.module = optix_module;
510 group_descs[PG_RGEN_SHADE_SURFACE_RAYTRACE].raygen.entryFunctionName =
511 "__raygen__kernel_optix_integrator_shade_surface_raytrace";
515 if (!use_osl_shading) {
516 group_descs[PG_CALL_SVM_AO].kind = OPTIX_PROGRAM_GROUP_KIND_CALLABLES;
517 group_descs[PG_CALL_SVM_AO].callables.moduleDC = optix_module;
518 group_descs[PG_CALL_SVM_AO].callables.entryFunctionNameDC =
"__direct_callable__svm_node_ao";
519 group_descs[PG_CALL_SVM_BEVEL].kind = OPTIX_PROGRAM_GROUP_KIND_CALLABLES;
520 group_descs[PG_CALL_SVM_BEVEL].callables.moduleDC = optix_module;
521 group_descs[PG_CALL_SVM_BEVEL].callables.entryFunctionNameDC =
522 "__direct_callable__svm_node_bevel";
527 group_descs[PG_RGEN_SHADE_SURFACE_MNEE].kind = OPTIX_PROGRAM_GROUP_KIND_RAYGEN;
528 group_descs[PG_RGEN_SHADE_SURFACE_MNEE].raygen.module = optix_module;
529 group_descs[PG_RGEN_SHADE_SURFACE_MNEE].raygen.entryFunctionName =
530 "__raygen__kernel_optix_integrator_shade_surface_mnee";
534 if (use_osl_shading) {
535 group_descs[PG_RGEN_SHADE_BACKGROUND].kind = OPTIX_PROGRAM_GROUP_KIND_RAYGEN;
536 group_descs[PG_RGEN_SHADE_BACKGROUND].raygen.module = optix_module;
537 group_descs[PG_RGEN_SHADE_BACKGROUND].raygen.entryFunctionName =
538 "__raygen__kernel_optix_integrator_shade_background";
539 group_descs[PG_RGEN_SHADE_LIGHT].kind = OPTIX_PROGRAM_GROUP_KIND_RAYGEN;
540 group_descs[PG_RGEN_SHADE_LIGHT].raygen.module = optix_module;
541 group_descs[PG_RGEN_SHADE_LIGHT].raygen.entryFunctionName =
542 "__raygen__kernel_optix_integrator_shade_light";
543 group_descs[PG_RGEN_SHADE_SURFACE].kind = OPTIX_PROGRAM_GROUP_KIND_RAYGEN;
544 group_descs[PG_RGEN_SHADE_SURFACE].raygen.module = optix_module;
545 group_descs[PG_RGEN_SHADE_SURFACE].raygen.entryFunctionName =
546 "__raygen__kernel_optix_integrator_shade_surface";
547 group_descs[PG_RGEN_SHADE_VOLUME].kind = OPTIX_PROGRAM_GROUP_KIND_RAYGEN;
548 group_descs[PG_RGEN_SHADE_VOLUME].raygen.module = optix_module;
549 group_descs[PG_RGEN_SHADE_VOLUME].raygen.entryFunctionName =
550 "__raygen__kernel_optix_integrator_shade_volume";
551 group_descs[PG_RGEN_SHADE_SHADOW].kind = OPTIX_PROGRAM_GROUP_KIND_RAYGEN;
552 group_descs[PG_RGEN_SHADE_SHADOW].raygen.module = optix_module;
553 group_descs[PG_RGEN_SHADE_SHADOW].raygen.entryFunctionName =
554 "__raygen__kernel_optix_integrator_shade_shadow";
555 group_descs[PG_RGEN_SHADE_DEDICATED_LIGHT].kind = OPTIX_PROGRAM_GROUP_KIND_RAYGEN;
556 group_descs[PG_RGEN_SHADE_DEDICATED_LIGHT].raygen.module = optix_module;
557 group_descs[PG_RGEN_SHADE_DEDICATED_LIGHT].raygen.entryFunctionName =
558 "__raygen__kernel_optix_integrator_shade_dedicated_light";
559 group_descs[PG_RGEN_EVAL_DISPLACE].kind = OPTIX_PROGRAM_GROUP_KIND_RAYGEN;
560 group_descs[PG_RGEN_EVAL_DISPLACE].raygen.module = optix_module;
561 group_descs[PG_RGEN_EVAL_DISPLACE].raygen.entryFunctionName =
562 "__raygen__kernel_optix_shader_eval_displace";
563 group_descs[PG_RGEN_EVAL_BACKGROUND].kind = OPTIX_PROGRAM_GROUP_KIND_RAYGEN;
564 group_descs[PG_RGEN_EVAL_BACKGROUND].raygen.module = optix_module;
565 group_descs[PG_RGEN_EVAL_BACKGROUND].raygen.entryFunctionName =
566 "__raygen__kernel_optix_shader_eval_background";
567 group_descs[PG_RGEN_EVAL_CURVE_SHADOW_TRANSPARENCY].kind = OPTIX_PROGRAM_GROUP_KIND_RAYGEN;
568 group_descs[PG_RGEN_EVAL_CURVE_SHADOW_TRANSPARENCY].raygen.module = optix_module;
569 group_descs[PG_RGEN_EVAL_CURVE_SHADOW_TRANSPARENCY].raygen.entryFunctionName =
570 "__raygen__kernel_optix_shader_eval_curve_shadow_transparency";
575 if (use_osl_camera) {
577 string ptx_data, ptx_filename =
path_get(
"lib/kernel_optix_osl_camera.ptx.zst");
580 string_printf(
"Failed to load OptiX OSL camera kernel from '%s'", ptx_filename.c_str()));
586 create_optix_module(pool, module_options, ptx_data, osl_camera_module,
result);
588 if (
result != OPTIX_SUCCESS) {
589 set_error(
string_printf(
"Failed to load OptiX kernel from '%s' (%s)",
590 ptx_filename.c_str(),
591 optixGetErrorName(
result)));
595 group_descs[PG_RGEN_INIT_FROM_CAMERA].kind = OPTIX_PROGRAM_GROUP_KIND_RAYGEN;
596 group_descs[PG_RGEN_INIT_FROM_CAMERA].raygen.module = osl_camera_module;
597 group_descs[PG_RGEN_INIT_FROM_CAMERA].raygen.entryFunctionName =
598 "__raygen__kernel_optix_integrator_init_from_camera";
602 optix_assert(optixProgramGroupCreate(
603 context, group_descs, NUM_PROGRAM_GROUPS, &group_options,
nullptr,
nullptr, groups));
606 OptixStackSizes stack_size[NUM_PROGRAM_GROUPS] = {};
608 sbt_data.alloc(NUM_PROGRAM_GROUPS);
609 memset(sbt_data.host_pointer, 0,
sizeof(SbtRecord) * NUM_PROGRAM_GROUPS);
610 for (
int i = 0;
i < NUM_PROGRAM_GROUPS; ++
i) {
611 optix_assert(optixSbtRecordPackHeader(groups[
i], &sbt_data[
i]));
612 optix_assert(optixProgramGroupGetStackSize(groups[
i], &stack_size[
i],
nullptr));
614 sbt_data.copy_to_device();
617 unsigned int trace_css = stack_size[PG_HITD].cssCH;
619 trace_css = std::max(trace_css, stack_size[PG_HITD].cssIS + stack_size[PG_HITD].cssAH);
620 trace_css = std::max(trace_css, stack_size[PG_HITS].cssIS + stack_size[PG_HITS].cssAH);
621 trace_css = std::max(trace_css, stack_size[PG_HITL].cssIS + stack_size[PG_HITL].cssAH);
622 trace_css = std::max(trace_css, stack_size[PG_HITV].cssIS + stack_size[PG_HITV].cssAH);
623 trace_css = std::max(trace_css,
624 stack_size[PG_HITD_MOTION].cssIS + stack_size[PG_HITD_MOTION].cssAH);
625 trace_css = std::max(trace_css,
626 stack_size[PG_HITS_MOTION].cssIS + stack_size[PG_HITS_MOTION].cssAH);
627 trace_css = std::max(
628 trace_css, stack_size[PG_HITD_POINTCLOUD].cssIS + stack_size[PG_HITD_POINTCLOUD].cssAH);
629 trace_css = std::max(
630 trace_css, stack_size[PG_HITS_POINTCLOUD].cssIS + stack_size[PG_HITS_POINTCLOUD].cssAH);
632 OptixPipelineLinkOptions link_options = {};
633 link_options.maxTraceDepth = 1;
635 if (use_osl_shading || use_osl_camera) {
641 pipeline_groups.reserve(NUM_PROGRAM_GROUPS);
643 pipeline_groups.push_back(groups[PG_RGEN_SHADE_SURFACE_RAYTRACE]);
644 pipeline_groups.push_back(groups[PG_CALL_SVM_AO]);
645 pipeline_groups.push_back(groups[PG_CALL_SVM_BEVEL]);
648 pipeline_groups.push_back(groups[PG_RGEN_SHADE_SURFACE_MNEE]);
650 pipeline_groups.push_back(groups[PG_MISS]);
651 pipeline_groups.push_back(groups[PG_HITD]);
652 pipeline_groups.push_back(groups[PG_HITS]);
653 pipeline_groups.push_back(groups[PG_HITL]);
654 pipeline_groups.push_back(groups[PG_HITV]);
655 if (pipeline_options.usesMotionBlur) {
656 pipeline_groups.push_back(groups[PG_HITD_MOTION]);
657 pipeline_groups.push_back(groups[PG_HITS_MOTION]);
658 pipeline_groups.push_back(groups[PG_HITV_MOTION]);
659 pipeline_groups.push_back(groups[PG_HITL_MOTION]);
662 pipeline_groups.push_back(groups[PG_HITD_POINTCLOUD]);
663 pipeline_groups.push_back(groups[PG_HITS_POINTCLOUD]);
664 pipeline_groups.push_back(groups[PG_HITV_POINTCLOUD]);
665 pipeline_groups.push_back(groups[PG_HITL_POINTCLOUD]);
668 optix_assert(optixPipelineCreate(context,
671 pipeline_groups.data(),
672 pipeline_groups.size(),
675 &pipelines[PIP_SHADE]));
678 const unsigned int css = std::max(stack_size[PG_RGEN_SHADE_SURFACE_RAYTRACE].cssRG,
679 stack_size[PG_RGEN_SHADE_SURFACE_MNEE].cssRG) +
680 link_options.maxTraceDepth * trace_css;
681 const unsigned int dss = std::max(stack_size[PG_CALL_SVM_AO].dssDC,
682 stack_size[PG_CALL_SVM_BEVEL].dssDC);
685 optix_assert(optixPipelineSetStackSize(
686 pipelines[PIP_SHADE], 0, dss, css, pipeline_options.usesMotionBlur ? 3 : 2));
691 pipeline_groups.reserve(NUM_PROGRAM_GROUPS);
692 pipeline_groups.push_back(groups[PG_RGEN_INTERSECT_CLOSEST]);
693 pipeline_groups.push_back(groups[PG_RGEN_INTERSECT_SHADOW]);
694 pipeline_groups.push_back(groups[PG_RGEN_INTERSECT_SUBSURFACE]);
695 pipeline_groups.push_back(groups[PG_RGEN_INTERSECT_VOLUME_STACK]);
696 pipeline_groups.push_back(groups[PG_RGEN_INTERSECT_DEDICATED_LIGHT]);
697 pipeline_groups.push_back(groups[PG_MISS]);
698 pipeline_groups.push_back(groups[PG_HITD]);
699 pipeline_groups.push_back(groups[PG_HITS]);
700 pipeline_groups.push_back(groups[PG_HITL]);
701 pipeline_groups.push_back(groups[PG_HITV]);
702 if (pipeline_options.usesMotionBlur) {
703 pipeline_groups.push_back(groups[PG_HITD_MOTION]);
704 pipeline_groups.push_back(groups[PG_HITS_MOTION]);
707 pipeline_groups.push_back(groups[PG_HITD_POINTCLOUD]);
708 pipeline_groups.push_back(groups[PG_HITS_POINTCLOUD]);
711 optix_assert(optixPipelineCreate(context,
714 pipeline_groups.data(),
715 pipeline_groups.size(),
718 &pipelines[PIP_INTERSECT]));
721 const unsigned int css =
722 std::max(stack_size[PG_RGEN_INTERSECT_CLOSEST].cssRG,
723 std::max(stack_size[PG_RGEN_INTERSECT_SHADOW].cssRG,
724 std::max(stack_size[PG_RGEN_INTERSECT_SUBSURFACE].cssRG,
725 stack_size[PG_RGEN_INTERSECT_VOLUME_STACK].cssRG))) +
726 link_options.maxTraceDepth * trace_css;
728 optix_assert(optixPipelineSetStackSize(
729 pipelines[PIP_INTERSECT], 0, 0, css, pipeline_options.usesMotionBlur ? 3 : 2));
732 return !have_error();
735bool OptiXDevice::load_osl_kernels()
747 auto get_osl_kernel = [&](
const OSL::ShaderGroupRef &group) {
753 osl_globals.ss->getattribute(group.get(),
"num_layers", num_layers);
754 if (num_layers == 0) {
761 osl_globals.ss->getattribute(group.get(),
"group_fused_name", fused_name);
762 osl_globals.ss->getattribute(
763 group.get(),
"ptx_compiled_version", OSL::TypeDesc::PTR, &osl_ptx);
765 int groupdata_size = 0;
766 osl_globals.ss->getattribute(group.get(),
"llvm_groupdata_size", groupdata_size);
767 if (groupdata_size == 0) {
769 osl_globals.ss->getattribute(group.get(),
"groupdata_size", groupdata_size);
771 if (groupdata_size > 2048) {
773 string_printf(
"Requested OSL group data size (%d) is greater than the maximum "
774 "supported with OptiX (2048)",
779 return OSLKernel{std::move(osl_ptx), std::move(fused_name)};
785 osl_kernels.emplace_back(get_osl_kernel(osl_globals.camera_state));
786 for (
const OSL::ShaderGroupRef &group : osl_globals.surface_state) {
787 osl_kernels.emplace_back(get_osl_kernel(group));
789 for (
const OSL::ShaderGroupRef &group : osl_globals.volume_state) {
790 osl_kernels.emplace_back(get_osl_kernel(group));
792 for (
const OSL::ShaderGroupRef &group : osl_globals.displacement_state) {
793 osl_kernels.emplace_back(get_osl_kernel(group));
795 for (
const OSL::ShaderGroupRef &group : osl_globals.bump_state) {
796 osl_kernels.emplace_back(get_osl_kernel(group));
803 const CUDAContextScope scope(
this);
805 if (pipelines[PIP_SHADE]) {
806 optixPipelineDestroy(pipelines[PIP_SHADE]);
809 for (OptixModule &
module : osl_modules) {
811 optixModuleDestroy(
module);
815 for (OptixProgramGroup &group : osl_groups) {
816 if (group !=
nullptr) {
817 optixProgramGroupDestroy(group);
824 if (osl_kernels.size() == 1 && osl_kernels[0].ptx.empty()) {
828 OptixProgramGroupOptions group_options = {};
829 OptixModuleCompileOptions module_options = {};
830 module_options.optLevel = OPTIX_COMPILE_OPTIMIZATION_LEVEL_3;
831 module_options.debugLevel = OPTIX_COMPILE_DEBUG_LEVEL_NONE;
835 size_t id_osl_services = osl_kernels.size();
836 size_t id_osl_shadeops = osl_kernels.size() + 1;
837 osl_groups.resize(osl_kernels.size() + 2);
838 osl_modules.resize(osl_kernels.size() + 2);
841 string osl_services_ptx, ptx_filename =
path_get(
"lib/kernel_optix_osl_services.ptx.zst");
843 set_error(
string_printf(
"Failed to load OptiX OSL services kernel from '%s'",
844 ptx_filename.c_str()));
848 const char *shadeops_ptx_ptr =
nullptr;
849 osl_globals.ss->getattribute(
"shadeops_cuda_ptx", OSL::TypeDesc::PTR, &shadeops_ptx_ptr);
850 int shadeops_ptx_size = 0;
851 osl_globals.ss->getattribute(
"shadeops_cuda_ptx_size", OSL::TypeDesc::INT, &shadeops_ptx_size);
852 string shadeops_ptx(shadeops_ptx_ptr, shadeops_ptx_size);
855 OptixResult services_result, shadeops_result;
857 pool, module_options, osl_services_ptx, osl_modules[id_osl_services], services_result);
859 pool, module_options, shadeops_ptx, osl_modules[id_osl_shadeops], shadeops_result);
863 if (services_result != OPTIX_SUCCESS) {
864 set_error(
string_printf(
"Failed to load OptiX OSL services kernel from '%s' (%s)",
865 ptx_filename.c_str(),
866 optixGetErrorName(services_result)));
869 OptixProgramGroupDesc group_desc = {};
870 group_desc.kind = OPTIX_PROGRAM_GROUP_KIND_CALLABLES;
871 group_desc.callables.entryFunctionNameDC =
"__direct_callable__dummy_services";
872 group_desc.callables.moduleDC = osl_modules[id_osl_services];
874 optix_assert(optixProgramGroupCreate(context,
880 &osl_groups[id_osl_services]));
884 if (shadeops_result != OPTIX_SUCCESS) {
885 set_error(
string_printf(
"Failed to load OptiX OSL shadeops kernel (%s)",
886 optixGetErrorName(shadeops_result)));
889 OptixProgramGroupDesc group_desc = {};
890 group_desc.kind = OPTIX_PROGRAM_GROUP_KIND_CALLABLES;
891 group_desc.callables.entryFunctionNameDC =
"__direct_callable__dummy_shadeops";
892 group_desc.callables.moduleDC = osl_modules[id_osl_shadeops];
894 optix_assert(optixProgramGroupCreate(context,
900 &osl_groups[id_osl_shadeops]));
907 for (
size_t i = 0;
i < osl_kernels.size(); ++
i) {
908 if (osl_kernels[
i].ptx.empty()) {
912 create_optix_module(pool, module_options, osl_kernels[
i].ptx, osl_modules[
i], results[
i]);
917 for (
size_t i = 0;
i < osl_kernels.size(); ++
i) {
918 if (osl_kernels[
i].ptx.empty()) {
922 if (results[
i] != OPTIX_SUCCESS) {
923 set_error(
string_printf(
"Failed to load OptiX OSL kernel for %s (%s)",
924 osl_kernels[
i].fused_entry.c_str(),
925 optixGetErrorName(results[
i])));
929 OptixProgramGroupDesc group_desc = {};
930 group_desc.kind = OPTIX_PROGRAM_GROUP_KIND_CALLABLES;
931 group_desc.callables.entryFunctionNameDC = osl_kernels[
i].fused_entry.c_str();
932 group_desc.callables.moduleDC = osl_modules[
i];
934 optix_assert(optixProgramGroupCreate(
935 context, &group_desc, 1, &group_options,
nullptr,
nullptr, &osl_groups[
i]));
939 sbt_data.alloc(NUM_PROGRAM_GROUPS + osl_groups.size());
940 for (
int i = 0;
i < NUM_PROGRAM_GROUPS; ++
i) {
941 optix_assert(optixSbtRecordPackHeader(groups[
i], &sbt_data[
i]));
943 for (
size_t i = 0;
i < osl_groups.size(); ++
i) {
944 if (osl_groups[
i] !=
nullptr) {
945 optix_assert(optixSbtRecordPackHeader(osl_groups[
i], &sbt_data[NUM_PROGRAM_GROUPS +
i]));
950 optix_assert(optixSbtRecordPackHeader(osl_groups[id_osl_services],
951 &sbt_data[NUM_PROGRAM_GROUPS +
i]));
954 sbt_data.copy_to_device();
956 OptixPipelineLinkOptions link_options = {};
957 link_options.maxTraceDepth = 0;
961 pipeline_groups.reserve(NUM_PROGRAM_GROUPS);
962 pipeline_groups.push_back(groups[PG_RGEN_SHADE_BACKGROUND]);
963 pipeline_groups.push_back(groups[PG_RGEN_SHADE_LIGHT]);
964 pipeline_groups.push_back(groups[PG_RGEN_SHADE_SURFACE]);
965 pipeline_groups.push_back(groups[PG_RGEN_SHADE_SURFACE_RAYTRACE]);
966 pipeline_groups.push_back(groups[PG_CALL_SVM_AO]);
967 pipeline_groups.push_back(groups[PG_CALL_SVM_BEVEL]);
968 pipeline_groups.push_back(groups[PG_RGEN_SHADE_SURFACE_MNEE]);
969 pipeline_groups.push_back(groups[PG_RGEN_SHADE_VOLUME]);
970 pipeline_groups.push_back(groups[PG_RGEN_SHADE_SHADOW]);
971 pipeline_groups.push_back(groups[PG_RGEN_SHADE_DEDICATED_LIGHT]);
972 pipeline_groups.push_back(groups[PG_RGEN_EVAL_DISPLACE]);
973 pipeline_groups.push_back(groups[PG_RGEN_EVAL_BACKGROUND]);
974 pipeline_groups.push_back(groups[PG_RGEN_EVAL_CURVE_SHADOW_TRANSPARENCY]);
975 pipeline_groups.push_back(groups[PG_RGEN_INIT_FROM_CAMERA]);
977 for (
const OptixProgramGroup &group : osl_groups) {
978 if (group !=
nullptr) {
979 pipeline_groups.push_back(group);
983 optix_assert(optixPipelineCreate(context,
986 pipeline_groups.data(),
987 pipeline_groups.size(),
990 &pipelines[PIP_SHADE]));
993 OptixStackSizes stack_size[NUM_PROGRAM_GROUPS] = {};
996 for (
int i = 0;
i < NUM_PROGRAM_GROUPS; ++
i) {
997 optix_assert(optixProgramGroupGetStackSize(groups[
i], &stack_size[
i],
nullptr));
999 for (
size_t i = 0;
i < osl_groups.size(); ++
i) {
1000 if (osl_groups[
i] !=
nullptr) {
1001 optix_assert(optixProgramGroupGetStackSize(
1002 osl_groups[
i], &osl_stack_size[
i], pipelines[PIP_SHADE]));
1006 const unsigned int css = std::max(stack_size[PG_RGEN_SHADE_SURFACE_RAYTRACE].cssRG,
1007 stack_size[PG_RGEN_SHADE_SURFACE_MNEE].cssRG);
1008 unsigned int dss = std::max(stack_size[PG_CALL_SVM_AO].dssDC,
1009 stack_size[PG_CALL_SVM_BEVEL].dssDC);
1010 for (
unsigned int i = 0;
i < osl_stack_size.size(); ++
i) {
1011 dss = std::max(dss, osl_stack_size[
i].dssDC);
1014 optix_assert(optixPipelineSetStackSize(
1015 pipelines[PIP_SHADE], 0, dss, css, pipeline_options.usesMotionBlur ? 3 : 2));
1027 size_t cpu_data_sizes[2] = {0, 0};
1028 osl_globals.ss->getattribute(
"colorsystem", OSL::TypeDesc::PTR, &cpu_data);
1029 osl_globals.ss->getattribute(
1030 "colorsystem:sizes",
TypeDesc(TypeDesc::LONGLONG, 2), (
void *)cpu_data_sizes);
1032 size_t cpu_full_size = cpu_data_sizes[0];
1033 size_t num_strings = cpu_data_sizes[1];
1034 size_t fixed_data_size = cpu_full_size -
sizeof(ustringhash) * num_strings;
1037 uint8_t *gpu_data = osl_colorsystem.alloc(fixed_data_size +
sizeof(
size_t) * num_strings);
1040 memcpy(gpu_data, cpu_data, fixed_data_size);
1043 ustringhash *cpu_strings =
reinterpret_cast<ustringhash *
>(cpu_data + fixed_data_size);
1044 size_t *gpu_strings =
reinterpret_cast<size_t *
>(gpu_data + fixed_data_size);
1045 for (
int i = 0;
i < num_strings;
i++) {
1046 gpu_strings[
i] = cpu_strings[
i].hash();
1050 osl_colorsystem.copy_to_device();
1053 &osl_colorsystem.device_pointer,
1057 return !have_error();
1063OSLGlobals *OptiXDevice::get_cpu_osl_memory()
1066 return &osl_globals;
1072bool OptiXDevice::build_optix_bvh(BVHOptiX *bvh,
1073 OptixBuildOperation operation,
1074 const OptixBuildInput &build_input,
1075 const uint16_t num_motion_steps)
1084 const CUDAContextScope scope(
this);
1089 OptixAccelBufferSizes sizes = {};
1090 OptixAccelBuildOptions
options = {};
1091 options.operation = operation;
1092 if (build_input.type == OPTIX_BUILD_INPUT_TYPE_CURVES) {
1095 options.buildFlags = OPTIX_BUILD_FLAG_PREFER_FAST_TRACE | OPTIX_BUILD_FLAG_ALLOW_COMPACTION |
1096 OPTIX_BUILD_FLAG_ALLOW_UPDATE;
1097 use_fast_trace_bvh =
true;
1099 else if (use_fast_trace_bvh) {
1100 VLOG_INFO <<
"Using fast to trace OptiX BVH";
1101 options.buildFlags = OPTIX_BUILD_FLAG_PREFER_FAST_TRACE | OPTIX_BUILD_FLAG_ALLOW_COMPACTION;
1104 VLOG_INFO <<
"Using fast to update OptiX BVH";
1105 options.buildFlags = OPTIX_BUILD_FLAG_PREFER_FAST_BUILD | OPTIX_BUILD_FLAG_ALLOW_UPDATE;
1108 options.motionOptions.numKeys = num_motion_steps;
1109 options.motionOptions.flags = OPTIX_MOTION_FLAG_START_VANISH | OPTIX_MOTION_FLAG_END_VANISH;
1110 options.motionOptions.timeBegin = 0.0f;
1111 options.motionOptions.timeEnd = 1.0f;
1113 optix_assert(optixAccelComputeMemoryUsage(context, &
options, &build_input, 1, &sizes));
1117 temp_mem.alloc_to_device(
align_up(sizes.tempSizeInBytes, 8) + 8);
1118 if (!temp_mem.device_pointer) {
1125 if (operation == OPTIX_BUILD_OPERATION_BUILD) {
1137 OptixAccelEmitDesc compacted_size_prop = {};
1138 compacted_size_prop.
type = OPTIX_PROPERTY_TYPE_COMPACTED_SIZE;
1141 compacted_size_prop.result =
align_up(temp_mem.device_pointer + sizes.tempSizeInBytes, 8);
1143 OptixTraversableHandle out_handle = 0;
1144 optix_assert(optixAccelBuild(context,
1149 temp_mem.device_pointer,
1150 sizes.tempSizeInBytes,
1152 sizes.outputSizeInBytes,
1154 use_fast_trace_bvh ? &compacted_size_prop :
nullptr,
1155 use_fast_trace_bvh ? 1 : 0));
1156 bvh->traversable_handle =
static_cast<uint64_t>(out_handle);
1159 cuda_assert(cuStreamSynchronize(
nullptr));
1163 if (use_fast_trace_bvh) {
1164 uint64_t compacted_size = sizes.outputSizeInBytes;
1165 cuda_assert(cuMemcpyDtoH(&compacted_size, compacted_size_prop.result,
sizeof(compacted_size)));
1171 if (compacted_size < sizes.outputSizeInBytes) {
1173 compacted_data.alloc_to_device(compacted_size);
1174 if (!compacted_data.device_pointer) {
1177 return !have_error();
1180 optix_assert(optixAccelCompact(context,
1183 compacted_data.device_pointer,
1186 bvh->traversable_handle =
static_cast<uint64_t>(out_handle);
1189 cuda_assert(cuStreamSynchronize(
nullptr));
1191 std::swap(out_data.
device_size, compacted_data.device_size);
1192 std::swap(out_data.
device_pointer, compacted_data.device_pointer);
1198 return !have_error();
1205 free_bvh_memory_delayed();
1207 BVHOptiX *
const bvh_optix =
static_cast<BVHOptiX *
>(bvh);
1209 progress.set_substatus(
"Building OptiX acceleration structure");
1216 OptixBuildOperation operation = OPTIX_BUILD_OPERATION_BUILD;
1217 if (
refit && !use_fast_trace_bvh) {
1218 assert(bvh_optix->traversable_handle != 0);
1219 operation = OPTIX_BUILD_OPERATION_UPDATE;
1222 bvh_optix->as_data->free();
1223 bvh_optix->traversable_handle = 0;
1230 Hair *
const hair =
static_cast<Hair *const
>(geom);
1237 size_t num_motion_steps = 1;
1239 if (pipeline_options.usesMotionBlur && hair->get_use_motion_blur() && motion_keys) {
1240 num_motion_steps = hair->get_motion_steps();
1247 size_t num_vertices = num_segments * 4;
1250 index_data.alloc(num_segments);
1251 vertex_data.alloc(num_vertices * num_motion_steps);
1254 aabb_data.alloc(num_segments * num_motion_steps);
1258 for (
size_t step = 0;
step < num_motion_steps; ++
step) {
1260 const float3 *keys = hair->get_curve_keys().data();
1261 size_t center_step = (num_motion_steps - 1) / 2;
1262 if (
step != center_step) {
1263 size_t attr_offset = (
step > center_step) ?
step - 1 :
step;
1265 keys = motion_keys->
data_float3() + attr_offset * hair->get_curve_keys().size();
1269 for (
size_t curve_index = 0, segment_index = 0, vertex_index =
step * num_vertices;
1274 const array<float> &curve_radius = hair->get_curve_radius();
1276 const int first_key_index = curve.
first_key;
1278 vertex_data[vertex_index++] =
make_float4(keys[first_key_index].
x,
1279 keys[first_key_index].
y,
1280 keys[first_key_index].
z,
1281 curve_radius[first_key_index]);
1286 index_data[segment_index++] = vertex_index - 1;
1288 vertex_data[vertex_index++] =
make_float4(keys[first_key_index + k].
x,
1289 keys[first_key_index + k].
y,
1290 keys[first_key_index + k].
z,
1291 curve_radius[first_key_index + k]);
1294 const int last_key_index = first_key_index + curve.
num_keys - 1;
1296 vertex_data[vertex_index++] =
make_float4(keys[last_key_index].
x,
1297 keys[last_key_index].
y,
1298 keys[last_key_index].
z,
1299 curve_radius[last_key_index]);
1300 vertex_data[vertex_index++] =
make_float4(keys[last_key_index].
x,
1301 keys[last_key_index].
y,
1302 keys[last_key_index].
z,
1303 curve_radius[last_key_index]);
1308 for (
size_t curve_index = 0,
i = 0; curve_index < hair->
num_curves(); ++curve_index) {
1315 const size_t index =
step * num_segments +
i;
1316 aabb_data[index].minX =
bounds.min.x;
1317 aabb_data[index].minY =
bounds.min.y;
1318 aabb_data[index].minZ =
bounds.min.z;
1319 aabb_data[index].maxX =
bounds.max.x;
1320 aabb_data[index].maxY =
bounds.max.y;
1321 aabb_data[index].maxZ =
bounds.max.z;
1328 aabb_data.copy_to_device();
1329 index_data.copy_to_device();
1330 vertex_data.copy_to_device();
1333 aabb_ptrs.reserve(num_motion_steps);
1336 width_ptrs.reserve(num_motion_steps);
1337 vertex_ptrs.reserve(num_motion_steps);
1338 for (
size_t step = 0;
step < num_motion_steps; ++
step) {
1339 aabb_ptrs.push_back(aabb_data.device_pointer +
step * num_segments *
sizeof(OptixAabb));
1340 const device_ptr base_ptr = vertex_data.device_pointer +
1342 width_ptrs.push_back(base_ptr + 3 *
sizeof(
float));
1343 vertex_ptrs.push_back(base_ptr);
1347 unsigned int build_flags = OPTIX_GEOMETRY_FLAG_REQUIRE_SINGLE_ANYHIT_CALL;
1348 OptixBuildInput build_input = {};
1350 build_input.type = OPTIX_BUILD_INPUT_TYPE_CURVES;
1351 build_input.curveArray.curveType = OPTIX_PRIMITIVE_TYPE_ROUND_CATMULLROM;
1352 build_input.curveArray.numPrimitives = num_segments;
1353 build_input.curveArray.vertexBuffers = (CUdeviceptr *)vertex_ptrs.data();
1354 build_input.curveArray.numVertices = num_vertices;
1355 build_input.curveArray.vertexStrideInBytes =
sizeof(
float4);
1356 build_input.curveArray.widthBuffers = (CUdeviceptr *)width_ptrs.data();
1357 build_input.curveArray.widthStrideInBytes =
sizeof(
float4);
1358 build_input.curveArray.indexBuffer = (CUdeviceptr)index_data.device_pointer;
1359 build_input.curveArray.indexStrideInBytes =
sizeof(int);
1360 build_input.curveArray.flag = build_flags;
1366 build_flags |= OPTIX_GEOMETRY_FLAG_DISABLE_ANYHIT;
1368 build_input.type = OPTIX_BUILD_INPUT_TYPE_CUSTOM_PRIMITIVES;
1369 build_input.customPrimitiveArray.aabbBuffers = (CUdeviceptr *)aabb_ptrs.data();
1370 build_input.customPrimitiveArray.numPrimitives = num_segments;
1371 build_input.customPrimitiveArray.strideInBytes =
sizeof(OptixAabb);
1372 build_input.customPrimitiveArray.flags = &build_flags;
1373 build_input.customPrimitiveArray.numSbtRecords = 1;
1377 if (!build_optix_bvh(bvh_optix, operation, build_input, num_motion_steps)) {
1378 progress.set_error(
"Failed to build OptiX acceleration structure");
1383 Mesh *
const mesh =
static_cast<Mesh *const
>(geom);
1388 const size_t num_verts = mesh->get_verts().size();
1390 size_t num_motion_steps = 1;
1392 if (pipeline_options.usesMotionBlur && mesh->get_use_motion_blur() && motion_keys) {
1393 num_motion_steps = mesh->get_motion_steps();
1397 index_data.alloc(mesh->get_triangles().size());
1398 memcpy(index_data.data(),
1399 mesh->get_triangles().data(),
1400 mesh->get_triangles().size() *
sizeof(
int));
1402 vertex_data.alloc(num_verts * num_motion_steps);
1404 for (
size_t step = 0;
step < num_motion_steps; ++
step) {
1407 size_t center_step = (num_motion_steps - 1) / 2;
1409 if (
step != center_step) {
1413 memcpy(vertex_data.data() + num_verts *
step,
verts, num_verts *
sizeof(
float3));
1417 index_data.copy_to_device();
1418 vertex_data.copy_to_device();
1421 vertex_ptrs.reserve(num_motion_steps);
1422 for (
size_t step = 0;
step < num_motion_steps; ++
step) {
1423 vertex_ptrs.push_back(vertex_data.device_pointer + num_verts *
step *
sizeof(
float3));
1427 unsigned int build_flags = OPTIX_GEOMETRY_FLAG_REQUIRE_SINGLE_ANYHIT_CALL;
1428 OptixBuildInput build_input = {};
1429 build_input.type = OPTIX_BUILD_INPUT_TYPE_TRIANGLES;
1430 build_input.triangleArray.vertexBuffers = (CUdeviceptr *)vertex_ptrs.data();
1431 build_input.triangleArray.numVertices = num_verts;
1432 build_input.triangleArray.vertexFormat = OPTIX_VERTEX_FORMAT_FLOAT3;
1433 build_input.triangleArray.vertexStrideInBytes =
sizeof(
float4);
1434 build_input.triangleArray.indexBuffer = index_data.device_pointer;
1435 build_input.triangleArray.numIndexTriplets = mesh->
num_triangles();
1436 build_input.triangleArray.indexFormat = OPTIX_INDICES_FORMAT_UNSIGNED_INT3;
1437 build_input.triangleArray.indexStrideInBytes = 3 *
sizeof(int);
1438 build_input.triangleArray.flags = &build_flags;
1442 build_input.triangleArray.numSbtRecords = 1;
1443 build_input.triangleArray.primitiveIndexOffset = mesh->
prim_offset;
1445 if (!build_optix_bvh(bvh_optix, operation, build_input, num_motion_steps)) {
1446 progress.set_error(
"Failed to build OptiX acceleration structure");
1452 const size_t num_points = pointcloud->
num_points();
1453 if (num_points == 0) {
1457 size_t num_motion_steps = 1;
1459 if (pipeline_options.usesMotionBlur && pointcloud->get_use_motion_blur() && motion_points) {
1460 num_motion_steps = pointcloud->get_motion_steps();
1464 aabb_data.alloc(num_points * num_motion_steps);
1467 for (
size_t step = 0;
step < num_motion_steps; ++
step) {
1469 size_t center_step = (num_motion_steps - 1) / 2;
1471 if (
step == center_step) {
1472 const float3 *points = pointcloud->get_points().data();
1473 const float *radius = pointcloud->get_radius().data();
1475 for (
size_t i = 0;
i < num_points; ++
i) {
1480 const size_t index =
step * num_points +
i;
1481 aabb_data[index].minX =
bounds.min.x;
1482 aabb_data[index].minY =
bounds.min.y;
1483 aabb_data[index].minZ =
bounds.min.z;
1484 aabb_data[index].maxX =
bounds.max.x;
1485 aabb_data[index].maxY =
bounds.max.y;
1486 aabb_data[index].maxZ =
bounds.max.z;
1490 size_t attr_offset = (
step > center_step) ?
step - 1 :
step;
1493 for (
size_t i = 0;
i < num_points; ++
i) {
1498 const size_t index =
step * num_points +
i;
1499 aabb_data[index].minX =
bounds.min.x;
1500 aabb_data[index].minY =
bounds.min.y;
1501 aabb_data[index].minZ =
bounds.min.z;
1502 aabb_data[index].maxX =
bounds.max.x;
1503 aabb_data[index].maxY =
bounds.max.y;
1504 aabb_data[index].maxZ =
bounds.max.z;
1510 aabb_data.copy_to_device();
1513 aabb_ptrs.reserve(num_motion_steps);
1514 for (
size_t step = 0;
step < num_motion_steps; ++
step) {
1515 aabb_ptrs.push_back(aabb_data.device_pointer +
step * num_points *
sizeof(OptixAabb));
1521 unsigned int build_flags = OPTIX_GEOMETRY_FLAG_DISABLE_ANYHIT |
1522 OPTIX_GEOMETRY_FLAG_REQUIRE_SINGLE_ANYHIT_CALL;
1523 OptixBuildInput build_input = {};
1524 build_input.type = OPTIX_BUILD_INPUT_TYPE_CUSTOM_PRIMITIVES;
1525 build_input.customPrimitiveArray.aabbBuffers = (CUdeviceptr *)aabb_ptrs.data();
1526 build_input.customPrimitiveArray.numPrimitives = num_points;
1527 build_input.customPrimitiveArray.strideInBytes =
sizeof(OptixAabb);
1528 build_input.customPrimitiveArray.flags = &build_flags;
1529 build_input.customPrimitiveArray.numSbtRecords = 1;
1530 build_input.customPrimitiveArray.primitiveIndexOffset = pointcloud->
prim_offset;
1532 if (!build_optix_bvh(bvh_optix, operation, build_input, num_motion_steps)) {
1533 progress.set_error(
"Failed to build OptiX acceleration structure");
1538 unsigned int num_instances = 0;
1539 unsigned int max_num_instances = 0xFFFFFFFF;
1541 bvh_optix->as_data->free();
1542 bvh_optix->traversable_handle = 0;
1543 bvh_optix->motion_transform_data->free();
1545 optixDeviceContextGetProperty(context,
1546 OPTIX_DEVICE_PROPERTY_LIMIT_MAX_INSTANCE_ID,
1548 sizeof(max_num_instances));
1550 max_num_instances >>= 1;
1551 if (bvh->
objects.size() > max_num_instances) {
1553 "Failed to build OptiX acceleration structure because there are too many instances");
1559 instances.alloc(bvh->
objects.size());
1562 size_t motion_transform_offset = 0;
1563 if (pipeline_options.usesMotionBlur) {
1564 size_t total_motion_transform_size = 0;
1567 total_motion_transform_size =
align_up(total_motion_transform_size,
1568 OPTIX_TRANSFORM_BYTE_ALIGNMENT);
1569 const size_t motion_keys =
max(ob->get_motion().size(), (
size_t)2) - 2;
1570 total_motion_transform_size = total_motion_transform_size +
1571 sizeof(OptixSRTMotionTransform) +
1572 motion_keys *
sizeof(OptixSRTData);
1576 assert(bvh_optix->motion_transform_data->device ==
this);
1577 bvh_optix->motion_transform_data->alloc_to_device(total_motion_transform_size);
1586 BVHOptiX *
const blas =
static_cast<BVHOptiX *
>(ob->get_geometry()->bvh.get());
1587 OptixTraversableHandle handle = blas->traversable_handle;
1592 OptixInstance &instance = instances[num_instances++];
1593 memset(&instance, 0,
sizeof(instance));
1596 instance.transform[0] = 1.0f;
1597 instance.transform[5] = 1.0f;
1598 instance.transform[10] = 1.0f;
1611 if (0 == instance.visibilityMask) {
1612 instance.visibilityMask = 0xFF;
1615 if (ob->get_geometry()->is_hair() &&
1618 if (pipeline_options.usesMotionBlur && ob->get_geometry()->has_motion_blur()) {
1620 instance.sbtOffset = PG_HITD_MOTION - PG_HITD;
1623 else if (ob->get_geometry()->is_pointcloud()) {
1625 instance.sbtOffset = PG_HITD_POINTCLOUD - PG_HITD;
1628 instance.visibilityMask |= 4;
1637 instance.flags = OPTIX_INSTANCE_FLAG_DISABLE_ANYHIT;
1641 if (pipeline_options.usesMotionBlur && ob->
use_motion()) {
1642 size_t motion_keys =
max(ob->get_motion().size(), (
size_t)2) - 2;
1643 size_t motion_transform_size =
sizeof(OptixSRTMotionTransform) +
1644 motion_keys *
sizeof(OptixSRTData);
1646 const CUDAContextScope scope(
this);
1648 motion_transform_offset =
align_up(motion_transform_offset,
1649 OPTIX_TRANSFORM_BYTE_ALIGNMENT);
1650 CUdeviceptr motion_transform_gpu = bvh_optix->motion_transform_data->device_pointer +
1651 motion_transform_offset;
1652 motion_transform_offset += motion_transform_size;
1656 OptixSRTMotionTransform *motion_transform =
reinterpret_cast<OptixSRTMotionTransform *
>(
1657 motion_transform_storage.data());
1658 motion_transform->child = handle;
1659 motion_transform->motionOptions.numKeys = ob->get_motion().size();
1660 motion_transform->motionOptions.flags = OPTIX_MOTION_FLAG_NONE;
1661 motion_transform->motionOptions.timeBegin = 0.0f;
1662 motion_transform->motionOptions.timeEnd = 1.0f;
1664 OptixSRTData *
const srt_data = motion_transform->srtData;
1667 decomp.data(), ob->get_motion().
data(), ob->get_motion().size());
1669 for (
size_t i = 0;
i < ob->get_motion().
size(); ++
i) {
1671 srt_data[
i].sx = decomp[
i].y.w;
1672 srt_data[
i].sy = decomp[
i].z.w;
1673 srt_data[
i].sz = decomp[
i].w.w;
1676 srt_data[
i].a = decomp[
i].z.x;
1677 srt_data[
i].b = decomp[
i].z.y;
1678 srt_data[
i].c = decomp[
i].w.x;
1684 srt_data[
i].pvx = 0.0f;
1685 srt_data[
i].pvy = 0.0f;
1686 srt_data[
i].pvz = 0.0f;
1689 srt_data[
i].qx = decomp[
i].x.x;
1690 srt_data[
i].qy = decomp[
i].x.y;
1691 srt_data[
i].qz = decomp[
i].x.z;
1692 srt_data[
i].qw = decomp[
i].x.w;
1695 srt_data[
i].tx = decomp[
i].y.x;
1696 srt_data[
i].ty = decomp[
i].y.y;
1697 srt_data[
i].tz = decomp[
i].y.z;
1701 cuMemcpyHtoD(motion_transform_gpu, motion_transform, motion_transform_size);
1702 motion_transform =
nullptr;
1703 motion_transform_storage.clear();
1706 optixConvertPointerToTraversableHandle(context,
1707 motion_transform_gpu,
1708 OPTIX_TRAVERSABLE_TYPE_SRT_MOTION_TRANSFORM,
1709 &instance.traversableHandle);
1712 instance.traversableHandle = handle;
1714 if (ob->get_geometry()->is_instanced()) {
1716 memcpy(instance.transform, &ob->get_tfm(),
sizeof(instance.transform));
1722 instances.resize(num_instances);
1723 instances.copy_to_device();
1726 OptixBuildInput build_input = {};
1727 build_input.type = OPTIX_BUILD_INPUT_TYPE_INSTANCES;
1728 build_input.instanceArray.instances = instances.device_pointer;
1729 build_input.instanceArray.numInstances = num_instances;
1731 if (!build_optix_bvh(bvh_optix, OPTIX_BUILD_OPERATION_BUILD, build_input, 0)) {
1732 progress.set_error(
"Failed to build OptiX acceleration structure");
1734 tlas_handle = bvh_optix->traversable_handle;
1738void OptiXDevice::release_bvh(
BVH *bvh)
1743 BVHOptiX *
const bvh_optix =
static_cast<BVHOptiX *
>(bvh);
1745 delayed_free_bvh_memory.emplace_back(std::move(bvh_optix->as_data));
1746 delayed_free_bvh_memory.emplace_back(std::move(bvh_optix->motion_transform_data));
1747 bvh_optix->traversable_handle = 0;
1750void OptiXDevice::free_bvh_memory_delayed()
1753 delayed_free_bvh_memory.free_memory();
1756void OptiXDevice::const_copy_to(
const char *name,
void *host,
const size_t size)
1759 CUDADevice::const_copy_to(name, host,
size);
1761 if (strcmp(name,
"data") == 0) {
1765 KernelData *
const data = (KernelData *)host;
1766 *(OptixTraversableHandle *)&
data->device_bvh = tlas_handle;
1773# define KERNEL_DATA_ARRAY(data_type, data_name) \
1774 if (strcmp(name, #data_name) == 0) { \
1775 update_launch_params(offsetof(KernelParamsOptiX, data_name), host, size); \
1779# include "kernel/data_arrays.h"
1780# undef KERNEL_DATA_ARRAY
1783void OptiXDevice::update_launch_params(
const size_t offset,
void *
data,
const size_t data_size)
1785 const CUDAContextScope scope(
this);
1787 cuda_assert(cuMemcpyHtoD(launch_params.device_pointer + offset,
data, data_size));
BMesh const char void * data
unsigned long long int uint64_t
static DBVT_INLINE btScalar size(const btDbvtVolume &a)
static btDbvtVolume bounds(btDbvtNode **leaves, int count)
void refit(btStridingMeshInterface *triangles, const btVector3 &aabbMin, const btVector3 &aabbMax)
SIMD_FORCE_INLINE const btScalar & z() const
Return the z value.
SIMD_FORCE_INLINE const btScalar & w() const
Return the w value.
Attribute * find(ustring name) const
vector< Geometry * > geometry
vector< Object * > objects
bool is_pointcloud() const
Curve get_curve(const size_t i) const
size_t curve_segment_offset
size_t num_curves() const
size_t num_segments() const
CurveShapeType curve_shape
device_ptr device_pointer
void alloc_to_device(const size_t num, bool shrink_to_fit=true)
CCL_NAMESPACE_BEGIN struct Options options
#define KERNEL_DATA_ARRAY(type, name)
DebugFlags & DebugFlags()
#define KERNEL_FEATURE_OBJECT_MOTION
#define KERNEL_FEATURE_OSL_SHADING
#define KERNEL_FEATURE_SUBSURFACE
#define KERNEL_FEATURE_HAIR_THICK
#define KERNEL_FEATURE_PATH_TRACING
#define KERNEL_FEATURE_OSL_CAMERA
#define KERNEL_FEATURE_HAIR
#define KERNEL_FEATURE_NODE_RAYTRACE
#define KERNEL_FEATURE_BAKING
#define KERNEL_FEATURE_MNEE
#define KERNEL_FEATURE_POINTCLOUD
#define CCL_NAMESPACE_END
VecBase< float, 4 > float4
#define assert(assertion)
VecBase< float, D > step(VecOp< float, D >, VecOp< float, D >) RET
@ ATTR_STD_MOTION_VERTEX_POSITION
#define VLOG_IS_ON(severity)
Segment< FEdge *, Vec3r > segment
size_t path_file_size(const string &path)
bool path_is_directory(const string &path)
string path_get(const string &sub)
string path_join(const string &dir, const string &file)
bool path_read_compressed_text(const string &path, string &text)
static struct PyModuleDef module
CCL_NAMESPACE_BEGIN string string_printf(const char *format,...)
void bounds_grow(const int k, const float3 *curve_keys, const float *curve_radius, BoundBox &bounds) const
size_t num_triangles() const
int get_device_index() const
bool is_traceable() const
uint visibility_for_tracing() const
void bounds_grow(const float3 *points, const float *radius, BoundBox &bounds) const
Point get_point(const int i) const
size_t num_points() const
void push(TaskRunFunction &&task)
void wait_work(Summary *stats=nullptr)
std::unique_lock< std::mutex > thread_scoped_lock
ccl_device_inline size_t align_up(const size_t offset, const size_t alignment)