Open3D (C++ API)  0.19.0
Loading...
Searching...
No Matches
Helper.h
Go to the documentation of this file.
1// ----------------------------------------------------------------------------
2// - Open3D: www.open3d.org -
3// ----------------------------------------------------------------------------
4// Copyright (c) 2018-2024 www.open3d.org
5// SPDX-License-Identifier: MIT
6// ----------------------------------------------------------------------------
7
10
11#pragma once
12
13#ifdef BUILD_CUDA_MODULE
14
15#include <cuda.h>
16#include <cuda_runtime.h>
17
20
21#endif // #ifdef BUILD_CUDA_MODULE
22
23namespace open3d {
24namespace ml {
25
26#ifdef BUILD_CUDA_MODULE
27
28#define OPEN3D_ML_CUDA_DRIVER_CHECK(err) \
29 __OPEN3D_ML_CUDA_DRIVER_CHECK(err, __FILE__, __LINE__)
30
31inline void __OPEN3D_ML_CUDA_DRIVER_CHECK(CUresult err,
32 const char *file,
33 const int line,
34 bool abort = true) {
35 if (err != CUDA_SUCCESS) {
36 const char *error_string;
37 CUresult err_get_string = cuGetErrorString(err, &error_string);
38
39 if (err_get_string == CUDA_SUCCESS) {
40 utility::LogError("{}:{} CUDA driver error: {}", file, line,
41 error_string);
42 } else {
43 utility::LogError("{}:{} CUDA driver error: UNKNOWN", file, line);
44 }
45 }
46}
47
48inline cudaStream_t GetDefaultStream() { return (cudaStream_t)0; }
49
50inline int GetDevice(cudaStream_t stream) {
51 if (stream == GetDefaultStream()) {
52 // Default device.
53 return 0;
54 }
55
56 // Remember current context.
57 CUcontext current_context;
58 OPEN3D_ML_CUDA_DRIVER_CHECK(cuCtxGetCurrent(&current_context));
59
60 // Switch to context of provided stream.
61 CUcontext context;
62 OPEN3D_ML_CUDA_DRIVER_CHECK(cuStreamGetCtx(stream, &context));
63 OPEN3D_ML_CUDA_DRIVER_CHECK(cuCtxSetCurrent(context));
64
65 // Query device of current context.
66 // This is the device of the provided stream.
67 CUdevice device;
68 OPEN3D_ML_CUDA_DRIVER_CHECK(cuCtxGetDevice(&device));
69
70 // Restore previous context.
71 OPEN3D_ML_CUDA_DRIVER_CHECK(cuCtxSetCurrent(current_context));
72
73 // CUdevice is a typedef to int.
74 return device;
75}
76
77class CUDAScopedDeviceStream {
78public:
79 explicit CUDAScopedDeviceStream(cudaStream_t stream)
80 : scoped_device_(GetDevice(stream)), scoped_stream_(stream) {}
81
82 CUDAScopedDeviceStream(CUDAScopedDeviceStream const &) = delete;
83 void operator=(CUDAScopedDeviceStream const &) = delete;
84
85private:
86 core::CUDAScopedDevice scoped_device_;
87 core::CUDAScopedStream scoped_stream_;
88};
89#endif
90
91} // namespace ml
92} // namespace open3d
Common CUDA utilities.
ImGuiContext * context
Definition Window.cpp:99
Definition PinholeCameraIntrinsic.cpp:16