-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathoptix_util_private.h
1515 lines (1263 loc) · 49.2 KB
/
optix_util_private.h
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 2025 Shin Watanabe
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
#include "optix_util.h"
#if defined(OPTIXU_Platform_Windows_MSVC)
# define _USE_MATH_DEFINES
# include <Windows.h>
# undef min
# undef max
# undef near
# undef far
# undef RGB
#endif // if defined(OPTIXU_Platform_Windows_MSVC)
#if defined(OPTIXU_Platform_Windows_MSVC)
# pragma warning(push)
# pragma warning(disable:4819)
#endif // if defined(OPTIXU_Platform_Windows_MSVC)
#include <optix_function_table_definition.h>
#include <cuda.h>
#if defined(OPTIXU_Platform_Windows_MSVC)
# pragma warning(pop)
#endif // if defined(OPTIXU_Platform_Windows_MSVC)
#include <sstream>
#include <vector>
#include <unordered_set>
#include <unordered_map>
#include <algorithm>
#include <variant>
#if __cplusplus <= 199711L
# if defined(OPTIXU_Platform_Windows_MSVC)
# pragma message("\"/Zc:__cplusplus\" compiler option to enable the updated __cplusplus definition is recommended.")
# else
# pragma message("Enabling the updated __cplusplus definition is recommended.")
# endif
#endif // if __cplusplus <= 199711L
#if __cplusplus >= 202002L
#include <bit>
#else // if __cplusplus >= 202002L
#include <intrin.h>
#endif // if __cplusplus >= 202002L
#include <stdexcept>
#define CUDADRV_CHECK(call) \
do { \
const CUresult error = call; \
if (error != CUDA_SUCCESS) { \
std::stringstream ss; \
const char* errMsg = "failed to get an error message."; \
cuGetErrorString(error, &errMsg); \
ss << "CUDA call (" << #call << " ) failed with error: '" \
<< errMsg \
<< "' (" __FILE__ << ":" << __LINE__ << ")\n"; \
throw std::runtime_error(ss.str().c_str()); \
} \
} while (0)
#define OPTIX_CHECK(call) \
do { \
const OptixResult error = call; \
if (error != OPTIX_SUCCESS) { \
std::stringstream ss; \
ss << "OptiX call (" << #call << ") failed: " \
<< "(" __FILE__ << ":" << __LINE__ << ")\n"; \
throw std::runtime_error(ss.str().c_str()); \
} \
} while (0)
#define OPTIX_CHECK_LOG(call) \
do { \
const OptixResult error = call; \
if (error != OPTIX_SUCCESS) { \
std::stringstream ss; \
ss << "OptiX call (" << #call << ") failed: " \
<< "(" __FILE__ << ":" << __LINE__ << ")\n" \
<< "Log: " << log << (logSize > sizeof(log) ? "<TRUNCATED>" : "") \
<< "\n"; \
throw std::runtime_error(ss.str().c_str()); \
} \
} while (0)
namespace optixu {
template <typename... Types>
static void _throwRuntimeError(const char* fmt, const Types &... args) {
char str[2048];
snprintf(str, sizeof(str), fmt, args...);
throw std::runtime_error(str);
}
static void logCallBack(uint32_t level, const char* tag, const char* message, void* cbdata) {
optixuPrintf("[%2u][%12s]: %s\n", level, tag, message);
}
static constexpr size_t s_maxMaterialUserDataSize = 512;
static constexpr size_t s_maxGeometryInstanceUserDataSize = 512;
static constexpr size_t s_maxGASChildUserDataSize = 512;
static constexpr size_t s_maxGASUserDataSize = 512;
#if __cplusplus < 202002L
inline uint32_t countr_zero(uint32_t x) {
return _tzcnt_u32(x);
}
#else // if __cplusplus < 202002L
using std::countr_zero;
#endif // if __cplusplus < 202002L
using _Context = Context::Priv;
// Alias private classes.
#define OPTIXU_PREPROCESS_OBJECT(Name) using _ ## Name = Name::Priv
OPTIXU_PREPROCESS_OBJECTS();
#undef OPTIXU_PREPROCESS_OBJECT
#define OPTIXU_OPAQUE_BRIDGE(BaseName) \
friend class BaseName; \
\
BaseName getPublicType() { \
BaseName ret; \
ret.m = this; \
return ret; \
} \
static BaseName::Priv* extract(BaseName publicType) { \
return publicType.m; \
}
template <typename PublicType>
static typename PublicType::Priv* extract(const PublicType &obj) {
return PublicType::Priv::extract(obj);
}
#if OPTIXU_ENABLE_RUNTIME_ERROR
# define OPTIXU_DEFINE_THROW_RUNTIME_ERROR(TypeName) \
template <typename... Types> \
void throwRuntimeError(bool expr, const char* fmt, const Types &... args) const { \
if (expr) \
return; \
\
std::stringstream ss; \
ss << TypeName ## " " << getName() << ": " << fmt; \
optixu::_throwRuntimeError(ss.str().c_str(), args...); \
}
#else // if OPTIXU_ENABLE_RUNTIME_ERROR
# define OPTIXU_DEFINE_THROW_RUNTIME_ERROR(TypeName) \
template <typename... Types> \
void throwRuntimeError(bool, const char*, const Types &...) const {}
#endif // if OPTIXU_ENABLE_RUNTIME_ERROR
struct SizeAlign {
uint32_t size;
uint32_t alignment;
constexpr SizeAlign() : size(0), alignment(1) {}
constexpr SizeAlign(uint32_t s, uint32_t a) : size(s), alignment(a) {}
constexpr SizeAlign &add(const SizeAlign &sa, uint32_t* offset) {
const uint32_t mask = sa.alignment - 1;
alignment = std::max(alignment, sa.alignment);
size = (size + mask) & ~mask;
if (offset)
*offset = size;
size += sa.size;
return *this;
}
constexpr SizeAlign &operator+=(const SizeAlign &sa) {
return add(sa, nullptr);
}
constexpr SizeAlign &alignUp() {
const uint32_t mask = alignment - 1;
size = (size + mask) & ~mask;
return *this;
}
};
static constexpr inline SizeAlign max(const SizeAlign &sa0, const SizeAlign &sa1) {
return SizeAlign{ std::max(sa0.size, sa1.size), std::max(sa0.alignment, sa1.alignment) };
}
static constexpr inline IndexSize convertToIndexSizeEnum(uint32_t indexSize) {
return indexSize > 0 ? static_cast<IndexSize>(countr_zero(indexSize)) : IndexSize::None;
}
class Context::Priv {
CUcontext cuContext;
OptixDeviceContext rawContext;
uint32_t rtCoreVersion;
uint32_t shaderExecutionReorderingFlags;
uint32_t maxInstanceID;
uint32_t numVisibilityMaskBits;
std::unordered_map<const void*, std::string> registeredNames;
public:
OPTIXU_OPAQUE_BRIDGE(Context);
Priv(CUcontext _cuContext, uint32_t logLevel, EnableValidation enableValidation) :
cuContext(_cuContext)
{
throwRuntimeError(logLevel <= 4, "Valid range for logLevel is [0, 4].");
OPTIX_CHECK(optixInit());
OptixDeviceContextOptions options = {};
options.logCallbackFunction = &logCallBack;
options.logCallbackData = nullptr;
options.logCallbackLevel = logLevel;
options.validationMode = enableValidation ?
OPTIX_DEVICE_CONTEXT_VALIDATION_MODE_ALL :
OPTIX_DEVICE_CONTEXT_VALIDATION_MODE_OFF;
OPTIX_CHECK(optixDeviceContextCreate(cuContext, &options, &rawContext));
OPTIX_CHECK(optixDeviceContextGetProperty(
rawContext, OPTIX_DEVICE_PROPERTY_LIMIT_MAX_INSTANCE_ID,
&maxInstanceID, sizeof(maxInstanceID)));
OPTIX_CHECK(optixDeviceContextGetProperty(
rawContext, OPTIX_DEVICE_PROPERTY_LIMIT_NUM_BITS_INSTANCE_VISIBILITY_MASK,
&numVisibilityMaskBits, sizeof(numVisibilityMaskBits)));
OPTIX_CHECK(optixDeviceContextGetProperty(
rawContext, OPTIX_DEVICE_PROPERTY_RTCORE_VERSION,
&rtCoreVersion, sizeof(rtCoreVersion)));
OPTIX_CHECK(optixDeviceContextGetProperty(
rawContext, OPTIX_DEVICE_PROPERTY_SHADER_EXECUTION_REORDERING,
&shaderExecutionReorderingFlags, sizeof(shaderExecutionReorderingFlags)));
}
~Priv() {
optixDeviceContextDestroy(rawContext);
}
uint32_t getMaxInstanceID() const {
return maxInstanceID;
}
uint32_t getNumVisibilityMaskBits() const {
return numVisibilityMaskBits;
}
_Context* getContext() {
return this;
}
OptixDeviceContext getRawContext() const {
return rawContext;
}
void registerName(const void* p, const std::string &name) {
optixuAssert(p, "Object must not be nullptr.");
registeredNames[p] = name;
}
void unregisterName(const void* p) {
optixuAssert(p, "Object must not be nullptr.");
if (registeredNames.count(p) > 0)
registeredNames.erase(p);
}
const char* getRegisteredName(const void* p) const {
if (registeredNames.count(p) > 0)
return registeredNames.at(p).c_str();
return nullptr;
}
std::string getName(const void* p) const {
const char* regName = getRegisteredName(p);
if (regName) {
return regName;
}
else {
char ptrStr[32];
sprintf_s(ptrStr, "%p", p);
return ptrStr;
}
}
void setName(const std::string &name) {
registerName(this, name);
}
const char* getRegisteredName() const {
return getRegisteredName(this);
}
std::string getName() const {
const char* regName = getRegisteredName(this);
if (regName) {
return regName;
}
else {
char ptrStr[32];
sprintf_s(ptrStr, "%p", this);
return ptrStr;
}
}
OPTIXU_DEFINE_THROW_RUNTIME_ERROR("Context");
};
class PrivateObject {
public:
virtual _Context* getContext() const = 0;
OptixDeviceContext getRawContext() const {
return getContext()->getRawContext();
}
void setName(const std::string &name) const {
getContext()->registerName(this, name);
}
const char* getRegisteredName() const {
return getContext()->getRegisteredName(this);
}
std::string getName() const {
return getContext()->getName(this);
}
};
template <>
class Object<Material>::Priv : public PrivateObject {
struct Key {
const _Pipeline* pipeline;
uint32_t rayType;
bool operator<(const Key &rKey) const {
if (pipeline < rKey.pipeline) {
return true;
}
else if (pipeline == rKey.pipeline) {
if (rayType < rKey.rayType)
return true;
}
return false;
}
struct Hash {
typedef std::size_t result_type;
std::size_t operator()(const Key &key) const {
size_t seed = 0;
const auto hash0 = std::hash<const _Pipeline*>()(key.pipeline);
const auto hash1 = std::hash<uint32_t>()(key.rayType);
seed ^= hash0 + 0x9e3779b9 + (seed << 6) + (seed >> 2);
seed ^= hash1 + 0x9e3779b9 + (seed << 6) + (seed >> 2);
return seed;
}
};
bool operator==(const Key &rKey) const {
return pipeline == rKey.pipeline && rayType == rKey.rayType;
}
};
_Context* context;
SizeAlign userDataSizeAlign;
std::vector<uint8_t> userData;
std::unordered_map<Key, _HitProgramGroup*, Key::Hash> programs;
public:
OPTIXU_OPAQUE_BRIDGE(Material);
Priv(_Context* ctxt) :
context(ctxt), userData(sizeof(uint32_t))
{}
~Priv() {
context->unregisterName(this);
}
_Context* getContext() const {
return context;
}
OPTIXU_DEFINE_THROW_RUNTIME_ERROR("Material");
SizeAlign getUserDataSizeAlign() const {
return userDataSizeAlign;
}
void setRecordHeader(
const _Pipeline* pipeline, uint32_t rayType, uint8_t* record, SizeAlign* curSizeAlign) const;
void setRecordData(uint8_t* record, SizeAlign* curSizeAlign) const;
};
template <>
class Object<Scene>::Priv : public PrivateObject {
struct SBTOffsetKey {
uint32_t gasSerialID;
uint32_t matSetIndex;
bool operator<(const SBTOffsetKey &rKey) const {
if (gasSerialID < rKey.gasSerialID) {
return true;
}
else if (gasSerialID == rKey.gasSerialID) {
if (matSetIndex < rKey.matSetIndex)
return true;
}
return false;
}
struct Hash {
typedef std::size_t result_type;
std::size_t operator()(const SBTOffsetKey &key) const {
size_t seed = 0;
const auto hash0 = std::hash<uint32_t>()(key.gasSerialID);
const auto hash1 = std::hash<uint32_t>()(key.matSetIndex);
seed ^= hash0 + 0x9e3779b9 + (seed << 6) + (seed >> 2);
seed ^= hash1 + 0x9e3779b9 + (seed << 6) + (seed >> 2);
return seed;
}
};
bool operator==(const SBTOffsetKey &rKey) const {
return gasSerialID == rKey.gasSerialID && matSetIndex == rKey.matSetIndex;
}
};
_Context* context;
std::unordered_map<uint32_t, _GeometryAccelerationStructure*> geomASs;
std::unordered_map<SBTOffsetKey, uint32_t, SBTOffsetKey::Hash> sbtOffsets;
uint32_t nextGeomASSerialID;
uint32_t singleRecordSize;
uint32_t numSBTRecords;
std::unordered_set<_Transform*> transforms;
std::unordered_set<_InstanceAccelerationStructure*> instASs;
uint32_t sbtLayoutIsUpToDate : 1;
public:
OPTIXU_OPAQUE_BRIDGE(Scene);
Priv(_Context* ctxt) : context(ctxt),
nextGeomASSerialID(0),
singleRecordSize(OPTIX_SBT_RECORD_HEADER_SIZE), numSBTRecords(0),
sbtLayoutIsUpToDate(false)
{}
~Priv() {
context->unregisterName(this);
}
_Context* getContext() const {
return context;
}
OPTIXU_DEFINE_THROW_RUNTIME_ERROR("Scene");
void addGAS(_GeometryAccelerationStructure* gas);
void removeGAS(_GeometryAccelerationStructure* gas);
void addTransform(_Transform* tr) {
transforms.insert(tr);
}
void removeTransform(_Transform* tr) {
transforms.erase(tr);
}
void addIAS(_InstanceAccelerationStructure* ias) {
instASs.insert(ias);
}
void removeIAS(_InstanceAccelerationStructure* ias) {
instASs.erase(ias);
}
bool sbtLayoutGenerationDone() const {
return sbtLayoutIsUpToDate;
}
void markSBTLayoutDirty();
uint32_t getSBTOffset(_GeometryAccelerationStructure* gas, uint32_t matSetIdx);
uint32_t getSingleRecordSize() const {
return singleRecordSize;
}
void setupHitGroupSBT(CUstream stream, const _Pipeline* pipeline, const BufferView &sbt, void* hostMem);
bool isReady(bool* hasMotionGAS, bool* hasMotionIAS);
};
template <>
class Object<OpacityMicroMapArray>::Priv : public PrivateObject {
_Scene* scene;
OptixOpacityMicromapFlags flags;
BufferView rawOmmBuffer;
BufferView perMicroMapDescBuffer;
BufferView outputBuffer;
std::vector<OptixOpacityMicromapHistogramEntry> microMapHistogramEntries;
OptixOpacityMicromapArrayBuildInput buildInput;
OptixMicromapBufferSizes memoryRequirement;
uint32_t memoryUsageComputed : 1;
uint32_t buffersSet : 1;
uint32_t available : 1;
public:
OPTIXU_OPAQUE_BRIDGE(OpacityMicroMapArray);
Priv(_Scene* _scene) :
scene(_scene),
memoryUsageComputed(false), buffersSet(false),
available(false)
{}
~Priv() {
getContext()->unregisterName(this);
}
const _Scene* getScene() const {
return scene;
}
_Context* getContext() const {
return scene->getContext();
}
OPTIXU_DEFINE_THROW_RUNTIME_ERROR("OMM");
bool isReady() const {
return available;
}
BufferView getBuffer() const {
throwRuntimeError(outputBuffer.isValid(), "Output buffer has not been set.");
return outputBuffer;
}
};
template <>
class Object<GeometryInstance>::Priv : public PrivateObject {
_Scene* scene;
SizeAlign userDataSizeAlign;
std::vector<uint8_t> userData;
struct TriangleGeometry {
CUdeviceptr* vertexBufferArray;
BufferView* vertexBuffers;
BufferView triangleBuffer;
BufferView materialIndexBuffer;
OptixVertexFormat vertexFormat;
OptixIndicesFormat indexFormat;
_OpacityMicroMapArray* opacityMicroMapArray;
BufferView opacityMicroMapIndexBuffer;
std::vector<OptixOpacityMicromapUsageCount> opacityMicroMapUsageCounts;
OptixOpacityMicromapArrayIndexingMode opacityMicroMapIndexingMode;
uint32_t opacityMicroMapIndexOffset;
uint32_t materialIndexSize : 3;
uint32_t opacityMicroMapIndexSize : 3;
};
struct CurveGeometry {
CUdeviceptr* vertexBufferArray;
CUdeviceptr* widthBufferArray;
CUdeviceptr* normalBufferArray;
BufferView* vertexBuffers;
BufferView* widthBuffers;
BufferView* normalBuffers;
BufferView segmentIndexBuffer;
OptixCurveEndcapFlags endcapFlags;
};
struct SphereGeometry {
CUdeviceptr* centerBufferArray;
CUdeviceptr* radiusBufferArray;
BufferView* centerBuffers;
BufferView* radiusBuffers;
BufferView materialIndexBuffer;
uint32_t materialIndexSize : 3;
uint32_t useSingleRadius : 1;
};
struct CustomPrimitiveGeometry {
CUdeviceptr* primitiveAabbBufferArray;
BufferView* primitiveAabbBuffers;
BufferView materialIndexBuffer;
uint32_t materialIndexSize : 3;
};
std::variant<
TriangleGeometry,
CurveGeometry,
SphereGeometry,
CustomPrimitiveGeometry
> geometry;
GeometryType geomType;
uint32_t numMotionSteps;
uint32_t primitiveIndexOffset;
std::vector<OptixGeometryFlags> buildInputFlags; // per SBT record
std::vector<std::vector<_Material*>> materials;
public:
OPTIXU_OPAQUE_BRIDGE(GeometryInstance);
Priv(_Scene* _scene, GeometryType _geomType) :
scene(_scene),
userData(),
geomType(_geomType),
primitiveIndexOffset(0)
{
buildInputFlags.resize(1, OPTIX_GEOMETRY_FLAG_NONE);
materials.resize(1);
materials[0].resize(1, nullptr);
numMotionSteps = 1;
if (geomType == GeometryType::Triangles) {
geometry = TriangleGeometry{};
auto &geom = std::get<TriangleGeometry>(geometry);
geom.vertexBufferArray = new CUdeviceptr[numMotionSteps];
geom.vertexBuffers = new BufferView[numMotionSteps];
geom.vertexFormat = OPTIX_VERTEX_FORMAT_FLOAT3;
geom.indexFormat = OPTIX_INDICES_FORMAT_NONE;
geom.opacityMicroMapArray = nullptr;
geom.opacityMicroMapIndexingMode = OPTIX_OPACITY_MICROMAP_ARRAY_INDEXING_MODE_NONE;
geom.opacityMicroMapIndexOffset = 0;
geom.materialIndexSize = 0;
geom.opacityMicroMapIndexSize = 0;
}
else if (geomType == GeometryType::LinearSegments ||
geomType == GeometryType::QuadraticBSplines ||
geomType == GeometryType::QuadraticBSplineRocaps ||
geomType == GeometryType::FlatQuadraticBSplines ||
geomType == GeometryType::CubicBSplines ||
geomType == GeometryType::CubicBSplineRocaps ||
geomType == GeometryType::CatmullRomSplines ||
geomType == GeometryType::CatmullRomSplineRocaps ||
geomType == GeometryType::CubicBezier ||
geomType == GeometryType::CubicBezierRocaps) {
geometry = CurveGeometry{};
auto &geom = std::get<CurveGeometry>(geometry);
geom.vertexBufferArray = new CUdeviceptr[numMotionSteps];
geom.vertexBuffers = new BufferView[numMotionSteps];
geom.widthBufferArray = new CUdeviceptr[numMotionSteps];
geom.widthBuffers = new BufferView[numMotionSteps];
if (geomType == GeometryType::FlatQuadraticBSplines) {
geom.normalBufferArray = new CUdeviceptr[numMotionSteps];
geom.normalBuffers = new BufferView[numMotionSteps];
}
geom.endcapFlags = OPTIX_CURVE_ENDCAP_DEFAULT;
}
else if (geomType == GeometryType::Spheres) {
geometry = SphereGeometry{};
auto &geom = std::get<SphereGeometry>(geometry);
geom.centerBufferArray = new CUdeviceptr[numMotionSteps];
geom.centerBuffers = new BufferView[numMotionSteps];
geom.radiusBufferArray = new CUdeviceptr[numMotionSteps];
geom.radiusBuffers = new BufferView[numMotionSteps];
geom.useSingleRadius = false;
}
else if (geomType == GeometryType::CustomPrimitives) {
geometry = CustomPrimitiveGeometry{};
auto &geom = std::get<CustomPrimitiveGeometry>(geometry);
geom.primitiveAabbBufferArray = new CUdeviceptr[numMotionSteps];
geom.primitiveAabbBuffers = new BufferView[numMotionSteps];
geom.materialIndexSize = 0;
}
else {
optixuAssert_ShouldNotBeCalled();
}
}
~Priv() {
if (std::holds_alternative<TriangleGeometry>(geometry)) {
auto &geom = std::get<TriangleGeometry>(geometry);
delete[] geom.vertexBuffers;
delete[] geom.vertexBufferArray;
}
else if (std::holds_alternative<CurveGeometry>(geometry)) {
auto &geom = std::get<CurveGeometry>(geometry);
if (geomType == GeometryType::FlatQuadraticBSplines) {
delete[] geom.normalBuffers;
delete[] geom.normalBufferArray;
}
delete[] geom.widthBuffers;
delete[] geom.widthBufferArray;
delete[] geom.vertexBuffers;
delete[] geom.vertexBufferArray;
}
else if (std::holds_alternative<SphereGeometry>(geometry)) {
auto &geom = std::get<SphereGeometry>(geometry);
delete[] geom.radiusBuffers;
delete[] geom.radiusBufferArray;
delete[] geom.centerBuffers;
delete[] geom.centerBufferArray;
}
else if (std::holds_alternative<CustomPrimitiveGeometry>(geometry)) {
auto &geom = std::get<CustomPrimitiveGeometry>(geometry);
delete[] geom.primitiveAabbBuffers;
delete[] geom.primitiveAabbBufferArray;
}
else {
optixuAssert_ShouldNotBeCalled();
}
getContext()->unregisterName(this);
}
const _Scene* getScene() const {
return scene;
}
_Context* getContext() const override {
return scene->getContext();
}
OPTIXU_DEFINE_THROW_RUNTIME_ERROR("GeomInst");
GeometryType getGeometryType() const {
return geomType;
}
uint32_t getNumMotionSteps() const {
return numMotionSteps;
}
void fillBuildInput(OptixBuildInput* input, CUdeviceptr preTransform) const;
void updateBuildInput(OptixBuildInput* input, CUdeviceptr preTransform) const;
void calcSBTRequirements(
uint32_t gasMatSetIdx,
const SizeAlign &gasUserDataSizeAlign,
const SizeAlign &gasChildUserDataSizeAlign,
SizeAlign* maxRecordSizeAlign, uint32_t* numSBTRecords) const;
uint32_t fillSBTRecords(
const _Pipeline* pipeline, uint32_t gasMatSetIdx,
const void* gasUserData, const SizeAlign &gasUserDataSizeAlign,
const void* gasChildUserData, const SizeAlign &gasChildUserDataSizeAlign,
uint32_t numRayTypes, uint8_t* records) const;
};
template <>
class Object<GeometryAccelerationStructure>::Priv : public PrivateObject {
struct Child {
_GeometryInstance* geomInst;
CUdeviceptr preTransform;
SizeAlign userDataSizeAlign;
std::vector<uint8_t> userData;
bool operator==(const Child &rChild) const {
return geomInst == rChild.geomInst && preTransform == rChild.preTransform;
}
};
_Scene* scene;
uint32_t serialID;
GeometryType geomType;
SizeAlign userDataSizeAlign;
std::vector<uint8_t> userData;
std::vector<uint32_t> numRayTypesPerMaterialSet;
std::vector<Child> children;
std::vector<OptixBuildInput> buildInputs;
OptixAccelBuildOptions buildOptions;
OptixAccelBufferSizes memoryRequirement;
CUevent finishEvent;
CUdeviceptr compactedSizeOnDevice;
size_t compactedSize;
OptixAccelEmitDesc propertyCompactedSize;
OptixTraversableHandle handle;
OptixTraversableHandle compactedHandle;
BufferView accelBuffer;
BufferView compactedAccelBuffer;
ASTradeoff tradeoff;
uint32_t allowUpdate : 1;
uint32_t allowCompaction : 1;
uint32_t allowRandomVertexAccess : 1;
uint32_t allowOpacityMicroMapUpdate : 1;
uint32_t allowDisableOpacityMicroMaps : 1;
uint32_t readyToBuild : 1;
uint32_t available : 1;
uint32_t readyToCompact : 1;
uint32_t compactedAvailable : 1;
public:
OPTIXU_OPAQUE_BRIDGE(GeometryAccelerationStructure);
Priv(_Scene* _scene, uint32_t _serialID, GeometryType _geomType) :
scene(_scene),
serialID(_serialID),
geomType(_geomType),
userData(sizeof(uint32_t)),
handle(0), compactedHandle(0),
tradeoff(ASTradeoff::Default),
allowUpdate(false), allowCompaction(false), allowRandomVertexAccess(false),
allowOpacityMicroMapUpdate(false), allowDisableOpacityMicroMaps(false),
readyToBuild(false), available(false),
readyToCompact(false), compactedAvailable(false)
{
scene->addGAS(this);
numRayTypesPerMaterialSet.resize(1, 0);
buildOptions = {};
CUDADRV_CHECK(cuEventCreate(
&finishEvent, CU_EVENT_BLOCKING_SYNC | CU_EVENT_DISABLE_TIMING));
CUDADRV_CHECK(cuMemAlloc(&compactedSizeOnDevice, sizeof(size_t)));
propertyCompactedSize = OptixAccelEmitDesc{};
propertyCompactedSize.type = OPTIX_PROPERTY_TYPE_COMPACTED_SIZE;
propertyCompactedSize.result = compactedSizeOnDevice;
}
~Priv() {
cuMemFree(compactedSizeOnDevice);
cuEventDestroy(finishEvent);
scene->removeGAS(this);
getContext()->unregisterName(this);
}
const _Scene* getScene() const {
return scene;
}
_Context* getContext() const override {
return scene->getContext();
}
OPTIXU_DEFINE_THROW_RUNTIME_ERROR("GAS");
uint32_t getSerialID() const {
return serialID;
}
uint32_t getNumMaterialSets() const {
return static_cast<uint32_t>(numRayTypesPerMaterialSet.size());
}
uint32_t getNumRayTypes(uint32_t matSetIdx) const {
return numRayTypesPerMaterialSet[matSetIdx];
}
void calcSBTRequirements(
uint32_t matSetIdx, SizeAlign* maxRecordSizeAlign, uint32_t* numSBTRecords) const;
uint32_t fillSBTRecords(const _Pipeline* pipeline, uint32_t matSetIdx, uint8_t* records) const;
bool hasMotion() const {
return buildOptions.motionOptions.numKeys >= 2;
}
void markDirty();
bool isReady() const {
return available || compactedAvailable;
}
OptixTraversableHandle getHandle() const {
throwRuntimeError(isReady(), "Traversable handle is not ready.");
if (compactedAvailable)
return compactedHandle;
if (available)
return handle;
optixuAssert_ShouldNotBeCalled();
return 0;
}
};
template <>
class Object<Transform>::Priv : public PrivateObject {
_Scene* scene;
std::variant<
void*,
_GeometryAccelerationStructure*,
_InstanceAccelerationStructure*,
_Transform*
> child;
uint8_t* data;
size_t dataSize;
TransformType type;
OptixMotionOptions options;
OptixTraversableHandle handle;
uint32_t available : 1;
public:
OPTIXU_OPAQUE_BRIDGE(Transform);
Priv(_Scene* _scene) :
scene(_scene),
data(nullptr), dataSize(0),
handle(0),
available(false)
{
scene->addTransform(this);
options.numKeys = 2;
options.timeBegin = 0.0f;
options.timeEnd = 0.0f;
options.flags = OPTIX_MOTION_FLAG_NONE;
}
~Priv() {
if (data)
delete data;
data = nullptr;
scene->removeTransform(this);
getContext()->unregisterName(this);
}
const _Scene* getScene() const {
return scene;
}
_Context* getContext() const override {
return scene->getContext();
}
OPTIXU_DEFINE_THROW_RUNTIME_ERROR("Xfm");
_GeometryAccelerationStructure* getDescendantGAS() const;
void markDirty();
bool isReady() const {
return available;
}
OptixTraversableHandle getHandle() const {
throwRuntimeError(isReady(), "IAS %s: Traversable handle is not ready.", getName().c_str());
return handle;
}
};
template <>
class Object<Instance>::Priv : public PrivateObject {
_Scene* scene;
std::variant<
void*,
_GeometryAccelerationStructure*,
_InstanceAccelerationStructure*,
_Transform*
> child;
uint32_t matSetIndex;
uint32_t id;
uint32_t visibilityMask;
OptixInstanceFlags flags;
float instTransform[12];
public:
OPTIXU_OPAQUE_BRIDGE(Instance);
Priv(_Scene* _scene) :
scene(_scene)
{
matSetIndex = 0xFFFFFFFF;
id = 0;
visibilityMask = 0xFF;
flags = OPTIX_INSTANCE_FLAG_NONE;
const float identity[] = {
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
};
std::copy_n(identity, 12, instTransform);
}
~Priv() {
getContext()->unregisterName(this);
}
const _Scene* getScene() const {
return scene;
}
_Context* getContext() const override {
return scene->getContext();
}
OPTIXU_DEFINE_THROW_RUNTIME_ERROR("Inst");
void fillInstance(OptixInstance* instance) const;
void updateInstance(OptixInstance* instance) const;
bool isMotionAS() const;
bool isTransform() const;
};