Compare commits

...
62 Commits
Author SHA1 Message Date
Krzysztof Raszkowski 80284e3579 ci: add external linux workflow 2024-07-24 11:26:31 +02:00
Johannes Günther 85af292993 Merge branch 'release-3.2.x' 2024-07-22 21:06:49 +02:00
Johannes Günther 101ec57e2a Sync README, fix links and spelling 2024-07-22 18:20:02 +02:00
Johannes Günther f70252b0b7 Bump dependencies
- Embree (better error reporting)
- rkcommon
- benchmark
2024-07-22 18:20:02 +02:00
Johannes Günther a27184a0fb Backplate to ignore pixelFilter, closes #590 2024-07-22 16:14:17 +02:00
Johannes Günther f8f52b5eb7 Docu: more details on face-varying attributes, closes #591
Also reformat Mesh parameters into a wide table
2024-07-22 16:14:17 +02:00
Johannes Günther 24423d6c71 Fix Windows release
- Disable stripping on Win (noop, but sometimes destroys sigs)
- Some files get rebuilt after CMake re-config, thus they are not identical
- Build Embree with Clang GNU-style options as well
2024-07-22 16:14:17 +02:00
Johannes Günther 64380b59f7 ospExample tweaks
- Change defaults to better highlight OSPRay capabilities
- Enable denoiser per default if GPU is available
- Add 'normal' as displayable AOV
2024-07-18 16:48:49 +02:00
Johannes Günther c75f0837d5 Fix warnings 2024-07-16 15:35:48 +02:00
Johannes Günther 52ddc68964 Ensure postprocessors run on every renderFrame
Even if rendering is done (targetFrames or varianceThreshold reached) PP
still needs to run on renderFrame to reflect changes
2024-07-15 19:10:46 +02:00
Johannes Günther ac6f16f899 Record aux info at last smooth vertex of a specular-only path 2024-07-15 19:10:46 +02:00
Johannes Günther f995831810 Denoiser quality level, HIGH is using cleanAux and prefiltering 2024-07-15 19:07:32 +02:00
Johannes Günther 89dbb1930d Docu: combine TMO params into single table, reformat FB table 2024-07-15 19:07:32 +02:00
Johannes Günther 94d5fe82a2 Fix missing version info in some MPI DLLs 2024-07-15 19:07:32 +02:00
Johannes Günther 5b05343902 Denoise alpha-channel 2024-07-15 19:07:32 +02:00
Johannes Günther aa3774ea66 Use OIDN ErrorFunction callback 2024-07-15 19:07:32 +02:00
Alexander Stukowski c08f6ba981 Object handles: support equality/inequality comparison 2024-07-15 17:09:32 +02:00
Miroslaw Pawlowski 1df508397e Add MIP map cache to handle MIP maps when data object is shared among many texture objects, use last MIP map instead of avg 2024-07-15 10:48:52 +02:00
Johannes Günther be552bf968 Initialize shadowCone for ShadowCatcher 2024-07-09 10:35:13 +02:00
Johannes Günther 536dca3f7d Build system improvements for ISPC
- fix race conditions if multiple targets compile the same .ispc source
- support OSPRAY_STRICT_BUILD (show warnings, but not as-error)
- reporting and generated header files with relative paths
2024-07-09 10:35:13 +02:00
Johannes Günther b25063c4b6 Bump dependencies
- Use FetchContent to get Dear ImGui and STB sources, requires CMake v3.14
- Downgrade to glfw v3.3.10 (GUI was missing on Windows with v3.4)
2024-07-09 10:34:37 +02:00
Johannes Günther 501f991080 Use sincos, fix warnings 2024-07-09 09:33:02 +02:00
Johannes Günther f71a2d73e0 Need to build VKL from source when installing in single directory 2024-07-09 09:33:02 +02:00
Johannes Günther a04c1a3351 CI updates
- sanitizer
  - with clang
  - add MPI and Denoiser modules
  - split into three jobs
  - remove sanitize_ignore.txt (not needed anymore)
- fix initialization
- use RenderKit Arch docker image
- test Ubuntu 24.04 (no longer 18.04)
- test Rocky8 (no longer CentOs7)
- no force-delete
- fix multiple scan jobs
- properly handle Windows exit codes in build and release jobs
2024-07-09 09:33:02 +02:00
Miroslaw Pawlowski 347e2a804f StructShared uninitialized _ptr fix 2024-07-04 19:04:45 +02:00
Johannes Günther d3dec43d5c Cleanup DistributedRaycast logging 2024-07-01 12:53:53 +02:00
Isha SharmaandJohannes Günther 069b4d0cb2 MIP mapping, with ray cones
- MIP bias
- trilinear filtering
- regard stereo mode and sub-image region
- calc footprint width in postIntersect
- precompute tc transform scale; invariant to axis
- ray cones for textured shadows
- unit tests

MIP generation
- with ISPC (even in module GPU)
- refactor getTexel and Texture2D
- set texel functions and optimizations
- handle 1D textures
- explicit average (instead of smalles level)

Co-authored-by: Johannes Günther <johannes.guenther@intel.com>
2024-07-01 12:53:53 +02:00
Johannes Günther f6f2deb604 Fix hasAlpha 2024-06-28 22:29:01 +02:00
Johannes Günther 4bb2ea57b0 Kill paths which scatter to the wrong side of the surface due to shading normals 2024-06-27 17:03:20 +02:00
Johannes Günther da5f5b492e Replace firstBounceLightSamples parameter by flag limitIndirectLightSample 2024-06-19 16:50:02 +02:00
Johannes Günther 9b4f1703e0 Fix "targetFrames" with MPI
- remove FB::doAccumulation
- handle FrameID on host
- fix "accumulation" of the first sample
2024-06-19 16:50:02 +02:00
Johannes Günther be954607fb Fix GeometryLights 2024-06-19 16:50:02 +02:00
Johannes Günther 98922bb22b Improve Russian roulette 2024-06-19 16:50:02 +02:00
Johannes Günther e7fc1d09bb Fix MIS with different #NEE samples, and when evaluating virtual lights 2024-06-19 16:50:02 +02:00
Johannes Günther 6c01601125 Sampling improvements
- changed low-discrepancy sampler from Sobol with Cranley-Patterson
  rotation to shuffled and fast Owen-scrambled Sobol (Burley 2020)
- optimized implementation (support maximum of 64k samples)
- keep plain implementation for debugging
- enable screen-space blue noise via parameter `targetFrames` at the
  framebuffer (because the total number of samplers needs to be known in
  advance)
- splitting for NEE with >1 light samples
2024-06-19 16:50:02 +02:00
Sebastian Herholz 932775bd2f Adding support to use different numbers of NEE samples for the primary and all subsequent diffuse-glossy intersections 2024-06-19 16:50:02 +02:00
Miroslaw Pawlowski 57a2deea05 Replaced ISPCRT with a new DeviceRT layer for device memory allocations and kernel launching 2024-06-19 12:27:17 +02:00
Johannes Günther 0d9196bab6 Fix Mesh epsilons and self-shadowing of GeometryLights 2024-05-23 18:41:09 +02:00
Johannes Günther 1593e9094b PING for kernels 2024-05-23 18:41:09 +02:00
Johannes Günther 218c20c3ae Cleanup math constants
- move Halton and Sobol constants to global arrays (static for SYCL)
- remove pre-computed zorder
2024-05-23 18:41:09 +02:00
Johannes Günther 6ad92f0dee Bump dependencies 2024-05-23 18:41:09 +02:00
Johannes Günther 04a3802636 Fix name 2024-05-17 16:17:04 +02:00
Moushumi Maria e12ce01a37 CI test for MPI tutorials 2024-05-15 11:42:08 +02:00
Moushumi Maria 2da9e15570 Refactor emissive materials 2024-05-15 11:11:57 +02:00
Johannes Günther 9ff9446dd8 CI: bump to icx 2024.1; Win: driver 101.5445, disable tests with artifacts 2024-05-10 12:37:53 +02:00
Johannes Günther 26de7347fa Fix cut-out transparency in Principled material 2024-04-25 16:53:46 +02:00
Johannes Günther 54f060e660 Add support for fp16 textures 2024-04-17 11:16:24 +02:00
Johannes Günther 30e2aec785 Docu: add missing datatype enums, clarify sizeOf(OSP_BOOL)=1 2024-04-16 18:25:11 +02:00
Johannes Günther c67b8cab8b CI: handle workflow changes 2024-04-16 18:25:11 +02:00
Johannes Günther 94e37acbae Correctly calculate pixel_center 2024-04-16 18:25:11 +02:00
Miroslaw Pawlowski 3692dd553e Enable texturing tests on GPU 2024-04-12 19:51:31 +02:00
Miroslaw Pawlowski 45a2db8ab2 Kernel size reduction by PT debugging removal, converted varying IF to uniform in Principled material 2024-04-12 19:51:19 +02:00
Miroslaw Pawlowski 41b72afa62 Kernel size reduction by Textures improved inlining 2024-04-11 14:15:26 +02:00
Miroslaw Pawlowski bc1757b895 Kernel size reduction by Materierial/BSDF improved inlining 2024-04-11 14:13:56 +02:00
Moushumi Maria 34a2557bde Fix camera sample
Use pixel center to decide between eyes for stereo images.
2024-04-02 17:34:51 +02:00
Moushumi Maria 42d07e5e84 Enable sycl print 2024-03-15 11:42:40 +01:00
Moushumi Maria dc9354631d Add ref texture in material param 2024-03-08 08:46:22 +01:00
Moushumi Maria ffba3a9e24 Add support for downloading VKL binary in superbuild 2024-03-01 11:16:13 +01:00
Johannes Günther 609308b23d Fix name 2024-02-29 16:54:45 +01:00
Johannes Günther c9d546e8e0 Test Bezier Curve as well 2024-02-29 13:43:48 +01:00
Moushumi Maria 013160d171 Refactor curve interpolate function to eliminate duplicate code
Use specialization constants
2024-02-29 13:43:31 +01:00
Johannes Günther faeea0b71a Bump version, add OSX ARM download link 2024-02-23 12:50:07 +01:00
588 changed files with 8805 additions and 117856 deletions
-1
View File
@@ -20,7 +20,6 @@ jobs:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
force-delete: true # guarantees .gitattributes are respected in working dir
image: ubuntu:20.04
cmd: |
scripts/build/linux.sh -G Ninja -DBUILD_GLFW=OFF -DBUILD_OSPRAY_MODULE_MULTIDEVICE=ON
+3 -4
View File
@@ -19,10 +19,9 @@ jobs:
### BUILD JOBS ###
build-linux:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
force-delete: true # guarantees .gitattributes are respected in working dir
image: rockylinux:8.7
env-from-files: .github/workflows/dpcpp.env
cmd: |
@@ -82,7 +81,7 @@ jobs:
benchmark-dg2:
needs: build-linux
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
image: ubuntu:22.04
@@ -96,7 +95,7 @@ jobs:
benchmark-pvc:
needs: build-linux
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
image: ubuntu:22.04
+16 -20
View File
@@ -18,10 +18,9 @@ jobs:
### BUILD JOBS ###
ubu22-mpi-dpcpp-build:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
force-delete: true # guarantees .gitattributes are respected in working dir
image: ubuntu:22.04
env-from-files: .github/workflows/dpcpp.env
cmd: |
@@ -34,36 +33,33 @@ jobs:
ubu22-mpi-icx-build:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
force-delete: true # guarantees .gitattributes are respected in working dir
image: ubuntu:22.04
env-from-files: .github/workflows/icx-linux.env .github/workflows/gfx-ubuntu22.env # OIDN AOT needs ocloc
cmd: |
module load cmake/3.25.3
scripts/build/linux.sh -G Ninja -DBUILD_GLFW=OFF -DBUILD_GPU_SUPPORT=ON -DBUILD_OSPRAY_MODULE_MPI=ON -DBUILD_OSPRAY_MODULE_MULTIDEVICE=ON -DBUILD_EMBREE_FROM_SOURCE=ON -DBUILD_OIDN_FROM_SOURCE=ON
scripts/build/linux.sh -G Ninja -DBUILD_GLFW=OFF -DBUILD_GPU_SUPPORT=ON -DBUILD_OSPRAY_MODULE_MPI=ON -DBUILD_OSPRAY_MODULE_MULTIDEVICE=ON -DBUILD_EMBREE_FROM_SOURCE=ON -DBUILD_OPENVKL_FROM_SOURCE=ON -DBUILD_OIDN_FROM_SOURCE=ON
artifact-out: build-ubuntu2204-mpi-icx
artifact-path: build/install/ospray build/CMakeCache.txt build/*/build/CMakeCache.txt
suse-icx-build:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
force-delete: true # guarantees .gitattributes are respected in working dir
image: opensuse/leap:15.3
env-from-files: .github/workflows/icx-linux.env
cmd: |
module load cmake/3.25.3
scripts/build/linux.sh -DBUILD_GPU_SUPPORT=ON -DBUILD_EMBREE_FROM_SOURCE=ON
scripts/build/linux.sh -DBUILD_GPU_SUPPORT=ON -DBUILD_EMBREE_FROM_SOURCE=ON -DBUILD_OPENVKL_FROM_SOURCE=ON
rocky8-mpich-dpcpp-build:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
force-delete: true # guarantees .gitattributes are respected in working dir
image: rockylinux:8.7
image: rockylinux:8
env-from-files: .github/workflows/dpcpp.env
cmd: |
module load cmake/3.25.3
@@ -80,7 +76,7 @@ jobs:
dpcpp-dg2-ubu22-test:
needs: ubu22-mpi-dpcpp-build
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
timeout-minutes: 100
@@ -99,7 +95,7 @@ jobs:
dpcpp-pvc-ubu22-test:
needs: ubu22-mpi-dpcpp-build
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
timeout-minutes: 100
@@ -118,7 +114,7 @@ jobs:
mpi-dpcpp-pvc-ubu22-test:
needs: ubu22-mpi-dpcpp-build
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
timeout-minutes: 100
@@ -137,7 +133,7 @@ jobs:
multidev-dpcpp-pvc-ubu22-test:
needs: ubu22-mpi-dpcpp-build
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
timeout-minutes: 100
@@ -156,7 +152,7 @@ jobs:
icx-dg2-ubu22-test:
needs: ubu22-mpi-icx-build
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
timeout-minutes: 100
@@ -174,7 +170,7 @@ jobs:
mpi-icx-dg2-ubu22-test:
needs: ubu22-mpi-icx-build
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
timeout-minutes: 100
@@ -192,7 +188,7 @@ jobs:
icx-pvc-ubu22-test:
needs: ubu22-mpi-icx-build
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
timeout-minutes: 100
@@ -210,7 +206,7 @@ jobs:
mpi-icx-pvc-ubu22-test:
needs: ubu22-mpi-icx-build
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
timeout-minutes: 100
@@ -228,7 +224,7 @@ jobs:
multidev-icx-pvc-ubu22-test:
needs: ubu22-mpi-icx-build
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
timeout-minutes: 100
+100 -113
View File
@@ -21,8 +21,7 @@ jobs:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
force-delete: true # guarantees .gitattributes are respected in working dir
image: ospray/docker-images:arch
image: archlinux:latest
cmd: |
export CC=clang
export CXX=clang++
@@ -32,8 +31,7 @@ jobs:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
force-delete: true # guarantees .gitattributes are respected in working dir
image: ospray/docker-images:arch
image: archlinux:latest
cmd: |
export CC=clang
export CXX=clang++
@@ -43,65 +41,33 @@ jobs:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
force-delete: true # guarantees .gitattributes are respected in working dir
image: ospray/docker-images:arch
image: archlinux:latest
cmd: |
scripts/build/linux.sh -G Ninja -DBUILD_GLFW=OFF
build-arch-gcc-extras:
build-ubuntu2404-gcc-extras:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
force-delete: true # guarantees .gitattributes are respected in working dir
image: ospray/docker-images:arch
image: ubuntu:24.04
cmd: |
scripts/build/linux.sh -G Ninja -DBUILD_GLFW=OFF -DBUILD_OSPRAY_CI_EXTRAS=ON
build-centos7-gcc:
build-rocky8-gcc:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
force-delete: true # guarantees .gitattributes are respected in working dir
image: centos:7
image: rockylinux:8
cmd: |
scripts/build/linux.sh -DBUILD_EMBREE_FROM_SOURCE=ON -DBUILD_OIDN=OFF -DBUILD_ISA_AVX512=OFF -DTBB_VERSION=2021.9.0
artifact-out: build-centos7-gcc
scripts/build/linux.sh -DBUILD_EMBREE_FROM_SOURCE=ON -DBUILD_OPENVKL_FROM_SOURCE=ON -DBUILD_OIDN=OFF -DBUILD_ISA_AVX512=OFF -DTBB_VERSION=2021.9.0
artifact-out: build-rocky8-gcc
artifact-path: build/install/ospray build/CMakeCache.txt build/*/build/CMakeCache.txt
# TODO: Update to newer ICC compiler?
# build-centos7-icc:
# uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
# secrets: inherit
# with:
# force-delete: true # guarantees .gitattributes are respected in working dir
# image: centos:7-devenv
# cmd: |
# module load cmake
# module load intel
# export CC=icc
# export CXX=icpc
# scripts/build/linux.sh
# TODO: Update to newer ICC compiler?
# build-centos7-icc15:
# uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
# secrets: inherit
# with:
# force-delete: true # guarantees .gitattributes are respected in working dir
# image: centos:7-devenv
# cmd: |
# module load cmake
# module load intel/2015
# export CC=icc
# export CXX=icpc
# scripts/build/linux.sh
build-centos7-icx:
build-rocky8-icx:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
force-delete: true # guarantees .gitattributes are respected in working dir
image: centos:7
image: rockylinux:8
cmd: |
module load cmake
module load intel/2022.1
@@ -110,50 +76,46 @@ jobs:
export CXXFLAGS="-fhonor-infinities -fhonor-nans"
export CFLAGS=$CXXFLAGS
export LDFLAGS="-static-intel"
scripts/build/linux.sh -DBUILD_EMBREE_FROM_SOURCE=ON -DBUILD_OIDN=OFF -DTBB_VERSION=2021.9.0
artifact-out: build-centos7-icx
scripts/build/linux.sh -DBUILD_EMBREE_FROM_SOURCE=ON -DBUILD_OPENVKL_FROM_SOURCE=ON -DBUILD_OIDN=OFF -DTBB_VERSION=2021.9.0
artifact-out: build-rocky8-icx
artifact-path: build/install/ospray build/CMakeCache.txt build/*/build/CMakeCache.txt
build-centos7-mpi-impi:
build-rocky8-mpi-impi:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
force-delete: true # guarantees .gitattributes are respected in working dir
image: centos:7
image: rockylinux:8
cmd: |
module load cmake
module load impi/2021.6
scripts/build/linux.sh -DBUILD_EMBREE_FROM_SOURCE=ON -DBUILD_OIDN=OFF -DBUILD_OSPRAY_MODULE_MPI=ON -DBUILD_ISA_AVX512=OFF -DTBB_VERSION=2021.9.0
scripts/build/linux.sh -DBUILD_EMBREE_FROM_SOURCE=ON -DBUILD_OPENVKL_FROM_SOURCE=ON -DBUILD_OIDN=OFF -DBUILD_OSPRAY_MODULE_MPI=ON -DBUILD_ISA_AVX512=OFF -DTBB_VERSION=2021.9.0
build-centos7-mpi-mpich:
build-rocky8-mpi-mpich:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
force-delete: true # guarantees .gitattributes are respected in working dir
image: centos:7
image: rockylinux:8
cmd: |
module load cmake
module load mpi/mpich-x86_64
scripts/build/linux.sh -DBUILD_EMBREE_FROM_SOURCE=ON -DBUILD_OIDN=OFF -DBUILD_OSPRAY_MODULE_MPI=ON -DBUILD_ISA_AVX512=OFF -DTBB_VERSION=2021.9.0
artifact-out: build-centos7-mpi-mpich
scripts/build/linux.sh -DBUILD_EMBREE_FROM_SOURCE=ON -DBUILD_OPENVKL_FROM_SOURCE=ON -DBUILD_OIDN=OFF -DBUILD_OSPRAY_MODULE_MPI=ON -DBUILD_ISA_AVX512=OFF -DTBB_VERSION=2021.9.0
artifact-out: build-rocky8-mpi-mpich
artifact-path: build/install/ospray build/CMakeCache.txt build/*/build/CMakeCache.txt
build-centos7-mpi-openmpi:
build-rocky8-mpi-openmpi:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
force-delete: true # guarantees .gitattributes are respected in working dir
image: centos:7
image: rockylinux:8
cmd: |
module load cmake
module load mpi/openmpi-x86_64
scripts/build/linux.sh -DBUILD_EMBREE_FROM_SOURCE=ON -DBUILD_OIDN=OFF -DBUILD_OSPRAY_MODULE_MPI=ON -DBUILD_ISA_AVX512=OFF -DTBB_VERSION=2021.9.0
scripts/build/linux.sh -DBUILD_EMBREE_FROM_SOURCE=ON -DBUILD_OPENVKL_FROM_SOURCE=ON -DBUILD_OIDN=OFF -DBUILD_OSPRAY_MODULE_MPI=ON -DBUILD_ISA_AVX512=OFF -DTBB_VERSION=2021.9.0
build-centos8:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
force-delete: true # guarantees .gitattributes are respected in working dir
image: centos:8
cmd: |
scripts/build/linux.sh -G Ninja
@@ -164,7 +126,6 @@ jobs:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
force-delete: true # guarantees .gitattributes are respected in working dir
image: centos:8
cmd: |
module load mpi/mpich-x86_64
@@ -174,7 +135,6 @@ jobs:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
force-delete: true # guarantees .gitattributes are respected in working dir
image: centos:8
cmd: |
module load mpi/openmpi-x86_64
@@ -184,8 +144,7 @@ jobs:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
force-delete: true # guarantees .gitattributes are respected in working dir
image: rockylinux:8.7
image: rockylinux:8
cmd: |
module load cmake/3.15.2
module load mpi/mpich-x86_64
@@ -197,32 +156,31 @@ jobs:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
force-delete: true # guarantees .gitattributes are respected in working dir
image: ospray/docker-images:arch
image: archlinux:latest
cmd: |
export CC=clang
export CXX=clang++
export CFLAGS=-fsanitize=address
export CXXFLAGS=-fsanitize=address
export LDFLAGS=-fsanitize=address
scripts/build/linux.sh -G Ninja -DBUILD_GLFW=OFF -DCMAKE_BUILD_TYPE=Debug -DBUILD_OIDN=OFF
scripts/build/linux.sh -G Ninja -DBUILD_GLFW=OFF -DCMAKE_BUILD_TYPE=Debug -DBUILD_OSPRAY_MODULE_MPI=ON
artifact-out: build-linux-debug
artifact-path: build/install/ospray build/CMakeCache.txt build/*/build/CMakeCache.txt build/install/embree
build-ubuntu1804-gcc:
build-ubuntu2404-gcc:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
force-delete: true # guarantees .gitattributes are respected in working dir
image: ubuntu:18.04
image: ubuntu:24.04
cmd: |
scripts/build/linux.sh -G Ninja -DBUILD_GLFW=OFF
artifact-out: build-ubuntu1804-gcc
artifact-out: build-ubuntu2404-gcc
artifact-path: build/install/ospray build/CMakeCache.txt build/*/build/CMakeCache.txt
build-ubuntu2004-gcc:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
force-delete: true # guarantees .gitattributes are respected in working dir
image: ubuntu:20.04
cmd: |
scripts/build/linux.sh -G Ninja -DBUILD_GLFW=OFF -DBUILD_OSPRAY_MODULE_MULTIDEVICE=ON
@@ -233,7 +191,6 @@ jobs:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
force-delete: true # guarantees .gitattributes are respected in working dir
image: ubuntu:22.04
cmd: |
scripts/build/linux.sh -DBUILD_OSPRAY_MODULE_MPI=ON
@@ -246,61 +203,61 @@ jobs:
with:
runs-on: '[ "Linux", "ARM64" ]'
cmd: |
scripts/build/linux.sh -DBUILD_GLFW=OFF -DBUILD_TBB_FROM_SOURCE=ON -DBUILD_EMBREE_FROM_SOURCE=ON -DBUILD_OIDN_FROM_SOURCE=ON
scripts/build/linux.sh -DBUILD_GLFW=OFF -DBUILD_TBB_FROM_SOURCE=ON -DBUILD_EMBREE_FROM_SOURCE=ON -DBUILD_OPENVKL_FROM_SOURCE=ON -DBUILD_OIDN_FROM_SOURCE=ON
artifact-out: build-ubuntu2204-arm
artifact-path: build/install/ospray build/CMakeCache.txt build/*/build/CMakeCache.txt
### TEST JOBS ###
test-centos7-gcc-avx2:
needs: build-centos7-gcc
test-rocky8-gcc-avx2:
needs: build-rocky8-gcc
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
with:
image: centos:7
image: rockylinux:8
cmd: |
PATH="$GITHUB_WORKSPACE/build/install/ospray/bin:$PATH" scripts/tests/run_tests.sh "$GITHUB_WORKSPACE" AVX2
artifact-in: build-centos7-gcc
artifact-out: test-centos7-gcc-avx2
artifact-in: build-rocky8-gcc
artifact-out: test-rocky8-gcc-avx2
artifact-path: build_regression_tests/tests*.xml build_regression_tests/failed*
artifact-on-failure: true
test-centos7-gcc-mpi-mpich-avx2:
needs: build-centos7-mpi-mpich
test-rocky8-gcc-mpi-mpich-avx2:
needs: build-rocky8-mpi-mpich
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
with:
image: centos:7
image: rockylinux:8
cmd: |
module load cmake
module load mpi/mpich-x86_64
PATH="$GITHUB_WORKSPACE/build/install/ospray/bin:$PATH" scripts/tests/run_tests.sh "$GITHUB_WORKSPACE" AVX2 TEST_MPI
artifact-in: build-centos7-mpi-mpich
artifact-out: test-centos7-gcc-mpi-mpich-avx2
artifact-in: build-rocky8-mpi-mpich
artifact-out: test-rocky8-gcc-mpi-mpich-avx2
artifact-path: build_regression_tests/tests*.xml build_regression_tests/failed*
artifact-on-failure: true
test-centos7-icx-avx2:
needs: build-centos7-icx
test-rocky8-icx-avx2:
needs: build-rocky8-icx
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
with:
image: centos:7
image: rockylinux:8
runs-on: '"avx2"'
cmd: |
PATH="$GITHUB_WORKSPACE/build/install/ospray/bin:$PATH" scripts/tests/run_tests.sh "$GITHUB_WORKSPACE" AVX2
artifact-in: build-centos7-icx
artifact-out: test-centos7-icx-avx2
artifact-in: build-rocky8-icx
artifact-out: test-rocky8-icx-avx2
artifact-path: build_regression_tests/tests*.xml build_regression_tests/failed*
artifact-on-failure: true
test-centos7-icx-avx512skx:
needs: build-centos7-icx
test-rocky8-icx-avx512skx:
needs: build-rocky8-icx
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
with:
image: centos:7
image: rockylinux:8
runs-on: '"avx512"'
cmd: |
PATH="$GITHUB_WORKSPACE/build/install/ospray/bin:$PATH" scripts/tests/run_tests.sh "$GITHUB_WORKSPACE" AVX512SKX
artifact-in: build-centos7-icx
artifact-out: test-centos7-icx-avx512skx
artifact-in: build-rocky8-icx
artifact-out: test-rocky8-icx-avx512skx
artifact-path: build_regression_tests/tests*.xml build_regression_tests/failed*
artifact-on-failure: true
@@ -321,7 +278,7 @@ jobs:
needs: build-rocky8-oidn-mpi
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
with:
image: rockylinux:8.7
image: rockylinux:8
runs-on: '"avx512"'
cmd: |
module load cmake/3.15.2
@@ -334,28 +291,28 @@ jobs:
artifact-on-failure: true
test-find-ospray:
needs: build-centos7-gcc
needs: build-centos8
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
with:
image: centos:7
image: centos:8
cmd: |
module load cmake
mkdir buildtut
cd buildtut
cmake -D ospray_DIR=`echo $GITHUB_WORKSPACE/build/install/ospray/lib/cmake/ospray-*` ../apps/ospTutorial/ospTutorialFindospray
cmake --build .
artifact-in: build-centos7-gcc
artifact-in: build-centos8
test-ubuntu1804-gcc-avx512skx:
needs: build-ubuntu1804-gcc
test-ubuntu2404-gcc-avx512skx:
needs: build-ubuntu2404-gcc
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
with:
image: ubuntu:18.04
image: ubuntu:24.04
runs-on: '"avx512"'
cmd: |
PATH="$GITHUB_WORKSPACE/build/install/ospray/bin:$PATH" scripts/tests/run_tests.sh "$GITHUB_WORKSPACE" AVX512SKX
artifact-in: build-ubuntu1804-gcc
artifact-out: test-ubuntu1804-gcc-avx512skx
artifact-in: build-ubuntu2404-gcc
artifact-out: test-ubuntu2404-gcc-avx512skx
artifact-path: build_regression_tests/tests*.xml build_regression_tests/failed*
artifact-on-failure: true
@@ -387,7 +344,7 @@ jobs:
test-ubuntu2204-oidn-mpi-avx2-dg2:
needs: build-ubuntu2204-oidn-mpi
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
image: ubuntu:22.04
@@ -420,26 +377,56 @@ jobs:
#artifact-on-failure: true
test-tutorials:
needs: build-centos7-gcc
needs: build-centos8
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
with:
image: centos:7
image: centos:8
cmd: scripts/tests/run_tutorials.sh
artifact-in: build-centos7-gcc
artifact-in: build-centos8
sanitize-linux-debug:
test-mpi-tutorials:
needs: build-rocky8-oidn-mpi
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
with:
image: rockylinux:8
cmd: |
module load cmake/3.15.2
module load mpi/mpich-x86_64
scripts/tests/run_tutorials.sh TEST_MPI
artifact-in: build-rocky8-oidn-mpi
sanitize-cpu:
needs: build-linux-debug
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
with:
image: ospray/docker-images:arch
image: archlinux:latest
cmd: |
export LSAN_OPTIONS="suppressions=$GITHUB_WORKSPACE/scripts/tests/sanitize_ignore.txt"
export PATH=$GITHUB_WORKSPACE/build/install/ospray/bin:$PATH
export LD_LIBRARY_PATH=$GITHUB_WORKSPACE/build/install/embree/lib:$GITHUB_WORKSPACE/build/install/ospray/lib:$LD_LIBRARY_PATH
export TBB_ENABLE_SANITIZERS=1
export ASAN_OPTIONS=intercept_tls_get_addr=0 # WA https://github.com/google/sanitizers/issues/1322
scripts/tests/run_tests.sh $GITHUB_WORKSPACE AVX512SKX
artifact-in: build-linux-debug
sanitize-bench:
needs: build-linux-debug
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
with:
image: archlinux:latest
cmd: |
export PATH=$GITHUB_WORKSPACE/build/install/ospray/bin:$PATH
export LD_LIBRARY_PATH=$GITHUB_WORKSPACE/build/install/embree/lib:$GITHUB_WORKSPACE/build/install/ospray/lib:$LD_LIBRARY_PATH
export TBB_ENABLE_SANITIZERS=1
build/install/ospray/bin/ospBenchmark --benchmark_min_time=0s
artifact-in: build-linux-debug
sanitize-mpi:
needs: build-linux-debug
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
with:
image: archlinux:latest
cmd: |
export PATH=$GITHUB_WORKSPACE/build/install/ospray/bin:$PATH
export LD_LIBRARY_PATH=$GITHUB_WORKSPACE/build/install/embree/lib:$GITHUB_WORKSPACE/build/install/ospray/lib:$LD_LIBRARY_PATH
export TBB_ENABLE_SANITIZERS=1
OMPI_ALLOW_RUN_AS_ROOT=1 OMPI_ALLOW_RUN_AS_ROOT_CONFIRM=1 scripts/tests/run_tests.sh $GITHUB_WORKSPACE AVX512SKX SKIP_CPU TEST_MPI
artifact-in: build-linux-debug
+2 -5
View File
@@ -21,7 +21,6 @@ jobs:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/macos.yml@main
secrets: inherit
with:
force-delete: true # guarantees .gitattributes are respected in working dir
runs-on: '["x86_64", "build"]'
cmd: |
scripts/build/macosx.sh -DBUILD_OSPRAY_MODULE_MULTIDEVICE=ON
@@ -32,10 +31,9 @@ jobs:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/macos.yml@main
secrets: inherit
with:
force-delete: true # guarantees .gitattributes are respected in working dir
runs-on: '["arm", "build"]'
cmd: |
scripts/build/macosx.sh -DBUILD_TBB_FROM_SOURCE=ON
scripts/build/macosx.sh -DBUILD_TBB_FROM_SOURCE=ON -DBUILD_OPENVKL_FROM_SOURCE=ON
artifact-out: build-osx-arm
artifact-path: build/install/ospray build/CMakeCache.txt build/*/build/CMakeCache.txt
@@ -43,10 +41,9 @@ jobs:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/macos.yml@main
secrets: inherit
with:
force-delete: true # guarantees .gitattributes are respected in working dir
runs-on: '["arm", "build"]'
cmd: |
scripts/build/macosx.sh -DCMAKE_TOOLCHAIN_FILE=../scripts/superbuild/toolchains/macos-rosetta.cmake -DBUILD_TBB_FROM_SOURCE=ON -DBUILD_EMBREE_FROM_SOURCE=ON -DBUILD_OIDN_FROM_SOURCE=ON -DBUILD_ISA_AVX=OFF -DBUILD_ISA_AVX2=OFF -DBUILD_ISA_AVX512=OFF
scripts/build/macosx.sh -DCMAKE_TOOLCHAIN_FILE=../scripts/superbuild/toolchains/macos-rosetta.cmake -DBUILD_TBB_FROM_SOURCE=ON -DBUILD_EMBREE_FROM_SOURCE=ON -DBUILD_OPENVKL_FROM_SOURCE=ON -DBUILD_OIDN_FROM_SOURCE=ON -DBUILD_ISA_AVX=OFF -DBUILD_ISA_AVX2=OFF -DBUILD_ISA_AVX512=OFF
artifact-out: build-osx-x64
artifact-path: build/install/ospray build/CMakeCache.txt build/*/build/CMakeCache.txt
+7 -9
View File
@@ -18,10 +18,9 @@ jobs:
### BUILD JOBS ###
dpcpp-build:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/windows_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/windows.yml@main
secrets: inherit
with:
force-delete: true
runs-on: '["build", "mpi"]'
env-from-files: .github/workflows/dpcpp.env
cmd: |
@@ -34,10 +33,9 @@ jobs:
artifact-path: build/install/ospray build/CMakeCache.txt build/ospray/build/CMakeCache.txt
icx-build:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/windows_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/windows.yml@main
secrets: inherit
with:
force-delete: true
runs-on: '["build", "mpi"]'
env-from-files: .github/workflows/icx-windows.env
ocloc-version: 77a13ae6-6100-4ddc-b069-0086ff44730c/ocloc_win_101.5082
@@ -45,7 +43,7 @@ jobs:
# disable warnings which lead to excessively large log files
$env:CXXFLAGS = '-w'
$env:CFLAGS = '-w'
scripts\build\win.ps1 -G Ninja -DCMAKE_CXX_COMPILER=icx -DCMAKE_C_COMPILER=icx -DBUILD_GPU_SUPPORT=ON -DBUILD_OSPRAY_MODULE_MPI=ON -DBUILD_EMBREE_FROM_SOURCE=ON -DBUILD_OIDN_FROM_SOURCE=ON
scripts\build\win.ps1 -G Ninja -DCMAKE_CXX_COMPILER=icx -DCMAKE_C_COMPILER=icx -DBUILD_GPU_SUPPORT=ON -DBUILD_OSPRAY_MODULE_MPI=ON -DBUILD_EMBREE_FROM_SOURCE=ON -DBUILD_OPENVKL_FROM_SOURCE=ON -DBUILD_OIDN_FROM_SOURCE=ON
artifact-out: build-windows-icx
artifact-path: build/install/ospray build/CMakeCache.txt build/ospray/build/CMakeCache.txt
@@ -55,7 +53,7 @@ jobs:
dpcpp-test:
needs: dpcpp-build
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/windows_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/windows.yml@main
secrets: inherit
with:
timeout-minutes: 100
@@ -71,7 +69,7 @@ jobs:
mpi-dpcpp-test:
needs: dpcpp-build
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/windows_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/windows.yml@main
secrets: inherit
with:
timeout-minutes: 100
@@ -88,7 +86,7 @@ jobs:
icx-test:
needs: icx-build
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/windows_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/windows.yml@main
secrets: inherit
with:
timeout-minutes: 100
@@ -104,7 +102,7 @@ jobs:
mpi-icx-test:
needs: icx-build
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/windows_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/windows.yml@main
secrets: inherit
with:
timeout-minutes: 100
-3
View File
@@ -21,7 +21,6 @@ jobs:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/windows.yml@main
secrets: inherit
with:
force-delete: true # guarantees .gitattributes are respected in working dir
cmd: |
scripts\build\win.ps1 -G "Visual Studio 15 2017 Win64"
artifact-out: build-windows-msvc15
@@ -31,7 +30,6 @@ jobs:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/windows.yml@main
secrets: inherit
with:
force-delete: true # guarantees .gitattributes are respected in working dir
runs-on: '["build", "mpi"]'
cmd: |
scripts\build\win.ps1 -G "Visual Studio 16 2019" -DBUILD_OSPRAY_MODULE_MPI=ON -DBUILD_OSPRAY_MODULE_MULTIDEVICE=ON
@@ -42,7 +40,6 @@ jobs:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/windows.yml@main
secrets: inherit
with:
force-delete: true # guarantees .gitattributes are respected in working dir
cmd: |
scripts\build\win.ps1 -G "Visual Studio 17 2022"
artifact-out: build-windows-msvc17
+1 -1
View File
@@ -1 +1 @@
GFX_DRIVER_VERSION=windows-101.5186
GFX_DRIVER_VERSION=windows-101.5445
+1 -1
View File
@@ -1 +1 @@
DPCPP_VERSION=intel/2024.0
DPCPP_VERSION=intel/2024.1.0
+1 -1
View File
@@ -1 +1 @@
DPCPP_VERSION=icx/compiler_ppkg-rel/20240201
DPCPP_VERSION=oneAPI/compiler/2024.1
+162
View File
@@ -0,0 +1,162 @@
## Copyright 2024 Intel Corporation
## SPDX-License-Identifier: Apache-2.0
name: public CI Linux
on:
push:
pull_request:
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
jobs:
generate-baseline-images:
runs-on: ubuntu-latest
container:
image: ubuntu:22.04
steps:
- name: Install packages
run: |
echo "Installing build dependencies..."
apt update
apt upgrade -y
apt install -y build-essential cmake ninja-build libglfw3-dev libgl1-mesa-dev libxinerama-dev libxcursor-dev libxi-dev git
- name: Checkout Repository
uses: actions/checkout@v4
- name: Generate baseline images
run: |
git config --global --add safe.directory `pwd`
mkdir build_regression_tests
cd build_regression_tests
cmake ../test_image_data
cmake --build . --target ospray_test_data --parallel 8
- name: Upload baseline images
uses: actions/upload-artifact@v4
with:
name: baseline-images
path: |
build_regression_tests/regression_test_baseline/*.png
build_regression_tests/regression_test_baseline/*.exr
build_regression_tests/regression_test_baseline/*.jpg
compression-level: 1
build-rocky-8:
runs-on: ubuntu-latest
container:
image: rockylinux:8
steps:
- name: Install packages
run: |
echo "Installing build dependencies..."
dnf update -y
dnf install -y git cmake mesa-libGL-devel libXrandr-devel libXinerama-devel libXcursor-devel libXi-devel
dnf group install -y "Development Tools"
- name: Checkout Repository
uses: actions/checkout@v4
- name: Build
run: |
git config --global --add safe.directory `pwd`
mkdir build
cd build
cmake ../scripts/superbuild
cmake --build . --parallel 8
- name: Upload build
uses: actions/upload-artifact@v4
with:
name: build-rocky-8
path: build/install/ospray
test-rocky-8:
needs: [build-rocky-8, generate-baseline-images]
runs-on: ubuntu-latest
container:
image: rockylinux:8
steps:
- name: Download build
uses: actions/download-artifact@v4
with:
name: build-rocky-8
- name: Download baseline images
uses: actions/download-artifact@v4
with:
name: baseline-images
path: regression_test_baseline
- name: Run tests
run: |
chmod +x ./bin/*
./bin/ospTutorial
./bin/ospTestSuite
build-ubuntu-2204:
runs-on: ubuntu-latest
container:
image: ubuntu:22.04
steps:
- name: Install packages
run: |
echo "Installing build dependencies..."
apt update
apt upgrade -y
apt install -y build-essential cmake ninja-build libglfw3-dev libgl1-mesa-dev libxinerama-dev libxcursor-dev libxi-dev git
- name: Checkout Repository
uses: actions/checkout@v4
- name: Build
run: |
git config --global --add safe.directory `pwd`
mkdir build
cd build
cmake ../scripts/superbuild
cmake --build . --parallel 8
- name: Upload build
uses: actions/upload-artifact@v4
with:
name: build-ubuntu-2204
path: build/install/ospray
test-ubuntu-2204:
needs: [build-ubuntu-2204, generate-baseline-images]
runs-on: ubuntu-latest
container:
image: ubuntu:22.04
steps:
- name: Download build
uses: actions/download-artifact@v4
with:
name: build-ubuntu-2204
- name: Download baseline images
uses: actions/download-artifact@v4
with:
name: baseline-images
path: regression_test_baseline
- name: Run tests
run: |
chmod +x ./bin/*
./bin/ospTutorial
./bin/ospTestSuite
+41 -25
View File
@@ -25,7 +25,6 @@ jobs:
secrets: inherit
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
with:
force-delete: true
image: ospray/docker-images:docu
submodules: true
cmd: |
@@ -40,11 +39,10 @@ jobs:
release-linux:
needs: pdf
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
force-delete: true # guarantees .gitattributes are respected in working dir
image: rockylinux:8.7
image: rockylinux:8
env-from-files: .github/workflows/dpcpp.env
cmd: |
module load cmake/3.25.3
@@ -65,7 +63,7 @@ jobs:
runs-on: '[ "Linux", "ARM64" ]'
env-from-files: .github/workflows/dpcpp.env
cmd: |
scripts/release/linux.sh -DBUILD_GLFW=OFF -DBUILD_TBB_FROM_SOURCE=ON -DBUILD_EMBREE_FROM_SOURCE=ON -DBUILD_OIDN_FROM_SOURCE=ON
scripts/release/linux.sh -DBUILD_GLFW=OFF -DBUILD_TBB_FROM_SOURCE=ON -DBUILD_EMBREE_FROM_SOURCE=ON -DBUILD_OPENVKL_FROM_SOURCE=ON -DBUILD_OIDN_FROM_SOURCE=ON
cp build_release/*.gz $STORAGE_PATH/packages/renderkit/ || true
artifact-in: pdf
artifact-out: release-linux-arm
@@ -76,7 +74,6 @@ jobs:
secrets: inherit
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/macos.yml@main
with:
force-delete: true # guarantees .gitattributes are respected in working dir
runs-on: '["sign", "x86_64"]'
cmd: |
export CC=clang
@@ -92,10 +89,9 @@ jobs:
secrets: inherit
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/macos.yml@main
with:
force-delete: true # guarantees .gitattributes are respected in working dir
runs-on: '["arm", "build"]'
cmd: |
scripts/release/macosx.sh -DBUILD_TBB_FROM_SOURCE=ON
scripts/release/macosx.sh -DBUILD_TBB_FROM_SOURCE=ON -DBUILD_OPENVKL_FROM_SOURCE=ON
cp build_release/*.zip $STORAGE_PATH/packages/renderkit/ || true
artifact-in: pdf
artifact-out: release-osx-arm
@@ -103,10 +99,9 @@ jobs:
release-windows:
needs: pdf
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/windows_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/windows.yml@main
secrets: inherit
with:
force-delete: true # guarantees .gitattributes are respected in working dir
runs-on: '["build", "mpi"]'
env-from-files: .github/workflows/dpcpp.env
cmd: |
@@ -138,7 +133,7 @@ jobs:
prebuild: >
module load impi/latest &&
echo "Configure dependencies" &&
cmake -L -S scripts/superbuild -B build_deps -DBUILD_DEPENDENCIES_ONLY=ON -DBUILD_EMBREE_FROM_SOURCE=ON -DBUILD_OIDN_FROM_SOURCE=ON -DBUILD_OSPRAY_MODULE_MPI=ON -DINSTALL_IN_SEPARATE_DIRECTORIES=OFF -DBUILD_ISA_AVX512=OFF &&
cmake -L -S scripts/superbuild -B build_deps -DBUILD_DEPENDENCIES_ONLY=ON -DBUILD_EMBREE_FROM_SOURCE=ON -DBUILD_OPENVKL_FROM_SOURCE=ON -DBUILD_OIDN_FROM_SOURCE=ON -DBUILD_OSPRAY_MODULE_MPI=ON -DINSTALL_IN_SEPARATE_DIRECTORIES=OFF -DBUILD_ISA_AVX512=OFF &&
echo "Build dependencies" &&
cmake --build build_deps &&
INSTALL_DIR=$(pwd)/build_deps/install &&
@@ -173,6 +168,7 @@ jobs:
artifact-in-linux: release-linux-arm
artifact-in-macos: release-osx-arm
path: build_release/ospray-*
artifact-out-name: binary-analysis-arm
antivirus-scan:
needs:
@@ -199,6 +195,7 @@ jobs:
artifact-in-linux: release-linux-arm
artifact-in-macos: release-osx-arm
path: build_release/ospray-*
artifact-out-name: antivirus-scan-arm
### TEST JOBS ###
@@ -206,7 +203,7 @@ jobs:
needs: release-linux
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
with:
image: rockylinux:8.7
image: rockylinux:8
cmd: |
module load cmake/3.15.2
tar -xzf build_release/*.gz
@@ -218,7 +215,7 @@ jobs:
needs: release-linux
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
with:
image: rockylinux:8.7
image: rockylinux:8
cmd: |
module load cmake/3.15.2
module load mpi/mpich-x86_64
@@ -229,7 +226,7 @@ jobs:
test-ubuntu-oidnsycl:
needs: release-linux
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
timeout-minutes: 100
@@ -281,7 +278,7 @@ jobs:
test-ubuntu-dg2:
needs: release-linux
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
with:
timeout-minutes: 100
image: ubuntu:22.04
@@ -296,7 +293,7 @@ jobs:
test-ubuntu-mpi-dg2:
needs: release-linux
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
with:
timeout-minutes: 100
image: ubuntu:22.04
@@ -317,7 +314,7 @@ jobs:
test-ubuntu-pvc:
needs: release-linux
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
with:
timeout-minutes: 100
image: ubuntu:22.04
@@ -332,7 +329,7 @@ jobs:
test-ubuntu-mpi-pvc:
needs: release-linux
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
with:
timeout-minutes: 100
image: ubuntu:22.04
@@ -441,9 +438,7 @@ jobs:
$msiFile = (Get-ChildItem build_release/*.msi | Select-Object -Expand FullName)
Start-Process msiexec "/a $msiFile /qn TARGETDIR=$env:GITHUB_WORKSPACE" -Wait
if ($LastExitCode) { $exitCode++ }
# compare whether files in bin folder of archives are identical
Get-ChildItem "ospray-*\bin\*" | Select-Object -Expand Name | % { if ((Get-FileHash "Intel\OSPRay*\bin\$_").hash -ne (Get-FileHash "ospray-*\bin\$_").hash) { $exitCode++ } }
& $env:SIGN_FILE_WINDOWS -t build_release\*.msi (Get-ChildItem "Intel\OSPRay*\bin\*" | Select-Object -Expand FullName)
& $env:SIGN_FILE_WINDOWS -t build_release\*.msi (Get-ChildItem "Intel\OSPRay*\bin\*" | Select-Object -Expand FullName) (Get-ChildItem "ospray-*\bin\*" | Select-Object -Expand FullName)
if ($LastExitCode) { $exitCode++ }
exit $exitCode
artifact-in: release-windows
@@ -454,9 +449,13 @@ jobs:
with:
runs-on: '"avx512"'
cmd: |
$exitCode = 0 # keep job status to properly fail
Expand-Archive build_release/*.zip -DestinationPath .
if ($LastExitCode) { $exitCode++ }
$env:Path += ";" + (Get-ChildItem ospray-*\bin | Select-Object -Expand FullName)
scripts\tests\run_tests.ps1 $env:GITHUB_WORKSPACE AVX512SKX
if ($LastExitCode) { $exitCode++ }
exit $exitCode
artifact-in: release-windows
test-windows-mpi-cpu:
@@ -465,56 +464,73 @@ jobs:
with:
runs-on: '["avx512", "mpi"]'
cmd: |
$exitCode = 0 # keep job status to properly fail
Expand-Archive build_release/*.zip -DestinationPath .
if ($LastExitCode) { $exitCode++ }
$env:Path += ";" + (Get-ChildItem ospray-*\bin | Select-Object -Expand FullName)
scripts\tests\run_tests.ps1 $env:GITHUB_WORKSPACE AVX512SKX SKIP_CPU TEST_MPI
if ($LastExitCode) { $exitCode++ }
exit $exitCode
artifact-in: release-windows
test-windows-oidnsycl:
needs: release-windows
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/windows_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/windows.yml@main
secrets: inherit
with:
timeout-minutes: 100
runs-on: '"dg2"'
force-delete: true
env-from-files: .github/workflows/gfx-windows.env
cmd: |
$exitCode = 0 # keep job status to properly fail
Expand-Archive build_release/*.zip -DestinationPath .
if ($LastExitCode) { $exitCode++ }
$env:Path += ";" + (Get-ChildItem ospray-*\bin | Select-Object -Expand FullName)
$env:OIDN_DEFAULT_DEVICE="sycl"
$env:OIDN_VERBOSE="2"
md build_regression_tests
cd build_regression_tests
cmake -G Ninja -D OSPRAY_TEST_ISA=AVX2 $env:GITHUB_WORKSPACE\test_image_data
if ($LastExitCode) { $exitCode++ }
cmake --build . --config Release --target ospray_test_data
if ($LastExitCode) { $exitCode++ }
ospTestSuite.exe --baseline-dir=regression_test_baseline --gtest_filter="DenoiserOp.DenoiserOp"
if ($LastExitCode) { $exitCode++ }
exit $exitCode
artifact-in: release-windows
test-windows-dg2:
needs: release-windows
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/windows_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/windows.yml@main
with:
timeout-minutes: 100
runs-on: '"dg2"'
env-from-files: .github/workflows/gfx-windows.env
cmd: |
$exitCode = 0 # keep job status to properly fail
$env:Path += ";C:\Program Files (x86)\Intel\oneAPI\mpi\latest\libfabric\bin\utils;C:\Program Files (x86)\Intel\oneAPI\mpi\latest\libfabric\bin;C:\Program Files (x86)\Intel\oneAPI\mpi\latest\bin\release;C:\Program Files (x86)\Intel\oneAPI\mpi\latest\bin"
Expand-Archive build_release/*.zip -DestinationPath .
if ($LastExitCode) { $exitCode++ }
$env:Path += ";" + (Get-ChildItem ospray-*\bin | Select-Object -Expand FullName)
scripts\tests\run_gpu_tests.ps1 $env:GITHUB_WORKSPACE
if ($LastExitCode) { $exitCode++ }
exit $exitCode
artifact-in: release-windows
test-windows-mpi-dg2:
needs: release-windows
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/windows_gpu.yml@main
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/windows.yml@main
with:
timeout-minutes: 100
runs-on: '"dg2"' # FIXME: mpi
env-from-files: .github/workflows/gfx-windows.env
cmd: |
$exitCode = 0 # keep job status to properly fail
$env:Path += ";C:\Program Files (x86)\Intel\oneAPI\mpi\latest\libfabric\bin\utils;C:\Program Files (x86)\Intel\oneAPI\mpi\latest\libfabric\bin;C:\Program Files (x86)\Intel\oneAPI\mpi\latest\bin\release;C:\Program Files (x86)\Intel\oneAPI\mpi\latest\bin"
Expand-Archive build_release/*.zip -DestinationPath .
if ($LastExitCode) { $exitCode++ }
$env:Path += ";" + (Get-ChildItem ospray-*\bin | Select-Object -Expand FullName)
scripts\tests\run_gpu_tests.ps1 $env:GITHUB_WORKSPACE SKIP_GPU TEST_MPI
if ($LastExitCode) { $exitCode++ }
exit $exitCode
artifact-in: release-windows
+6 -6
View File
@@ -22,21 +22,21 @@ jobs:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
image: ospray/docker-images:arch
image: archlinux:latest
cmd: |
export CC=clang
export CXX=clang++
scripts/build/linux.sh -G Ninja -DBUILD_GLFW=OFF -DBUILD_OSPRAY_CI_EXTRAS=ON -DBUILD_ISPCRT_FROM_SOURCE=ON -DISPCRT_BRANCH=devel -DBUILD_EMBREE_FROM_SOURCE=ON -DEMBREE_VERSION=devel -DBUILD_OIDN_FROM_SOURCE=ON -DOIDN_VERSION=devel -DOPENVKL_VERSION=devel -DRKCOMMON_VERSION=devel
scripts/build/linux.sh -G Ninja -DBUILD_GLFW=OFF -DBUILD_OSPRAY_CI_EXTRAS=ON -DBUILD_EMBREE_FROM_SOURCE=ON -DBUILD_OPENVKL_FROM_SOURCE=ON -DEMBREE_VERSION=devel -DBUILD_OIDN_FROM_SOURCE=ON -DOIDN_VERSION=devel -DOPENVKL_VERSION=devel -DRKCOMMON_VERSION=devel
build-linux-debug-all:
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
secrets: inherit
with:
image: ospray/docker-images:arch
image: archlinux:latest
cmd: |
export CC=clang
export CXX=clang++
scripts/build/linux.sh -G Ninja -DCMAKE_BUILD_TYPE=Debug -DDEPENDENCIES_BUILD_TYPE=Debug -DBUILD_GLFW=OFF -DBUILD_OSPRAY_CI_EXTRAS=ON -DBUILD_ISPCRT_FROM_SOURCE=ON -DBUILD_EMBREE_FROM_SOURCE=ON -DBUILD_OIDN=OFF -DBUILD_OSPRAY_MODULE_MPI=ON -DBUILD_OSPRAY_MODULE_MULTIDEVICE=ON
scripts/build/linux.sh -G Ninja -DCMAKE_BUILD_TYPE=Debug -DDEPENDENCIES_BUILD_TYPE=Debug -DBUILD_GLFW=OFF -DBUILD_OSPRAY_CI_EXTRAS=ON -DBUILD_EMBREE_FROM_SOURCE=ON -DBUILD_OPENVKL_FROM_SOURCE=ON -DBUILD_OIDN=OFF -DBUILD_OSPRAY_MODULE_MPI=ON -DBUILD_OSPRAY_MODULE_MULTIDEVICE=ON
artifact-out: build-linux-debug-all
artifact-path: build/install/ospray build/CMakeCache.txt build/*/build/CMakeCache.txt
@@ -56,7 +56,7 @@ jobs:
with:
runs-on: '["build", "NAS", "mpi"]'
cmd: |
scripts\build\win.ps1 -G "Visual Studio 17 2022" -buildType Debug -DBUILD_OSPRAY_CI_EXTRAS=ON -DBUILD_ISPCRT_FROM_SOURCE=ON -DBUILD_EMBREE_FROM_SOURCE=ON -DBUILD_ISA_AVX512=OFF -DBUILD_OIDN=OFF -DBUILD_OSPRAY_MODULE_MPI=ON -DBUILD_OSPRAY_MODULE_MULTIDEVICE=ON
scripts\build\win.ps1 -G "Visual Studio 17 2022" -buildType Debug -DBUILD_OSPRAY_CI_EXTRAS=ON -DBUILD_EMBREE_FROM_SOURCE=ON -DBUILD_OPENVKL_FROM_SOURCE=ON -DBUILD_ISA_AVX512=OFF -DBUILD_OIDN=OFF -DBUILD_OSPRAY_MODULE_MPI=ON -DBUILD_OSPRAY_MODULE_MULTIDEVICE=ON
artifact-out: build-windows-debug-all
artifact-path: build/install/ospray build/CMakeCache.txt build/ospray/build/CMakeCache.txt
@@ -73,7 +73,7 @@ jobs:
needs: build-linux-debug-all
uses: intel-innersource/libraries.devops.renderkit.workflows/.github/workflows/docker.yml@main
with:
image: ospray/docker-images:arch
image: archlinux:latest
runs-on: '"avx512"'
cmd: |
PATH="$GITHUB_WORKSPACE/build/install/ospray/bin:$PATH" scripts/tests/run_tests.sh "$GITHUB_WORKSPACE" AVX512SKX
+50 -5
View File
@@ -1,6 +1,45 @@
Version History
---------------
### Changes in v3.2.0:
- Sampling improvements:
- Better performance (lower rendering time and faster convergence)
- More pleasing blue noise enabled when the total number of frames
to be accumulated is known in advance and set as the
`targetFrames` parameter at the framebuffer
- Note a maximum of 64k samples is supported
- Improved `denoiser` image operation:
- User-controlled quality levels via parameter `quality`
- Optionally denoise alpha channel as well, enabled via
parameter `denoiseAlpha`
- Support half-precision (16\ bit float) texture formats
`OSP_TEXTURE_[RGBA16F|RGB16F|RA16F|R16F]` and two-channel 32\ bit
float textures `OSP_TEXTURE_RA32F`
- New parameter `limitIndirectLightSamples` for the `pathtracer` which
limits the number of light samples after the first non-specular
(i.e., diffuse and glossy) bounce to at most one
- Implement MIP Mapping for better texture filtering. If the
additional memory per texture needed cannot be spared, applications
can disable the generation of MIP maps with device parameter
`disableMipMapGeneration`
- The backplate (background texture) is now always sampled at the pixel
center and thus not blurred by the pixel filter anymore
- Avoid color bleeding across eye-subimages when stereo rendering
- Superbuild uses binary packages of Open VKL
- Removed Intel ISPCRT dependency (ISPC compiler is still needed):
- oneAPI Level Zero Loader is no longer necessary
- `zeContext` and `zeDevice`device parameters are no longer supported
- `ispcrtContext` and `ispcrtDevice`device parameters are no longer
supported
- Clarify the size of `OSP_BOOL` to be 1 byte
- Fix artifacts occasionally appearing with `gpu` device
- The new minimum versions of dependencies:
- Embree v4.3.3 (better error reporting)
- Open Image Denoise v2.3 (better image quality with `HIGH`
quality mode, added `FAST` quality mode)
- rkcommon v1.14.0
### Changes in v3.1.0:
- Principled and Luminous materials support emissive textures
@@ -39,9 +78,11 @@ Version History
- Clipping
- Motion blur
- Subdivision surfaces
- Progress reporting via `ospGetProgress` or canceling the frame via `ospCancel`
- Progress reporting via `ospGetProgress` or canceling the frame
via `ospCancel`
- Picking via `ospPick`
- Adaptive accumulation via `OSP_FB_VARIANCE` and `varianceThreshold`
- Adaptive accumulation via `OSP_FB_VARIANCE` and
`varianceThreshold`
- Framebuffer channels `OSP_FB_ID_*` (id buffers)
- Experimental support for shared device-only data, works only for
`structuredRegular` volume
@@ -88,10 +129,14 @@ Version History
- error callback signatures without user pointer
- first argument of `ospNewMaterial`
- module name `ispc`; use `cpu`
- `volume` texture and `isosurface` geometry: `volumetricModel`; use `OSPVolume volume`
- `volume` texture and `isosurface` geometry:
`volumetricModel`; use `OSPVolume volume`
- Transfer function `vec2f valueRange`; use `box1f value`
- `hdri` and `sun-sky` lights: `intensityQuantity` `OSP_INTENSITY_QUANTITY_RADIANCE`
- `spot` light with `intensityDistribution`: `intensityQuantity` other than `OSP_INTENSITY_QUANTITY_SCALE`
- `hdri` and `sun-sky` lights: `intensityQuantity`
`OSP_INTENSITY_QUANTITY_RADIANCE`
- `spot` light with `intensityDistribution`:
`intensityQuantity` other than
`OSP_INTENSITY_QUANTITY_SCALE`
### Changes in v2.12.0:
+3 -1
View File
@@ -1,7 +1,7 @@
## Copyright 2009 Intel Corporation
## SPDX-License-Identifier: Apache-2.0
cmake_minimum_required(VERSION 3.1)
cmake_minimum_required(VERSION 3.8)
##############################################################
# Language setup
@@ -20,6 +20,7 @@ set(CMAKE_C_EXTENSIONS OFF)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
set(CMAKE_INSTALL_MESSAGE LAZY)
##############################################################
# Establish project
@@ -38,6 +39,7 @@ list(APPEND CMAKE_MODULE_PATH
${PROJECT_SOURCE_DIR}/cmake/compiler
)
include(ispc)
include(ospray_macros)
include(ospray_options)
include(package)
+125 -92
View File
@@ -1,7 +1,7 @@
OSPRay
======
This is release v3.1.0 of Intel® OSPRay. For changes and new features
This is release v3.2.0 of Intel® OSPRay. For changes and new features
see the [changelog](CHANGELOG.md). Visit http://www.ospray.org for more
information.
@@ -11,8 +11,8 @@ OSPRay Overview
Intel® OSPRay is an **o**pen source, **s**calable, and **p**ortable
**ray** tracing engine for high-performance, high-fidelity visualization
on Intel Architecture CPUs, Intel Xe GPUs, and ARM64 CPUs. OSPRay is
part of the [Intel oneAPI Rendering
Toolkit](https://software.intel.com/en-us/rendering-framework) and is
part of the [Intel Rendering Toolkit (Render
Kit)](https://software.intel.com/en-us/rendering-framework) and is
released under the permissive [Apache 2.0
license](http://www.apache.org/licenses/LICENSE-2.0).
@@ -84,21 +84,22 @@ before you can build OSPRay you need the following prerequisites:
Compiler (ISPC)](http://ispc.github.io), version 1.23.0 or later.
Please obtain a release of ISPC from the [ISPC downloads
page](https://ispc.github.io/downloads.html). If ISPC is not found by
CMake its location can be hinted with the variable `ispcrt_DIR`.
CMake its location can be hinted with the variable `ISPC_EXECUTABLE`.
- OSPRay builds on top of the [Intel oneAPI Rendering Toolkit common
library (rkcommon)](https://www.github.com/ospray/rkcommon). The
library provides abstractions for tasking, aligned memory allocation,
vector math types, among others. For users who also need to build
rkcommon, we recommend the default the Intel [Threading Building
Blocks (TBB)](https://www.threadingbuildingblocks.org/) as tasking
system for performance and flexibility reasons. TBB must be built from
source when targeting ARM CPUs, or can be built from source as part of
the [superbuild](#cmake-superbuild). Alternatively you can set CMake
variable `RKCOMMON_TASKING_SYSTEM` to `OpenMP` or `Internal`.
- OSPRay builds on top of the [Intel Rendering Toolkit (Render Kit)
common library (rkcommon)](https://www.github.com/ospray/rkcommon).
The library provides abstractions for tasking, aligned memory
allocation, vector math types, among others. For users who also need
to build rkcommon, we recommend the default the Intel [Threading
Building Blocks (TBB)](https://www.threadingbuildingblocks.org/) as
tasking system for performance and flexibility reasons. TBB must be
built from source when targeting ARM CPUs, or can be built from source
as part of the [superbuild](#cmake-superbuild). Alternatively you can
set CMake variable `RKCOMMON_TASKING_SYSTEM` to `OpenMP` or
`Internal`.
- OSPRay also heavily uses Intel [Embree](https://www.embree.org/),
installing version 4.3.1 or newer is required. If Embree is not found
installing version 4.3.3 or newer is required. If Embree is not found
by CMake its location can be hinted with the variable `embree_DIR`.
- OSPRay supports volume rendering (enabled by default via
@@ -110,7 +111,7 @@ before you can build OSPRay you need the following prerequisites:
- OSPRay also provides an optional module implementing the `denoiser`
image operation, which is enabled by `OSPRAY_MODULE_DENOISER`. This
module requires Intel [Open Image
Denoise](https://openimagedenoise.github.io/) in version 2.2.0 or
Denoise](https://openimagedenoise.github.io/) in version 2.3.0 or
newer. You may need to hint the location of the library with the CMake
variable `OpenImageDenoise_DIR`.
@@ -163,16 +164,6 @@ To build OSPRay’s GPU module you need
or the latest [Intel oneAPI DPC++/C++
Compiler](https://www.intel.com/content/www/us/en/developer/articles/tool/oneapi-standalone-components.html#dpcpp-cpp)
- a recent [CMake](http://www.cmake.org), version 3.25.3 or higher
- the [oneAPI Level Zero Loader
v1.12.0](https://github.com/oneapi-src/level-zero/releases/tag/v1.12.0)
development packages
- On Linux Ubuntu 22.04 there are prebuilt packages available for
this: `level-zero-devel` and `level-zero`
- Other Linux distributions require building these packages from
source
- On Windows, you can use the single package
`level-zero_<version>_win-sdk`; note you will need to set the
environment variable `LEVEL_ZERO_ROOT` to the location of the SDK
CMake Superbuild
----------------
@@ -191,7 +182,7 @@ cmake [<OSPRAY_SOURCE_DIR>/scripts/superbuild]
cmake --build .
```
On Windows make sure to select a 64bit generator, e.g.
On Windows make sure to select a 64 bit generator, e.g.
``` sh
cmake -G "Visual Studio 17 2022" [<OSPRAY_SOURCE_DIR>/scripts/superbuild]
@@ -517,15 +508,16 @@ exactly the same as `ospSetParam`, which is documented below in the
[parameters](#parameters) section. The following parameters can be set
on all devices:
| Type | Name | Description |
|:-------|:------------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| int | numThreads | number of threads which OSPRay should use |
| uint | logLevel | logging level; valid values (in order of severity) are `OSP_LOG_NONE`, `OSP_LOG_ERROR`, `OSP_LOG_WARNING`, `OSP_LOG_INFO`, and `OSP_LOG_DEBUG` |
| string | logOutput | convenience for setting where status messages go; valid values are `cerr` and `cout` |
| string | errorOutput | convenience for setting where error messages go; valid values are `cerr` and `cout` |
| bool | debug | set debug mode; equivalent to `logLevel=debug` and `numThreads=1` |
| bool | warnAsError | send `warning` and `error` messages through the error callback, otherwise send `warning` messages through the message callback; must have sufficient `logLevel` to enable warnings |
| bool | setAffinity | bind software threads to hardware threads if set to 1; 0 disables binding omitting the parameter will let OSPRay choose |
| Type | Name | Description |
|:-------|:------------------------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| int | numThreads | number of threads which OSPRay should use |
| bool | disableMipMapGeneration | disable the default generation of MIP maps for textures (e.g., to save the additional memory needed) |
| uint | logLevel | logging level; valid values (in order of severity) are `OSP_LOG_NONE`, `OSP_LOG_ERROR`, `OSP_LOG_WARNING`, `OSP_LOG_INFO`, and `OSP_LOG_DEBUG` |
| string | logOutput | convenience for setting where status messages go; valid values are `cerr` and `cout` |
| string | errorOutput | convenience for setting where error messages go; valid values are `cerr` and `cout` |
| bool | debug | set debug mode; equivalent to `logLevel=debug` and `numThreads=1` |
| bool | warnAsError | send `warning` and `error` messages through the error callback, otherwise send `warning` messages through the message callback; must have sufficient `logLevel` to enable warnings |
| bool | setAffinity | bind software threads to hardware threads if set to 1; 0 disables binding omitting the parameter will let OSPRay choose |
Parameters shared by all devices.
@@ -882,16 +874,22 @@ below.
| OSP_OBJECT | generic object reference |
| OSP_CAMERA | camera object reference |
| OSP_FRAMEBUFFER | framebuffer object reference |
| OSP_FUTURE | future object reference |
| OSP_LIGHT | light object reference |
| OSP_MATERIAL | material object reference |
| OSP_TEXTURE | texture object reference |
| OSP_RENDERER | renderer object reference |
| OSP_WORLD | world object reference |
| OSP_GROUP | group object reference |
| OSP_INSTANCE | instance object reference |
| OSP_GEOMETRY | geometry object reference |
| OSP_GEOMETRIC_MODEL | geometric model object reference |
| OSP_VOLUME | volume object reference |
| OSP_VOLUMETRIC_MODEL | volumetric model object reference |
| OSP_TRANSFER_FUNCTION | transfer function object reference |
| OSP_IMAGE_OPERATION | image operation object reference |
| OSP_STRING | C-style zero-terminated character string |
| OSP_BOOL | 8 bit boolean |
| OSP_CHAR, OSP_VEC\[234\]C | 8 bit signed character scalar and \[234\]-element vector |
| OSP_UCHAR, OSP_VEC\[234\]UC | 8 bit unsigned character scalar and \[234\]-element vector |
| OSP_SHORT, OSP_VEC\[234\]S | 16 bit unsigned integer scalar and \[234\]-element vector |
@@ -1181,7 +1179,7 @@ the `cell.type` parameter must be omitted).
| bool | indexPrefixed | false | indicates that the `index` array is compatible to VTK, where the indices of each cell are prefixed with the number of vertices |
| uint32\[\] / uint64\[\] | cell.index | | [data](#data) array of locations (into the index array), specifying the first index of each cell |
| float\[\] | cell.data | | [data](#data) array of cell data values to be sampled |
| uint8\[\] | cell.type | | [data](#data) array of cell types (VTK compatible), only set if `indexPrefixed = false` false. Supported types are: |
| uint8\[\] | cell.type | | [data](#data) array of cell types (VTK compatible), only set if `indexPrefixed = false`. Supported types are: |
| | | | `OSP_TETRAHEDRON` |
| | | | `OSP_HEXAHEDRON` |
| | | | `OSP_WEDGE` |
@@ -1403,6 +1401,17 @@ i.e., each four subsequent vertices form one quad. If the size of the
`vertex.position` array is not a multiple of three for triangles or four
for quads, the remainder vertices are ignored.
Face-varying attributes (`normal`, `motion.normal`, `color`, `texcoord`)
map unique values to each vertex of a primitive/face (triangle or quad),
thus attributes can be different for the same vertex that is shared by
multiple primitives. Essentially, face-varying attributes are a
‘attribute soup’ and behave similar to the implicit index, the size of
the array must be at least three times the number of triangles or four
times the number of quads, respectively. Face-varying attributes take
precedence over the respective vertex attributes (`vertex.normal`,
`motion.vertex.normal`, `vertex.color`, `vertex.texcoord`) when both
arrays of the same attribute are present.
### Subdivision
A mesh consisting of subdivision surfaces, created by specifying a
@@ -2376,7 +2385,7 @@ because it is always `OSP_INTENSITY_QUANTITY_RADIANCE`).
|:------|:-------------|--------:|:----------------------------------------|
| vec3f | color | white | color of the emitted light (linear RGB) |
| float | intensity | 1 | intensity of the light (a factor) |
| float | transparency | 1 | material transparency |
| float | transparency | 0 | material transparency |
Parameters accepted by the Luminous material.
@@ -2430,14 +2439,19 @@ The supported texture formats for `texture2d` are:
| OSP_TEXTURE_RGBA8 | 8 bit \[0–255\] linear components red, green, blue, alpha |
| OSP_TEXTURE_SRGBA | 8 bit sRGB gamma encoded color components, and linear alpha |
| OSP_TEXTURE_RGBA32F | 32 bit float components red, green, blue, alpha |
| OSP_TEXTURE_RGBA16F | 16 bit float components red, green, blue, alpha |
| OSP_TEXTURE_RGB8 | 8 bit \[0–255\] linear components red, green, blue |
| OSP_TEXTURE_SRGB | 8 bit sRGB gamma encoded components red, green, blue |
| OSP_TEXTURE_RGB32F | 32 bit float components red, green, blue |
| OSP_TEXTURE_RGB16F | 16 bit float components red, green, blue |
| OSP_TEXTURE_R8 | 8 bit \[0–255\] linear single component red |
| OSP_TEXTURE_RA8 | 8 bit \[0–255\] linear two components red, alpha |
| OSP_TEXTURE_L8 | 8 bit \[0–255\] gamma encoded luminance (replicated into red, green, blue) |
| OSP_TEXTURE_LA8 | 8 bit \[0–255\] gamma encoded luminance, and linear alpha |
| OSP_TEXTURE_RA32F | 32 bit float two component red, alpha |
| OSP_TEXTURE_R32F | 32 bit float single component red |
| OSP_TEXTURE_RA16F | 16 bit float two component red, alpha |
| OSP_TEXTURE_R16F | 16 bit float single component red |
| OSP_TEXTURE_RGBA16 | 16 bit \[0–65535\] linear components red, green, blue, alpha |
| OSP_TEXTURE_RGB16 | 16 bit \[0–65535\] linear components red, green, blue |
| OSP_TEXTURE_RA16 | 16 bit \[0–65535\] linear two components red, alpha |
@@ -2834,7 +2848,7 @@ General parameters of all renderers are
| Type | Name | Default | Description |
|:----------------------|:------------------|------------------------:|:--------------------------------------------------------------------------------------------------------------------------------------------|
| int | pixelSamples | 1 | samples per pixel |
| int | pixelSamples | 1 | samples per pixel, best results when a power of 2 |
| int | maxPathLength | 20 | maximum ray recursion depth |
| float | minContribution | 0.001 | sample contributions below this value will be neglected to speedup rendering |
| float | varianceThreshold | 0 | threshold for adaptive accumulation |
@@ -2843,6 +2857,7 @@ General parameters of all renderers are
| OSPTexture | map_maxDepth | | optional screen-sized float [texture](#texture) with maximum far distance per pixel (use texture type `texture2d`) |
| OSPMaterial\[\] | material | | optional [data](#data) array of [materials](#materials) which can be indexed by a [GeometricModel](#geometricmodels)’s `material` parameter |
| uint | pixelFilter | `OSP_PIXELFILTER_GAUSS` | `OSPPixelFilterType` to select the pixel filter used by the renderer for antialiasing. Possible pixel filters are listed below. |
| float | mipMapBias | 0 | bias for texture MIP-mapping, balancing between sharpness/aliasing and blurriness due to prefiltering |
Parameters understood by all renderers.
@@ -2855,7 +2870,8 @@ variance below the `varianceThreshold`. This feature requires a
Per default the background of the rendered image will be transparent
black, i.e., the alpha channel holds the opacity of the rendered
objects. This eases transparency-aware blending of the image with an
arbitrary background image by the application. The parameter
arbitrary background image by the application (via
$ospray.rgb + appBackground.rgb⋅(1-ospray.alpha)$). The parameter
`backgroundColor` or `map_backplate` can be used to already blend with a
constant background color or backplate texture, respectively, (and
alpha) during rendering.
@@ -2869,7 +2885,7 @@ distance of primary rays, thus objects of other renderers can hide
objects rendered by OSPRay.
OSPRay supports antialiasing in image space by using pixel filters,
which are centered around the center of a pixel. The size $w×w$ of the
which are aligned around the center of a pixel. The size $w×w$ of the
filter depends on the selected filter type. The types of supported pixel
filters are defined by the `OSPPixelFilterType` enum and can be set
using the `pixelFilter` parameter.
@@ -2884,6 +2900,15 @@ using the `pixelFilter` parameter.
Pixel filter types supported by OSPRay for antialiasing in image space.
OSPRay also antialiases textures with prefiltering and MIP-mapping,
which can be adjusted with parameter `mipMapBias`. For final frame
rendering with a high number of `pixelSamples` or accumulated frames
`mipMapBias` can be lowered (e.g., set to -0.5 or -2) to result in
sharper textures which are essentially anisotropically filtered.
Conversely, for preview rendering with just a single sample per pixel a
higher `mipMapBias` of 1 or 2 can reduce texture aliasing and increase
rendering speed.
### SciVis Renderer
The SciVis renderer is a fast ray tracer for scientific visualization
@@ -2935,13 +2960,14 @@ realistic materials. This renderer is created by passing the type string
parameters](#renderer) understood by all renderers the path tracer
supports the following special parameters:
| Type | Name | Default | Description |
|:------|:---------------------|--------:|:------------------------------------------------------------------------------------------|
| int | lightSamples | all | number of random light samples per path vertex, per default all light sources are sampled |
| int | roulettePathLength | 5 | ray recursion depth at which to start Russian roulette termination |
| int | maxScatteringEvents | 20 | maximum number of non-specular (i.e., diffuse and glossy) bounces |
| float | maxContribution | ∞ | samples are clamped to this value before they are accumulated into the framebuffer |
| bool | backgroundRefraction | false | allow for alpha blending even if background is seen through refractive objects like glass |
| Type | Name | Default | Description |
|:------|:--------------------------|--------:|:------------------------------------------------------------------------------------------------------------------------------------------|
| int | lightSamples | all | number of random light samples per path vertex, best results when a power of 2; per default all light sources are sampled |
| bool | limitIndirectLightSamples | true | after the first non-specular (i.e., diffuse and glossy) path vertex take (at most) a single light sample (instead of `lightSamples` many) |
| int | roulettePathLength | 5 | ray recursion depth at which to start Russian roulette termination |
| int | maxScatteringEvents | 20 | maximum number of non-specular (i.e., diffuse and glossy) bounces |
| float | maxContribution | ∞ | samples are clamped to this value before they are accumulated into the framebuffer |
| bool | backgroundRefraction | false | allow for alpha blending even if background is seen through refractive objects like glass |
Special parameters understood by the path tracer.
@@ -2993,7 +3019,7 @@ values of `OSPFrameBufferChannel` listed in the table below.
| OSP_FB_ACCUM | accumulation buffer for progressive refinement |
| OSP_FB_VARIANCE | for estimation of the current noise level if OSP_FB_ACCUM is also present, see [rendering](#rendering) |
| OSP_FB_NORMAL | accumulated world-space normal of the first non-specular hit, as vec3f |
| OSP_FB_ALBEDO | accumulated material albedo (color without illumination) at the first hit, as vec3f |
| OSP_FB_ALBEDO | accumulated material albedo (color without illumination) at the first non-specular hit, as vec3f |
| OSP_FB_ID_PRIMITIVE | primitive index of the first hit, as uint32 |
| OSP_FB_ID_OBJECT | geometric/volumetric model `id`, if specified, or index in [group](#groups) of first hit, as uint32 |
| OSP_FB_ID_INSTANCE | user defined [instance](#instances) `id`, if specified, or instance index of first hit, as uint32 |
@@ -3068,12 +3094,18 @@ The framebuffer takes a list of pixel operations to be applied to the
image in sequence as an `OSPData`. The pixel operations will be run in
the order they are in the array.
| Type | Name | Description |
|:----------------------|:---------------|:-------------------------------------|
| OSPImageOperation\[\] | imageOperation | ordered sequence of image operations |
| Type | Name | Description |
|:----------------------|:---------------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| OSPImageOperation\[\] | imageOperation | ordered sequence of image operations |
| int | targetFrames | anticipated number of frames that will be accumulated for progressive refinement, used renderers to generate a blue noise sampling pattern; should be a power of 2, is always 1 without `OSP_FB_ACCUM`; default 0 (disabled) |
Parameters accepted by the framebuffer.
If the total number of frames to be accumulated is known, then
`targetFrames` should be set, because then renderers can generate more
pleasing blue noise patterns. Accumulation stops when `targetFrames` is
reached.
### Image Operation
Image operations are functions that are applied to every pixel of a
@@ -3094,32 +3126,20 @@ passing the type string “`tonemapper`” to `ospNewImageOperation`. The
tone mapping curve can be customized using the parameters listed in the
table below.
| Type | Name | Default | Description |
|:------|:----------|--------:|:-------------------------------------------------------------------------|
| float | exposure | 1.0 | amount of light per unit area |
| float | contrast | 1.6773 | contrast (toe of the curve); typically is in \[1–2\] |
| float | shoulder | 0.9714 | highlight compression (shoulder of the curve); typically is in \[0.9–1\] |
| float | midIn | 0.18 | mid-level anchor input; default is 18% gray |
| float | midOut | 0.18 | mid-level anchor output; default is 18% gray |
| float | hdrMax | 11.0785 | maximum HDR input that is not clipped |
| bool | acesColor | true | apply the ACES color transforms |
| Type | Name | Default | Filmic | Description |
|:------|:----------|--------:|-------:|:-------------------------------------------------------------------------|
| float | exposure | 1.0 | 1.0 | amount of light per unit area |
| float | contrast | 1.6773 | 1.1759 | contrast (toe of the curve); typically is in \[1–2\] |
| float | shoulder | 0.9714 | 0.9746 | highlight compression (shoulder of the curve); typically is in \[0.9–1\] |
| float | midIn | 0.18 | 0.18 | mid-level anchor input; default is 18% gray |
| float | midOut | 0.18 | 0.18 | mid-level anchor output; default is 18% gray |
| float | hdrMax | 11.0785 | 6.3704 | maximum HDR input that is not clipped |
| bool | acesColor | true | false | apply the ACES color transforms |
Parameters accepted by the tone mapper.
To use the popular “Uncharted 2” filmic tone mapping curve instead, set
the parameters to the values listed in the table below.
| Name | Value |
|:----------|:-------|
| contrast | 1.1759 |
| shoulder | 0.9746 |
| midIn | 0.18 |
| midOut | 0.18 |
| hdrMax | 6.3704 |
| acesColor | false |
Filmic tone mapping curve parameters. Note that the curve includes an
exposure bias to match 18% middle gray.
Parameters accepted by the tone mapper. The column “Filmic” lists
alternative values for the popular “Uncharted 2” tone mapping curve
(note that that curve includes an exposure bias to match 18% middle
gray).
#### Denoiser
@@ -3132,6 +3152,16 @@ using a GPU when available. The device selection be overridden by the
environment variable `OIDN_DEFAULT_DEVICE`, possible values are `cpu`,
`sycl`, `cuda`, `hip`, or a physical device ID
| Type | Name | Description |
|:-----|:-------------|:-------------------------------------------------------------------------------------------------------------------|
| uint | quality | `OSPDenoiserQuality` for denoiser quality, default is |
| | | `OSP_DENOISER_QUALITY_MEDIUM`: balanced quality/performance for interactive/real-time rendering; also allowed are: |
| | | `OSP_DENOISER_QUALITY_LOW`: high performance, for interactive/real-time preview rendering |
| | | `OSP_DENOISER_QUALITY_HIGH`: high quality, for final frame rendering |
| bool | denoiseAlpha | whether to denoise the alpha channel as well, default false |
Parameters accepted by the denoiser.
Rendering
---------
@@ -3143,7 +3173,8 @@ combining a framebuffer, renderer, camera, and world.
What to render and how to render it depends on the renderer’s
parameters. If the framebuffer supports accumulation (i.e., it was
created with `OSP_FB_ACCUM`) then successive calls to `ospRenderFrame`
will progressively refine the rendered image.
will progressively refine the rendered image (until `targetFrames` is
reached).
To start an render task, use
@@ -3306,22 +3337,20 @@ ospDeviceCommit(dev);
ospSetCurrentDevice(dev);
```
| Type | Name | Description |
|:--------|:------------|:-------------------|
| void \* | syclContext | SYCL context |
| void \* | syclDevice | SYCL device |
| void \* | zeContext | Level Zero context |
| void \* | zeDevice | Level Zero device |
| Type | Name | Description |
|:--------|:------------|:-------------|
| void \* | syclContext | SYCL context |
| void \* | syclDevice | SYCL device |
Parameters specific to the `gpu` device.
Applications can either set their SYCL context and device or their Level
Zero context and device, to share device memory with OSPRay or to
control which device should be used (e.g., in case multiple GPUs are
present). If neither parameter is set, the `gpu` device will
automatically create a context internally and select a GPU (that
selection can be influenced via environment variable
`ONEAPI_DEVICE_SELECTOR`).
Applications can set their SYCL context and device to share device
memory with OSPRay or to control which device should be used (e.g., in
case multiple GPUs are present). If neither parameter is set, the `gpu`
device will automatically create a context internally and select a GPU
(that selection can be influenced via environment variable
`ONEAPI_DEVICE_SELECTOR`, see [Intel oneAPI DPC++ Compiler
documentation](https://intel.github.io/llvm-docs/EnvironmentVariables.html#oneapi-device-selector)).
Compile times for just in time compilation (JIT compilation) can be
large. To resolve this issue we recommend enabling persistent JIT
@@ -3332,7 +3361,11 @@ JIT cache should get stored).
To reduce GPU memory allocation overhead when rendering scenes with many
objects (geometries, instances, etc.), memory pooling should be enabled
by setting the environment variable `ISPCRT_MEM_POOL=1`.
by setting the environment variable
`SYCL_PI_LEVEL_ZERO_USM_ALLOCATOR="1;0;shared:1M,0,2M"`. See [Intel
oneAPI DPC++ Compiler
documentation](https://intel.github.io/llvm-docs/EnvironmentVariables.html#debugging-variables-for-level-zero-plugin)
for more details.
### Known Issues
+1 -1
View File
@@ -7,7 +7,7 @@ be overly strict. However, deviations from this document should be
supported with technical reasoning.
This document is relatively simple and meant as a "quick overview" of
expecations for OSPRay. A more complete set of guidelines for all of C++
expectations for OSPRay. A more complete set of guidelines for all of C++
can be found in the [ISO C++ Core
Guidelines](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md).
+35 -9
View File
@@ -1,22 +1,47 @@
## Copyright 2009 Intel Corporation
## SPDX-License-Identifier: Apache-2.0
cmake_minimum_required(VERSION 3.14)
include(FetchContent)
set(FETCHCONTENT_QUIET ON)
set(FETCHCONTENT_TRY_FIND_PACKAGE_MODE NEVER)
FetchContent_Declare(
imgui
GIT_REPOSITORY https://github.com/ocornut/imgui
GIT_TAG ${OSPRAY_IMGUI_GIT_TAG}
# `patch` is not available on all systems, so use `git apply` instead.
# The patch command first resets the repository to a clean state. That
# is because CMake wants to apply the patch again when CMake needs to
# reconfigure, which fails.
PATCH_COMMAND git reset --hard && git apply -v -p1 < ${CMAKE_CURRENT_SOURCE_DIR}/imgui.patch
)
FetchContent_MakeAvailable(imgui)
mark_as_advanced(FETCHCONTENT_BASE_DIR)
mark_as_advanced(FETCHCONTENT_FULLY_DISCONNECTED)
mark_as_advanced(FETCHCONTENT_QUIET)
mark_as_advanced(FETCHCONTENT_SOURCE_DIR_IMGUI)
mark_as_advanced(FETCHCONTENT_UPDATES_DISCONNECTED)
mark_as_advanced(FETCHCONTENT_UPDATES_DISCONNECTED_IMGUI)
ospray_disable_compiler_warnings()
add_library(ospray_imgui SHARED
imgui.cpp
imgui_draw.cpp
imgui_tables.cpp
imgui_widgets.cpp
imgui_impl_opengl3.cpp
imgui_impl_glfw.cpp
${imgui_SOURCE_DIR}/imgui.cpp
${imgui_SOURCE_DIR}/imgui_draw.cpp
${imgui_SOURCE_DIR}/imgui_tables.cpp
${imgui_SOURCE_DIR}/imgui_widgets.cpp
${imgui_SOURCE_DIR}/backends/imgui_impl_opengl3.cpp
${imgui_SOURCE_DIR}/backends/imgui_impl_glfw.cpp
)
target_link_libraries(ospray_imgui
PUBLIC
glfw
${OPENGL_LIBRARIES}
rkcommon::rkcommon
)
ospray_install_library(ospray_imgui apps)
@@ -24,7 +49,8 @@ ospray_install_library(ospray_imgui apps)
target_include_directories(
ospray_imgui
INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_LIST_DIR}>
$<BUILD_INTERFACE:${imgui_SOURCE_DIR}>
$<BUILD_INTERFACE:${imgui_SOURCE_DIR}/backends>
PRIVATE
${CMAKE_CURRENT_LIST_DIR}
${imgui_SOURCE_DIR}
)
-140
View File
@@ -1,140 +0,0 @@
//-----------------------------------------------------------------------------
// DEAR IMGUI COMPILE-TIME OPTIONS
// Runtime options (clipboard callbacks, enabling various features, etc.) can generally be set via the ImGuiIO structure.
// You can use ImGui::SetAllocatorFunctions() before calling ImGui::CreateContext() to rewire memory allocation functions.
//-----------------------------------------------------------------------------
// A) You may edit imconfig.h (and not overwrite it when updating Dear ImGui, or maintain a patch/rebased branch with your modifications to it)
// B) or '#define IMGUI_USER_CONFIG "my_imgui_config.h"' in your project and then add directives in your own file without touching this template.
//-----------------------------------------------------------------------------
// You need to make sure that configuration settings are defined consistently _everywhere_ Dear ImGui is used, which include the imgui*.cpp
// files but also _any_ of your code that uses Dear ImGui. This is because some compile-time options have an affect on data structures.
// Defining those options in imconfig.h will ensure every compilation unit gets to see the same data structure layouts.
// Call IMGUI_CHECKVERSION() from your .cpp file to verify that the data structures your files are using are matching the ones imgui.cpp is using.
//-----------------------------------------------------------------------------
#pragma once
//---- Define assertion handler. Defaults to calling assert().
// If your macro uses multiple statements, make sure is enclosed in a 'do { .. } while (0)' block so it can be used as a single statement.
//#define IM_ASSERT(_EXPR) MyAssert(_EXPR)
//#define IM_ASSERT(_EXPR) ((void)(_EXPR)) // Disable asserts
//---- Define attributes of all API symbols declarations, e.g. for DLL under Windows
// Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
#ifdef _WIN32
# ifdef ospray_imgui_EXPORTS
# define IMGUI_API __declspec(dllexport)
# else
# define IMGUI_API __declspec(dllimport)
# endif
#else
# define IMGUI_API
#endif
// DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions()
// for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for more details.
//#define IMGUI_API __declspec( dllexport )
//#define IMGUI_API __declspec( dllimport )
//---- Don't define obsolete functions/enums/behaviors. Consider enabling from time to time after updating to clean your code of obsolete function/names.
#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS
//#define IMGUI_DISABLE_OBSOLETE_KEYIO // 1.87+ disable legacy io.KeyMap[]+io.KeysDown[] in favor io.AddKeyEvent(). This is automatically done by IMGUI_DISABLE_OBSOLETE_FUNCTIONS.
//---- Disable all of Dear ImGui or don't implement standard windows/tools.
// It is very strongly recommended to NOT disable the demo windows and debug tool during development. They are extremely useful in day to day work. Please read comments in imgui_demo.cpp.
//#define IMGUI_DISABLE // Disable everything: all headers and source files will be empty.
#define IMGUI_DISABLE_DEMO_WINDOWS // Disable demo windows: ShowDemoWindow()/ShowStyleEditor() will be empty.
#define IMGUI_DISABLE_DEBUG_TOOLS // Disable metrics/debugger and other debug tools: ShowMetricsWindow(), ShowDebugLogWindow() and ShowIDStackToolWindow() will be empty.
//---- Don't implement some functions to reduce linkage requirements.
//#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // [Win32] Don't implement default clipboard handler. Won't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc. (user32.lib/.a, kernel32.lib/.a)
//#define IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with Visual Studio] Implement default IME handler (require imm32.lib/.a, auto-link for Visual Studio, -limm32 on command-line for MinGW)
//#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with non-Visual Studio compilers] Don't implement default IME handler (won't require imm32.lib/.a)
//#define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use and link with any Win32 function (clipboard, IME).
//#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] Implement default OSX clipboard handler (need to link with '-framework ApplicationServices', this is why this is not the default).
//#define IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS // Don't implement ImFormatString/ImFormatStringV so you can implement them yourself (e.g. if you don't want to link with vsnprintf)
//#define IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 so you can implement them yourself.
#define IMGUI_DISABLE_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle at all (replace them with dummies)
//#define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle so you can implement them yourself if you don't want to link with fopen/fclose/fread/fwrite. This will also disable the LogToTTY() function.
//#define IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call ImGui::SetAllocatorFunctions().
//#define IMGUI_DISABLE_SSE // Disable use of SSE intrinsics even if available
//---- Include imgui_user.h at the end of imgui.h as a convenience
// May be convenient for some users to only explicitly include vanilla imgui.h and have extra stuff included.
//#define IMGUI_INCLUDE_IMGUI_USER_H
//#define IMGUI_USER_H_FILENAME "my_folder/my_imgui_user.h"
//---- Pack colors to BGRA8 instead of RGBA8 (to avoid converting from one to another)
//#define IMGUI_USE_BGRA_PACKED_COLOR
//---- Use 32-bit for ImWchar (default is 16-bit) to support Unicode planes 1-16. (e.g. point beyond 0xFFFF like emoticons, dingbats, symbols, shapes, ancient languages, etc...)
//#define IMGUI_USE_WCHAR32
//---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version
// By default the embedded implementations are declared static and not available outside of Dear ImGui sources files.
//#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h"
//#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h"
//#define IMGUI_STB_SPRINTF_FILENAME "my_folder/stb_sprintf.h" // only used if IMGUI_USE_STB_SPRINTF is defined.
//#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION
//#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION
//#define IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION // only disabled if IMGUI_USE_STB_SPRINTF is defined.
//---- Use stb_sprintf.h for a faster implementation of vsnprintf instead of the one from libc (unless IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS is defined)
// Compatibility checks of arguments and formats done by clang and GCC will be disabled in order to support the extra formats provided by stb_sprintf.h.
//#define IMGUI_USE_STB_SPRINTF
//---- Use FreeType to build and rasterize the font atlas (instead of stb_truetype which is embedded by default in Dear ImGui)
// Requires FreeType headers to be available in the include path. Requires program to be compiled with 'misc/freetype/imgui_freetype.cpp' (in this repository) + the FreeType library (not provided).
// On Windows you may use vcpkg with 'vcpkg install freetype --triplet=x64-windows' + 'vcpkg integrate install'.
//#define IMGUI_ENABLE_FREETYPE
//---- Use FreeType+lunasvg library to render OpenType SVG fonts (SVGinOT)
// Requires lunasvg headers to be available in the include path + program to be linked with the lunasvg library (not provided).
// Only works in combination with IMGUI_ENABLE_FREETYPE.
// (implementation is based on Freetype's rsvg-port.c which is licensed under CeCILL-C Free Software License Agreement)
//#define IMGUI_ENABLE_FREETYPE_LUNASVG
//---- Use stb_truetype to build and rasterize the font atlas (default)
// The only purpose of this define is if you want force compilation of the stb_truetype backend ALONG with the FreeType backend.
//#define IMGUI_ENABLE_STB_TRUETYPE
//---- Define constructor and implicit cast operators to convert back<>forth between your math types and ImVec2/ImVec4.
// This will be inlined as part of ImVec2 and ImVec4 class declarations.
/*
#define IM_VEC2_CLASS_EXTRA \
constexpr ImVec2(const MyVec2& f) : x(f.x), y(f.y) {} \
operator MyVec2() const { return MyVec2(x,y); }
#define IM_VEC4_CLASS_EXTRA \
constexpr ImVec4(const MyVec4& f) : x(f.x), y(f.y), z(f.z), w(f.w) {} \
operator MyVec4() const { return MyVec4(x,y,z,w); }
*/
//---- ...Or use Dear ImGui's own very basic math operators.
//#define IMGUI_DEFINE_MATH_OPERATORS
//---- Use 32-bit vertex indices (default is 16-bit) is one way to allow large meshes with more than 64K vertices.
// Your renderer backend will need to support it (most example renderer backends support both 16/32-bit indices).
// Another way to allow large meshes while keeping 16-bit indices is to handle ImDrawCmd::VtxOffset in your renderer.
// Read about ImGuiBackendFlags_RendererHasVtxOffset for details.
//#define ImDrawIdx unsigned int
//---- Override ImDrawCallback signature (will need to modify renderer backends accordingly)
//struct ImDrawList;
//struct ImDrawCmd;
//typedef void (*MyImDrawCallback)(const ImDrawList* draw_list, const ImDrawCmd* cmd, void* my_renderer_user_data);
//#define ImDrawCallback MyImDrawCallback
//---- Debug Tools: Macro to break in Debugger (we provide a default implementation of this in the codebase)
// (use 'Metrics->Tools->Item Picker' to pick widgets with the mouse and break into them for easy debugging.)
//#define IM_DEBUG_BREAK IM_ASSERT(0)
//#define IM_DEBUG_BREAK __debugbreak()
//---- Debug Tools: Enable slower asserts
//#define IMGUI_DEBUG_PARANOID
//---- Tip: You can add extra functions within the ImGui:: namespace from anywhere (e.g. your own sources/header files)
/*
namespace ImGui
{
void MyFunction(const char* name, MyMatrix44* mtx);
}
*/
File diff suppressed because it is too large Load Diff
-3306
View File
File diff suppressed because it is too large Load Diff
+44
View File
@@ -0,0 +1,44 @@
--- a/imconfig.h
+++ b/imconfig.h
@@ -21,20 +21,29 @@
//---- Define attributes of all API symbols declarations, e.g. for DLL under Windows
// Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
+#ifdef _WIN32
+# ifdef ospray_imgui_EXPORTS
+# define IMGUI_API __declspec(dllexport)
+# else
+# define IMGUI_API __declspec(dllimport)
+# endif
+#else
+# define IMGUI_API
+#endif
// DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions()
// for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for more details.
//#define IMGUI_API __declspec( dllexport )
//#define IMGUI_API __declspec( dllimport )
//---- Don't define obsolete functions/enums/behaviors. Consider enabling from time to time after updating to clean your code of obsolete function/names.
-//#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS
+#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS
//#define IMGUI_DISABLE_OBSOLETE_KEYIO // 1.87+ disable legacy io.KeyMap[]+io.KeysDown[] in favor io.AddKeyEvent(). This is automatically done by IMGUI_DISABLE_OBSOLETE_FUNCTIONS.
//---- Disable all of Dear ImGui or don't implement standard windows/tools.
// It is very strongly recommended to NOT disable the demo windows and debug tool during development. They are extremely useful in day to day work. Please read comments in imgui_demo.cpp.
//#define IMGUI_DISABLE // Disable everything: all headers and source files will be empty.
-//#define IMGUI_DISABLE_DEMO_WINDOWS // Disable demo windows: ShowDemoWindow()/ShowStyleEditor() will be empty.
-//#define IMGUI_DISABLE_DEBUG_TOOLS // Disable metrics/debugger and other debug tools: ShowMetricsWindow(), ShowDebugLogWindow() and ShowIDStackToolWindow() will be empty.
+#define IMGUI_DISABLE_DEMO_WINDOWS // Disable demo windows: ShowDemoWindow()/ShowStyleEditor() will be empty.
+#define IMGUI_DISABLE_DEBUG_TOOLS // Disable metrics/debugger and other debug tools: ShowMetricsWindow(), ShowDebugLogWindow() and ShowIDStackToolWindow() will be empty.
//---- Don't implement some functions to reduce linkage requirements.
//#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // [Win32] Don't implement default clipboard handler. Won't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc. (user32.lib/.a, kernel32.lib/.a)
@@ -44,7 +53,7 @@
//#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] Implement default OSX clipboard handler (need to link with '-framework ApplicationServices', this is why this is not the default).
//#define IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS // Don't implement ImFormatString/ImFormatStringV so you can implement them yourself (e.g. if you don't want to link with vsnprintf)
//#define IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 so you can implement them yourself.
-//#define IMGUI_DISABLE_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle at all (replace them with dummies)
+#define IMGUI_DISABLE_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle at all (replace them with dummies)
//#define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle so you can implement them yourself if you don't want to link with fopen/fclose/fread/fwrite. This will also disable the LogToTTY() function.
//#define IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call ImGui::SetAllocatorFunctions().
//#define IMGUI_DISABLE_SSE // Disable use of SSE intrinsics even if available
File diff suppressed because it is too large Load Diff
-856
View File
@@ -1,856 +0,0 @@
// dear imgui: Platform Backend for GLFW
// This needs to be used along with a Renderer (e.g. OpenGL3, Vulkan, WebGPU..)
// (Info: GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.)
// (Requires: GLFW 3.1+. Prefer GLFW 3.3+ or GLFW 3.4+ for full feature support.)
// Implemented features:
// [X] Platform: Clipboard support.
// [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen (Windows only).
// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLFW_KEY_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set]
// [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange' (note: the resizing cursors requires GLFW 3.4+).
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// CHANGELOG
// (minor and older changes stripped away, please see git history for details)
// 2023-12-19: Emscripten: Added ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback() to register canvas selector and auto-resize GLFW window.
// 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys.
// 2023-07-18: Inputs: Revert ignoring mouse data on GLFW_CURSOR_DISABLED as it can be used differently. User may set ImGuiConfigFLags_NoMouse if desired. (#5625, #6609)
// 2023-06-12: Accept glfwGetTime() not returning a monotonically increasing value. This seems to happens on some Windows setup when peripherals disconnect, and is likely to also happen on browser + Emscripten. (#6491)
// 2023-04-04: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen on Windows ONLY, using a custom WndProc hook. (#2702)
// 2023-03-16: Inputs: Fixed key modifiers handling on secondary viewports (docking branch). Broken on 2023/01/04. (#6248, #6034)
// 2023-03-14: Emscripten: Avoid using glfwGetError() and glfwGetGamepadState() which are not correctly implemented in Emscripten emulation. (#6240)
// 2023-02-03: Emscripten: Registering custom low-level mouse wheel handler to get more accurate scrolling impulses on Emscripten. (#4019, #6096)
// 2023-01-04: Inputs: Fixed mods state on Linux when using Alt-GR text input (e.g. German keyboard layout), could lead to broken text input. Revert a 2022/01/17 change were we resumed using mods provided by GLFW, turns out they were faulty.
// 2022-11-22: Perform a dummy glfwGetError() read to cancel missing names with glfwGetKeyName(). (#5908)
// 2022-10-18: Perform a dummy glfwGetError() read to cancel missing mouse cursors errors. Using GLFW_VERSION_COMBINED directly. (#5785)
// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
// 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported).
// 2022-09-01: Inputs: Honor GLFW_CURSOR_DISABLED by not setting mouse position *EDIT* Reverted 2023-07-18.
// 2022-04-30: Inputs: Fixed ImGui_ImplGlfw_TranslateUntranslatedKey() for lower case letters on OSX.
// 2022-03-23: Inputs: Fixed a regression in 1.87 which resulted in keyboard modifiers events being reported incorrectly on Linux/X11.
// 2022-02-07: Added ImGui_ImplGlfw_InstallCallbacks()/ImGui_ImplGlfw_RestoreCallbacks() helpers to facilitate user installing callbacks after initializing backend.
// 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion.
// 2021-01-20: Inputs: calling new io.AddKeyAnalogEvent() for gamepad support, instead of writing directly to io.NavInputs[].
// 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+).
// 2022-01-17: Inputs: always update key mods next and before key event (not in NewFrame) to fix input queue with very low framerates.
// 2022-01-12: *BREAKING CHANGE*: Now using glfwSetCursorPosCallback(). If you called ImGui_ImplGlfw_InitXXX() with install_callbacks = false, you MUST install glfwSetCursorPosCallback() and forward it to the backend via ImGui_ImplGlfw_CursorPosCallback().
// 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range.
// 2022-01-05: Inputs: Converting GLFW untranslated keycodes back to translated keycodes (in the ImGui_ImplGlfw_KeyCallback() function) in order to match the behavior of every other backend, and facilitate the use of GLFW with lettered-shortcuts API.
// 2021-08-17: *BREAKING CHANGE*: Now using glfwSetWindowFocusCallback() to calling io.AddFocusEvent(). If you called ImGui_ImplGlfw_InitXXX() with install_callbacks = false, you MUST install glfwSetWindowFocusCallback() and forward it to the backend via ImGui_ImplGlfw_WindowFocusCallback().
// 2021-07-29: *BREAKING CHANGE*: Now using glfwSetCursorEnterCallback(). MousePos is correctly reported when the host platform window is hovered but not focused. If you called ImGui_ImplGlfw_InitXXX() with install_callbacks = false, you MUST install glfwSetWindowFocusCallback() callback and forward it to the backend via ImGui_ImplGlfw_CursorEnterCallback().
// 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
// 2020-01-17: Inputs: Disable error callback while assigning mouse cursors because some X11 setup don't have them and it generates errors.
// 2019-12-05: Inputs: Added support for new mouse cursors added in GLFW 3.4+ (resizing cursors, not allowed cursor).
// 2019-10-18: Misc: Previously installed user callbacks are now restored on shutdown.
// 2019-07-21: Inputs: Added mapping for ImGuiKey_KeyPadEnter.
// 2019-05-11: Inputs: Don't filter value from character callback before calling AddInputCharacter().
// 2019-03-12: Misc: Preserve DisplayFramebufferScale when main window is minimized.
// 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window.
// 2018-11-07: Inputs: When installing our GLFW callbacks, we save user's previously installed ones - if any - and chain call them.
// 2018-08-01: Inputs: Workaround for Emscripten which doesn't seem to handle focus related calls.
// 2018-06-29: Inputs: Added support for the ImGuiMouseCursor_Hand cursor.
// 2018-06-08: Misc: Extracted imgui_impl_glfw.cpp/.h away from the old combined GLFW+OpenGL/Vulkan examples.
// 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors flag + honor ImGuiConfigFlags_NoMouseCursorChange flag.
// 2018-02-20: Inputs: Added support for mouse cursors (ImGui::GetMouseCursor() value, passed to glfwSetCursor()).
// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
// 2018-02-06: Inputs: Added mapping for ImGuiKey_Space.
// 2018-01-25: Inputs: Added gamepad support if ImGuiConfigFlags_NavEnableGamepad is set.
// 2018-01-25: Inputs: Honoring the io.WantSetMousePos by repositioning the mouse (when using navigation and ImGuiConfigFlags_NavMoveMouse is set).
// 2018-01-20: Inputs: Added Horizontal Mouse Wheel support.
// 2018-01-18: Inputs: Added mapping for ImGuiKey_Insert.
// 2017-08-25: Inputs: MousePos set to -FLT_MAX,-FLT_MAX when mouse is unavailable/missing (instead of -1,-1).
// 2016-10-15: Misc: Added a void* user_data parameter to Clipboard function handlers.
#include "imgui.h"
#ifndef IMGUI_DISABLE
#include "imgui_impl_glfw.h"
// Clang warnings with -Weverything
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast
#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
#endif
// GLFW
#include <GLFW/glfw3.h>
#ifdef _WIN32
#undef APIENTRY
#define GLFW_EXPOSE_NATIVE_WIN32
#include <GLFW/glfw3native.h> // for glfwGetWin32Window()
#endif
#ifdef __APPLE__
#define GLFW_EXPOSE_NATIVE_COCOA
#include <GLFW/glfw3native.h> // for glfwGetCocoaWindow()
#endif
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#include <emscripten/html5.h>
#endif
// We gather version tests as define in order to easily see which features are version-dependent.
#define GLFW_VERSION_COMBINED (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 + GLFW_VERSION_REVISION)
#ifdef GLFW_RESIZE_NESW_CURSOR // Let's be nice to people who pulled GLFW between 2019-04-16 (3.4 define) and 2019-11-29 (cursors defines) // FIXME: Remove when GLFW 3.4 is released?
#define GLFW_HAS_NEW_CURSORS (GLFW_VERSION_COMBINED >= 3400) // 3.4+ GLFW_RESIZE_ALL_CURSOR, GLFW_RESIZE_NESW_CURSOR, GLFW_RESIZE_NWSE_CURSOR, GLFW_NOT_ALLOWED_CURSOR
#else
#define GLFW_HAS_NEW_CURSORS (0)
#endif
#define GLFW_HAS_GAMEPAD_API (GLFW_VERSION_COMBINED >= 3300) // 3.3+ glfwGetGamepadState() new api
#define GLFW_HAS_GETKEYNAME (GLFW_VERSION_COMBINED >= 3200) // 3.2+ glfwGetKeyName()
#define GLFW_HAS_GETERROR (GLFW_VERSION_COMBINED >= 3300) // 3.3+ glfwGetError()
// GLFW data
enum GlfwClientApi
{
GlfwClientApi_Unknown,
GlfwClientApi_OpenGL,
GlfwClientApi_Vulkan
};
struct ImGui_ImplGlfw_Data
{
GLFWwindow* Window;
GlfwClientApi ClientApi;
double Time;
GLFWwindow* MouseWindow;
GLFWcursor* MouseCursors[ImGuiMouseCursor_COUNT];
ImVec2 LastValidMousePos;
bool InstalledCallbacks;
bool CallbacksChainForAllWindows;
#ifdef __EMSCRIPTEN__
const char* CanvasSelector;
#endif
// Chain GLFW callbacks: our callbacks will call the user's previously installed callbacks, if any.
GLFWwindowfocusfun PrevUserCallbackWindowFocus;
GLFWcursorposfun PrevUserCallbackCursorPos;
GLFWcursorenterfun PrevUserCallbackCursorEnter;
GLFWmousebuttonfun PrevUserCallbackMousebutton;
GLFWscrollfun PrevUserCallbackScroll;
GLFWkeyfun PrevUserCallbackKey;
GLFWcharfun PrevUserCallbackChar;
GLFWmonitorfun PrevUserCallbackMonitor;
#ifdef _WIN32
WNDPROC GlfwWndProc;
#endif
ImGui_ImplGlfw_Data() { memset((void*)this, 0, sizeof(*this)); }
};
// Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts
// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
// FIXME: multi-context support is not well tested and probably dysfunctional in this backend.
// - Because glfwPollEvents() process all windows and some events may be called outside of it, you will need to register your own callbacks
// (passing install_callbacks=false in ImGui_ImplGlfw_InitXXX functions), set the current dear imgui context and then call our callbacks.
// - Otherwise we may need to store a GLFWWindow* -> ImGuiContext* map and handle this in the backend, adding a little bit of extra complexity to it.
// FIXME: some shared resources (mouse cursor shape, gamepad) are mishandled when using multi-context.
static ImGui_ImplGlfw_Data* ImGui_ImplGlfw_GetBackendData()
{
return ImGui::GetCurrentContext() ? (ImGui_ImplGlfw_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr;
}
// Functions
static const char* ImGui_ImplGlfw_GetClipboardText(void* user_data)
{
return glfwGetClipboardString((GLFWwindow*)user_data);
}
static void ImGui_ImplGlfw_SetClipboardText(void* user_data, const char* text)
{
glfwSetClipboardString((GLFWwindow*)user_data, text);
}
static ImGuiKey ImGui_ImplGlfw_KeyToImGuiKey(int key)
{
switch (key)
{
case GLFW_KEY_TAB: return ImGuiKey_Tab;
case GLFW_KEY_LEFT: return ImGuiKey_LeftArrow;
case GLFW_KEY_RIGHT: return ImGuiKey_RightArrow;
case GLFW_KEY_UP: return ImGuiKey_UpArrow;
case GLFW_KEY_DOWN: return ImGuiKey_DownArrow;
case GLFW_KEY_PAGE_UP: return ImGuiKey_PageUp;
case GLFW_KEY_PAGE_DOWN: return ImGuiKey_PageDown;
case GLFW_KEY_HOME: return ImGuiKey_Home;
case GLFW_KEY_END: return ImGuiKey_End;
case GLFW_KEY_INSERT: return ImGuiKey_Insert;
case GLFW_KEY_DELETE: return ImGuiKey_Delete;
case GLFW_KEY_BACKSPACE: return ImGuiKey_Backspace;
case GLFW_KEY_SPACE: return ImGuiKey_Space;
case GLFW_KEY_ENTER: return ImGuiKey_Enter;
case GLFW_KEY_ESCAPE: return ImGuiKey_Escape;
case GLFW_KEY_APOSTROPHE: return ImGuiKey_Apostrophe;
case GLFW_KEY_COMMA: return ImGuiKey_Comma;
case GLFW_KEY_MINUS: return ImGuiKey_Minus;
case GLFW_KEY_PERIOD: return ImGuiKey_Period;
case GLFW_KEY_SLASH: return ImGuiKey_Slash;
case GLFW_KEY_SEMICOLON: return ImGuiKey_Semicolon;
case GLFW_KEY_EQUAL: return ImGuiKey_Equal;
case GLFW_KEY_LEFT_BRACKET: return ImGuiKey_LeftBracket;
case GLFW_KEY_BACKSLASH: return ImGuiKey_Backslash;
case GLFW_KEY_RIGHT_BRACKET: return ImGuiKey_RightBracket;
case GLFW_KEY_GRAVE_ACCENT: return ImGuiKey_GraveAccent;
case GLFW_KEY_CAPS_LOCK: return ImGuiKey_CapsLock;
case GLFW_KEY_SCROLL_LOCK: return ImGuiKey_ScrollLock;
case GLFW_KEY_NUM_LOCK: return ImGuiKey_NumLock;
case GLFW_KEY_PRINT_SCREEN: return ImGuiKey_PrintScreen;
case GLFW_KEY_PAUSE: return ImGuiKey_Pause;
case GLFW_KEY_KP_0: return ImGuiKey_Keypad0;
case GLFW_KEY_KP_1: return ImGuiKey_Keypad1;
case GLFW_KEY_KP_2: return ImGuiKey_Keypad2;
case GLFW_KEY_KP_3: return ImGuiKey_Keypad3;
case GLFW_KEY_KP_4: return ImGuiKey_Keypad4;
case GLFW_KEY_KP_5: return ImGuiKey_Keypad5;
case GLFW_KEY_KP_6: return ImGuiKey_Keypad6;
case GLFW_KEY_KP_7: return ImGuiKey_Keypad7;
case GLFW_KEY_KP_8: return ImGuiKey_Keypad8;
case GLFW_KEY_KP_9: return ImGuiKey_Keypad9;
case GLFW_KEY_KP_DECIMAL: return ImGuiKey_KeypadDecimal;
case GLFW_KEY_KP_DIVIDE: return ImGuiKey_KeypadDivide;
case GLFW_KEY_KP_MULTIPLY: return ImGuiKey_KeypadMultiply;
case GLFW_KEY_KP_SUBTRACT: return ImGuiKey_KeypadSubtract;
case GLFW_KEY_KP_ADD: return ImGuiKey_KeypadAdd;
case GLFW_KEY_KP_ENTER: return ImGuiKey_KeypadEnter;
case GLFW_KEY_KP_EQUAL: return ImGuiKey_KeypadEqual;
case GLFW_KEY_LEFT_SHIFT: return ImGuiKey_LeftShift;
case GLFW_KEY_LEFT_CONTROL: return ImGuiKey_LeftCtrl;
case GLFW_KEY_LEFT_ALT: return ImGuiKey_LeftAlt;
case GLFW_KEY_LEFT_SUPER: return ImGuiKey_LeftSuper;
case GLFW_KEY_RIGHT_SHIFT: return ImGuiKey_RightShift;
case GLFW_KEY_RIGHT_CONTROL: return ImGuiKey_RightCtrl;
case GLFW_KEY_RIGHT_ALT: return ImGuiKey_RightAlt;
case GLFW_KEY_RIGHT_SUPER: return ImGuiKey_RightSuper;
case GLFW_KEY_MENU: return ImGuiKey_Menu;
case GLFW_KEY_0: return ImGuiKey_0;
case GLFW_KEY_1: return ImGuiKey_1;
case GLFW_KEY_2: return ImGuiKey_2;
case GLFW_KEY_3: return ImGuiKey_3;
case GLFW_KEY_4: return ImGuiKey_4;
case GLFW_KEY_5: return ImGuiKey_5;
case GLFW_KEY_6: return ImGuiKey_6;
case GLFW_KEY_7: return ImGuiKey_7;
case GLFW_KEY_8: return ImGuiKey_8;
case GLFW_KEY_9: return ImGuiKey_9;
case GLFW_KEY_A: return ImGuiKey_A;
case GLFW_KEY_B: return ImGuiKey_B;
case GLFW_KEY_C: return ImGuiKey_C;
case GLFW_KEY_D: return ImGuiKey_D;
case GLFW_KEY_E: return ImGuiKey_E;
case GLFW_KEY_F: return ImGuiKey_F;
case GLFW_KEY_G: return ImGuiKey_G;
case GLFW_KEY_H: return ImGuiKey_H;
case GLFW_KEY_I: return ImGuiKey_I;
case GLFW_KEY_J: return ImGuiKey_J;
case GLFW_KEY_K: return ImGuiKey_K;
case GLFW_KEY_L: return ImGuiKey_L;
case GLFW_KEY_M: return ImGuiKey_M;
case GLFW_KEY_N: return ImGuiKey_N;
case GLFW_KEY_O: return ImGuiKey_O;
case GLFW_KEY_P: return ImGuiKey_P;
case GLFW_KEY_Q: return ImGuiKey_Q;
case GLFW_KEY_R: return ImGuiKey_R;
case GLFW_KEY_S: return ImGuiKey_S;
case GLFW_KEY_T: return ImGuiKey_T;
case GLFW_KEY_U: return ImGuiKey_U;
case GLFW_KEY_V: return ImGuiKey_V;
case GLFW_KEY_W: return ImGuiKey_W;
case GLFW_KEY_X: return ImGuiKey_X;
case GLFW_KEY_Y: return ImGuiKey_Y;
case GLFW_KEY_Z: return ImGuiKey_Z;
case GLFW_KEY_F1: return ImGuiKey_F1;
case GLFW_KEY_F2: return ImGuiKey_F2;
case GLFW_KEY_F3: return ImGuiKey_F3;
case GLFW_KEY_F4: return ImGuiKey_F4;
case GLFW_KEY_F5: return ImGuiKey_F5;
case GLFW_KEY_F6: return ImGuiKey_F6;
case GLFW_KEY_F7: return ImGuiKey_F7;
case GLFW_KEY_F8: return ImGuiKey_F8;
case GLFW_KEY_F9: return ImGuiKey_F9;
case GLFW_KEY_F10: return ImGuiKey_F10;
case GLFW_KEY_F11: return ImGuiKey_F11;
case GLFW_KEY_F12: return ImGuiKey_F12;
case GLFW_KEY_F13: return ImGuiKey_F13;
case GLFW_KEY_F14: return ImGuiKey_F14;
case GLFW_KEY_F15: return ImGuiKey_F15;
case GLFW_KEY_F16: return ImGuiKey_F16;
case GLFW_KEY_F17: return ImGuiKey_F17;
case GLFW_KEY_F18: return ImGuiKey_F18;
case GLFW_KEY_F19: return ImGuiKey_F19;
case GLFW_KEY_F20: return ImGuiKey_F20;
case GLFW_KEY_F21: return ImGuiKey_F21;
case GLFW_KEY_F22: return ImGuiKey_F22;
case GLFW_KEY_F23: return ImGuiKey_F23;
case GLFW_KEY_F24: return ImGuiKey_F24;
default: return ImGuiKey_None;
}
}
// X11 does not include current pressed/released modifier key in 'mods' flags submitted by GLFW
// See https://github.com/ocornut/imgui/issues/6034 and https://github.com/glfw/glfw/issues/1630
static void ImGui_ImplGlfw_UpdateKeyModifiers(GLFWwindow* window)
{
ImGuiIO& io = ImGui::GetIO();
io.AddKeyEvent(ImGuiMod_Ctrl, (glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS));
io.AddKeyEvent(ImGuiMod_Shift, (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS));
io.AddKeyEvent(ImGuiMod_Alt, (glfwGetKey(window, GLFW_KEY_LEFT_ALT) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_ALT) == GLFW_PRESS));
io.AddKeyEvent(ImGuiMod_Super, (glfwGetKey(window, GLFW_KEY_LEFT_SUPER) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_SUPER) == GLFW_PRESS));
}
static bool ImGui_ImplGlfw_ShouldChainCallback(GLFWwindow* window)
{
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
return bd->CallbacksChainForAllWindows ? true : (window == bd->Window);
}
void ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods)
{
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
if (bd->PrevUserCallbackMousebutton != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window))
bd->PrevUserCallbackMousebutton(window, button, action, mods);
ImGui_ImplGlfw_UpdateKeyModifiers(window);
ImGuiIO& io = ImGui::GetIO();
if (button >= 0 && button < ImGuiMouseButton_COUNT)
io.AddMouseButtonEvent(button, action == GLFW_PRESS);
}
void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset)
{
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
if (bd->PrevUserCallbackScroll != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window))
bd->PrevUserCallbackScroll(window, xoffset, yoffset);
#ifdef __EMSCRIPTEN__
// Ignore GLFW events: will be processed in ImGui_ImplEmscripten_WheelCallback().
return;
#endif
ImGuiIO& io = ImGui::GetIO();
io.AddMouseWheelEvent((float)xoffset, (float)yoffset);
}
static int ImGui_ImplGlfw_TranslateUntranslatedKey(int key, int scancode)
{
#if GLFW_HAS_GETKEYNAME && !defined(__EMSCRIPTEN__)
// GLFW 3.1+ attempts to "untranslate" keys, which goes the opposite of what every other framework does, making using lettered shortcuts difficult.
// (It had reasons to do so: namely GLFW is/was more likely to be used for WASD-type game controls rather than lettered shortcuts, but IHMO the 3.1 change could have been done differently)
// See https://github.com/glfw/glfw/issues/1502 for details.
// Adding a workaround to undo this (so our keys are translated->untranslated->translated, likely a lossy process).
// This won't cover edge cases but this is at least going to cover common cases.
if (key >= GLFW_KEY_KP_0 && key <= GLFW_KEY_KP_EQUAL)
return key;
GLFWerrorfun prev_error_callback = glfwSetErrorCallback(nullptr);
const char* key_name = glfwGetKeyName(key, scancode);
glfwSetErrorCallback(prev_error_callback);
#if GLFW_HAS_GETERROR && !defined(__EMSCRIPTEN__) // Eat errors (see #5908)
(void)glfwGetError(nullptr);
#endif
if (key_name && key_name[0] != 0 && key_name[1] == 0)
{
const char char_names[] = "`-=[]\\,;\'./";
const int char_keys[] = { GLFW_KEY_GRAVE_ACCENT, GLFW_KEY_MINUS, GLFW_KEY_EQUAL, GLFW_KEY_LEFT_BRACKET, GLFW_KEY_RIGHT_BRACKET, GLFW_KEY_BACKSLASH, GLFW_KEY_COMMA, GLFW_KEY_SEMICOLON, GLFW_KEY_APOSTROPHE, GLFW_KEY_PERIOD, GLFW_KEY_SLASH, 0 };
IM_ASSERT(IM_ARRAYSIZE(char_names) == IM_ARRAYSIZE(char_keys));
if (key_name[0] >= '0' && key_name[0] <= '9') { key = GLFW_KEY_0 + (key_name[0] - '0'); }
else if (key_name[0] >= 'A' && key_name[0] <= 'Z') { key = GLFW_KEY_A + (key_name[0] - 'A'); }
else if (key_name[0] >= 'a' && key_name[0] <= 'z') { key = GLFW_KEY_A + (key_name[0] - 'a'); }
else if (const char* p = strchr(char_names, key_name[0])) { key = char_keys[p - char_names]; }
}
// if (action == GLFW_PRESS) printf("key %d scancode %d name '%s'\n", key, scancode, key_name);
#else
IM_UNUSED(scancode);
#endif
return key;
}
void ImGui_ImplGlfw_KeyCallback(GLFWwindow* window, int keycode, int scancode, int action, int mods)
{
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
if (bd->PrevUserCallbackKey != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window))
bd->PrevUserCallbackKey(window, keycode, scancode, action, mods);
if (action != GLFW_PRESS && action != GLFW_RELEASE)
return;
ImGui_ImplGlfw_UpdateKeyModifiers(window);
keycode = ImGui_ImplGlfw_TranslateUntranslatedKey(keycode, scancode);
ImGuiIO& io = ImGui::GetIO();
ImGuiKey imgui_key = ImGui_ImplGlfw_KeyToImGuiKey(keycode);
io.AddKeyEvent(imgui_key, (action == GLFW_PRESS));
io.SetKeyEventNativeData(imgui_key, keycode, scancode); // To support legacy indexing (<1.87 user code)
}
void ImGui_ImplGlfw_WindowFocusCallback(GLFWwindow* window, int focused)
{
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
if (bd->PrevUserCallbackWindowFocus != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window))
bd->PrevUserCallbackWindowFocus(window, focused);
ImGuiIO& io = ImGui::GetIO();
io.AddFocusEvent(focused != 0);
}
void ImGui_ImplGlfw_CursorPosCallback(GLFWwindow* window, double x, double y)
{
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
if (bd->PrevUserCallbackCursorPos != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window))
bd->PrevUserCallbackCursorPos(window, x, y);
ImGuiIO& io = ImGui::GetIO();
io.AddMousePosEvent((float)x, (float)y);
bd->LastValidMousePos = ImVec2((float)x, (float)y);
}
// Workaround: X11 seems to send spurious Leave/Enter events which would make us lose our position,
// so we back it up and restore on Leave/Enter (see https://github.com/ocornut/imgui/issues/4984)
void ImGui_ImplGlfw_CursorEnterCallback(GLFWwindow* window, int entered)
{
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
if (bd->PrevUserCallbackCursorEnter != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window))
bd->PrevUserCallbackCursorEnter(window, entered);
ImGuiIO& io = ImGui::GetIO();
if (entered)
{
bd->MouseWindow = window;
io.AddMousePosEvent(bd->LastValidMousePos.x, bd->LastValidMousePos.y);
}
else if (!entered && bd->MouseWindow == window)
{
bd->LastValidMousePos = io.MousePos;
bd->MouseWindow = nullptr;
io.AddMousePosEvent(-FLT_MAX, -FLT_MAX);
}
}
void ImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c)
{
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
if (bd->PrevUserCallbackChar != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window))
bd->PrevUserCallbackChar(window, c);
ImGuiIO& io = ImGui::GetIO();
io.AddInputCharacter(c);
}
void ImGui_ImplGlfw_MonitorCallback(GLFWmonitor*, int)
{
// Unused in 'master' branch but 'docking' branch will use this, so we declare it ahead of it so if you have to install callbacks you can install this one too.
}
#ifdef __EMSCRIPTEN__
static EM_BOOL ImGui_ImplEmscripten_WheelCallback(int, const EmscriptenWheelEvent* ev, void*)
{
// Mimic Emscripten_HandleWheel() in SDL.
// Corresponding equivalent in GLFW JS emulation layer has incorrect quantizing preventing small values. See #6096
float multiplier = 0.0f;
if (ev->deltaMode == DOM_DELTA_PIXEL) { multiplier = 1.0f / 100.0f; } // 100 pixels make up a step.
else if (ev->deltaMode == DOM_DELTA_LINE) { multiplier = 1.0f / 3.0f; } // 3 lines make up a step.
else if (ev->deltaMode == DOM_DELTA_PAGE) { multiplier = 80.0f; } // A page makes up 80 steps.
float wheel_x = ev->deltaX * -multiplier;
float wheel_y = ev->deltaY * -multiplier;
ImGuiIO& io = ImGui::GetIO();
io.AddMouseWheelEvent(wheel_x, wheel_y);
//IMGUI_DEBUG_LOG("[Emsc] mode %d dx: %.2f, dy: %.2f, dz: %.2f --> feed %.2f %.2f\n", (int)ev->deltaMode, ev->deltaX, ev->deltaY, ev->deltaZ, wheel_x, wheel_y);
return EM_TRUE;
}
#endif
#ifdef _WIN32
// GLFW doesn't allow to distinguish Mouse vs TouchScreen vs Pen.
// Add support for Win32 (based on imgui_impl_win32), because we rely on _TouchScreen info to trickle inputs differently.
static ImGuiMouseSource GetMouseSourceFromMessageExtraInfo()
{
LPARAM extra_info = ::GetMessageExtraInfo();
if ((extra_info & 0xFFFFFF80) == 0xFF515700)
return ImGuiMouseSource_Pen;
if ((extra_info & 0xFFFFFF80) == 0xFF515780)
return ImGuiMouseSource_TouchScreen;
return ImGuiMouseSource_Mouse;
}
static LRESULT CALLBACK ImGui_ImplGlfw_WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
switch (msg)
{
case WM_MOUSEMOVE: case WM_NCMOUSEMOVE:
case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK: case WM_LBUTTONUP:
case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK: case WM_RBUTTONUP:
case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK: case WM_MBUTTONUP:
case WM_XBUTTONDOWN: case WM_XBUTTONDBLCLK: case WM_XBUTTONUP:
ImGui::GetIO().AddMouseSourceEvent(GetMouseSourceFromMessageExtraInfo());
break;
}
return ::CallWindowProcW(bd->GlfwWndProc, hWnd, msg, wParam, lParam);
}
#endif
void ImGui_ImplGlfw_InstallCallbacks(GLFWwindow* window)
{
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
IM_ASSERT(bd->InstalledCallbacks == false && "Callbacks already installed!");
IM_ASSERT(bd->Window == window);
bd->PrevUserCallbackWindowFocus = glfwSetWindowFocusCallback(window, ImGui_ImplGlfw_WindowFocusCallback);
bd->PrevUserCallbackCursorEnter = glfwSetCursorEnterCallback(window, ImGui_ImplGlfw_CursorEnterCallback);
bd->PrevUserCallbackCursorPos = glfwSetCursorPosCallback(window, ImGui_ImplGlfw_CursorPosCallback);
bd->PrevUserCallbackMousebutton = glfwSetMouseButtonCallback(window, ImGui_ImplGlfw_MouseButtonCallback);
bd->PrevUserCallbackScroll = glfwSetScrollCallback(window, ImGui_ImplGlfw_ScrollCallback);
bd->PrevUserCallbackKey = glfwSetKeyCallback(window, ImGui_ImplGlfw_KeyCallback);
bd->PrevUserCallbackChar = glfwSetCharCallback(window, ImGui_ImplGlfw_CharCallback);
bd->PrevUserCallbackMonitor = glfwSetMonitorCallback(ImGui_ImplGlfw_MonitorCallback);
bd->InstalledCallbacks = true;
}
void ImGui_ImplGlfw_RestoreCallbacks(GLFWwindow* window)
{
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
IM_ASSERT(bd->InstalledCallbacks == true && "Callbacks not installed!");
IM_ASSERT(bd->Window == window);
glfwSetWindowFocusCallback(window, bd->PrevUserCallbackWindowFocus);
glfwSetCursorEnterCallback(window, bd->PrevUserCallbackCursorEnter);
glfwSetCursorPosCallback(window, bd->PrevUserCallbackCursorPos);
glfwSetMouseButtonCallback(window, bd->PrevUserCallbackMousebutton);
glfwSetScrollCallback(window, bd->PrevUserCallbackScroll);
glfwSetKeyCallback(window, bd->PrevUserCallbackKey);
glfwSetCharCallback(window, bd->PrevUserCallbackChar);
glfwSetMonitorCallback(bd->PrevUserCallbackMonitor);
bd->InstalledCallbacks = false;
bd->PrevUserCallbackWindowFocus = nullptr;
bd->PrevUserCallbackCursorEnter = nullptr;
bd->PrevUserCallbackCursorPos = nullptr;
bd->PrevUserCallbackMousebutton = nullptr;
bd->PrevUserCallbackScroll = nullptr;
bd->PrevUserCallbackKey = nullptr;
bd->PrevUserCallbackChar = nullptr;
bd->PrevUserCallbackMonitor = nullptr;
}
// Set to 'true' to enable chaining installed callbacks for all windows (including secondary viewports created by backends or by user.
// This is 'false' by default meaning we only chain callbacks for the main viewport.
// We cannot set this to 'true' by default because user callbacks code may be not testing the 'window' parameter of their callback.
// If you set this to 'true' your user callback code will need to make sure you are testing the 'window' parameter.
void ImGui_ImplGlfw_SetCallbacksChainForAllWindows(bool chain_for_all_windows)
{
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
bd->CallbacksChainForAllWindows = chain_for_all_windows;
}
static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, GlfwClientApi client_api)
{
ImGuiIO& io = ImGui::GetIO();
IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!");
//printf("GLFW_VERSION: %d.%d.%d (%d)", GLFW_VERSION_MAJOR, GLFW_VERSION_MINOR, GLFW_VERSION_REVISION, GLFW_VERSION_COMBINED);
// Setup backend capabilities flags
ImGui_ImplGlfw_Data* bd = IM_NEW(ImGui_ImplGlfw_Data)();
io.BackendPlatformUserData = (void*)bd;
io.BackendPlatformName = "imgui_impl_glfw";
io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used)
bd->Window = window;
bd->Time = 0.0;
io.SetClipboardTextFn = ImGui_ImplGlfw_SetClipboardText;
io.GetClipboardTextFn = ImGui_ImplGlfw_GetClipboardText;
io.ClipboardUserData = bd->Window;
// Create mouse cursors
// (By design, on X11 cursors are user configurable and some cursors may be missing. When a cursor doesn't exist,
// GLFW will emit an error which will often be printed by the app, so we temporarily disable error reporting.
// Missing cursors will return nullptr and our _UpdateMouseCursor() function will use the Arrow cursor instead.)
GLFWerrorfun prev_error_callback = glfwSetErrorCallback(nullptr);
bd->MouseCursors[ImGuiMouseCursor_Arrow] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
bd->MouseCursors[ImGuiMouseCursor_TextInput] = glfwCreateStandardCursor(GLFW_IBEAM_CURSOR);
bd->MouseCursors[ImGuiMouseCursor_ResizeNS] = glfwCreateStandardCursor(GLFW_VRESIZE_CURSOR);
bd->MouseCursors[ImGuiMouseCursor_ResizeEW] = glfwCreateStandardCursor(GLFW_HRESIZE_CURSOR);
bd->MouseCursors[ImGuiMouseCursor_Hand] = glfwCreateStandardCursor(GLFW_HAND_CURSOR);
#if GLFW_HAS_NEW_CURSORS
bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_RESIZE_ALL_CURSOR);
bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_RESIZE_NESW_CURSOR);
bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_RESIZE_NWSE_CURSOR);
bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = glfwCreateStandardCursor(GLFW_NOT_ALLOWED_CURSOR);
#else
bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
#endif
glfwSetErrorCallback(prev_error_callback);
#if GLFW_HAS_GETERROR && !defined(__EMSCRIPTEN__) // Eat errors (see #5908)
(void)glfwGetError(nullptr);
#endif
// Chain GLFW callbacks: our callbacks will call the user's previously installed callbacks, if any.
if (install_callbacks)
ImGui_ImplGlfw_InstallCallbacks(window);
// Register Emscripten Wheel callback to workaround issue in Emscripten GLFW Emulation (#6096)
// We intentionally do not check 'if (install_callbacks)' here, as some users may set it to false and call GLFW callback themselves.
// FIXME: May break chaining in case user registered their own Emscripten callback?
#ifdef __EMSCRIPTEN__
emscripten_set_wheel_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, nullptr, false, ImGui_ImplEmscripten_WheelCallback);
#endif
// Set platform dependent data in viewport
ImGuiViewport* main_viewport = ImGui::GetMainViewport();
#ifdef _WIN32
main_viewport->PlatformHandleRaw = glfwGetWin32Window(bd->Window);
#elif defined(__APPLE__)
main_viewport->PlatformHandleRaw = (void*)glfwGetCocoaWindow(bd->Window);
#else
IM_UNUSED(main_viewport);
#endif
// Windows: register a WndProc hook so we can intercept some messages.
#ifdef _WIN32
bd->GlfwWndProc = (WNDPROC)::GetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC);
IM_ASSERT(bd->GlfwWndProc != nullptr);
::SetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC, (LONG_PTR)ImGui_ImplGlfw_WndProc);
#endif
bd->ClientApi = client_api;
return true;
}
bool ImGui_ImplGlfw_InitForOpenGL(GLFWwindow* window, bool install_callbacks)
{
return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_OpenGL);
}
bool ImGui_ImplGlfw_InitForVulkan(GLFWwindow* window, bool install_callbacks)
{
return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_Vulkan);
}
bool ImGui_ImplGlfw_InitForOther(GLFWwindow* window, bool install_callbacks)
{
return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_Unknown);
}
void ImGui_ImplGlfw_Shutdown()
{
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?");
ImGuiIO& io = ImGui::GetIO();
if (bd->InstalledCallbacks)
ImGui_ImplGlfw_RestoreCallbacks(bd->Window);
#ifdef __EMSCRIPTEN__
emscripten_set_wheel_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, nullptr, false, nullptr);
#endif
for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++)
glfwDestroyCursor(bd->MouseCursors[cursor_n]);
// Windows: register a WndProc hook so we can intercept some messages.
#ifdef _WIN32
ImGuiViewport* main_viewport = ImGui::GetMainViewport();
::SetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC, (LONG_PTR)bd->GlfwWndProc);
bd->GlfwWndProc = nullptr;
#endif
io.BackendPlatformName = nullptr;
io.BackendPlatformUserData = nullptr;
io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad);
IM_DELETE(bd);
}
static void ImGui_ImplGlfw_UpdateMouseData()
{
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
ImGuiIO& io = ImGui::GetIO();
// (those braces are here to reduce diff with multi-viewports support in 'docking' branch)
{
GLFWwindow* window = bd->Window;
#ifdef __EMSCRIPTEN__
const bool is_window_focused = true;
#else
const bool is_window_focused = glfwGetWindowAttrib(window, GLFW_FOCUSED) != 0;
#endif
if (is_window_focused)
{
// (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user)
if (io.WantSetMousePos)
glfwSetCursorPos(window, (double)io.MousePos.x, (double)io.MousePos.y);
// (Optional) Fallback to provide mouse position when focused (ImGui_ImplGlfw_CursorPosCallback already provides this when hovered or captured)
if (bd->MouseWindow == nullptr)
{
double mouse_x, mouse_y;
glfwGetCursorPos(window, &mouse_x, &mouse_y);
bd->LastValidMousePos = ImVec2((float)mouse_x, (float)mouse_y);
io.AddMousePosEvent((float)mouse_x, (float)mouse_y);
}
}
}
}
static void ImGui_ImplGlfw_UpdateMouseCursor()
{
ImGuiIO& io = ImGui::GetIO();
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
if ((io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) || glfwGetInputMode(bd->Window, GLFW_CURSOR) == GLFW_CURSOR_DISABLED)
return;
ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
// (those braces are here to reduce diff with multi-viewports support in 'docking' branch)
{
GLFWwindow* window = bd->Window;
if (imgui_cursor == ImGuiMouseCursor_None || io.MouseDrawCursor)
{
// Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
}
else
{
// Show OS mouse cursor
// FIXME-PLATFORM: Unfocused windows seems to fail changing the mouse cursor with GLFW 3.2, but 3.3 works here.
glfwSetCursor(window, bd->MouseCursors[imgui_cursor] ? bd->MouseCursors[imgui_cursor] : bd->MouseCursors[ImGuiMouseCursor_Arrow]);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
}
}
}
// Update gamepad inputs
static inline float Saturate(float v) { return v < 0.0f ? 0.0f : v > 1.0f ? 1.0f : v; }
static void ImGui_ImplGlfw_UpdateGamepads()
{
ImGuiIO& io = ImGui::GetIO();
if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs.
return;
io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad;
#if GLFW_HAS_GAMEPAD_API && !defined(__EMSCRIPTEN__)
GLFWgamepadstate gamepad;
if (!glfwGetGamepadState(GLFW_JOYSTICK_1, &gamepad))
return;
#define MAP_BUTTON(KEY_NO, BUTTON_NO, _UNUSED) do { io.AddKeyEvent(KEY_NO, gamepad.buttons[BUTTON_NO] != 0); } while (0)
#define MAP_ANALOG(KEY_NO, AXIS_NO, _UNUSED, V0, V1) do { float v = gamepad.axes[AXIS_NO]; v = (v - V0) / (V1 - V0); io.AddKeyAnalogEvent(KEY_NO, v > 0.10f, Saturate(v)); } while (0)
#else
int axes_count = 0, buttons_count = 0;
const float* axes = glfwGetJoystickAxes(GLFW_JOYSTICK_1, &axes_count);
const unsigned char* buttons = glfwGetJoystickButtons(GLFW_JOYSTICK_1, &buttons_count);
if (axes_count == 0 || buttons_count == 0)
return;
#define MAP_BUTTON(KEY_NO, _UNUSED, BUTTON_NO) do { io.AddKeyEvent(KEY_NO, (buttons_count > BUTTON_NO && buttons[BUTTON_NO] == GLFW_PRESS)); } while (0)
#define MAP_ANALOG(KEY_NO, _UNUSED, AXIS_NO, V0, V1) do { float v = (axes_count > AXIS_NO) ? axes[AXIS_NO] : V0; v = (v - V0) / (V1 - V0); io.AddKeyAnalogEvent(KEY_NO, v > 0.10f, Saturate(v)); } while (0)
#endif
io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
MAP_BUTTON(ImGuiKey_GamepadStart, GLFW_GAMEPAD_BUTTON_START, 7);
MAP_BUTTON(ImGuiKey_GamepadBack, GLFW_GAMEPAD_BUTTON_BACK, 6);
MAP_BUTTON(ImGuiKey_GamepadFaceLeft, GLFW_GAMEPAD_BUTTON_X, 2); // Xbox X, PS Square
MAP_BUTTON(ImGuiKey_GamepadFaceRight, GLFW_GAMEPAD_BUTTON_B, 1); // Xbox B, PS Circle
MAP_BUTTON(ImGuiKey_GamepadFaceUp, GLFW_GAMEPAD_BUTTON_Y, 3); // Xbox Y, PS Triangle
MAP_BUTTON(ImGuiKey_GamepadFaceDown, GLFW_GAMEPAD_BUTTON_A, 0); // Xbox A, PS Cross
MAP_BUTTON(ImGuiKey_GamepadDpadLeft, GLFW_GAMEPAD_BUTTON_DPAD_LEFT, 13);
MAP_BUTTON(ImGuiKey_GamepadDpadRight, GLFW_GAMEPAD_BUTTON_DPAD_RIGHT, 11);
MAP_BUTTON(ImGuiKey_GamepadDpadUp, GLFW_GAMEPAD_BUTTON_DPAD_UP, 10);
MAP_BUTTON(ImGuiKey_GamepadDpadDown, GLFW_GAMEPAD_BUTTON_DPAD_DOWN, 12);
MAP_BUTTON(ImGuiKey_GamepadL1, GLFW_GAMEPAD_BUTTON_LEFT_BUMPER, 4);
MAP_BUTTON(ImGuiKey_GamepadR1, GLFW_GAMEPAD_BUTTON_RIGHT_BUMPER, 5);
MAP_ANALOG(ImGuiKey_GamepadL2, GLFW_GAMEPAD_AXIS_LEFT_TRIGGER, 4, -0.75f, +1.0f);
MAP_ANALOG(ImGuiKey_GamepadR2, GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER, 5, -0.75f, +1.0f);
MAP_BUTTON(ImGuiKey_GamepadL3, GLFW_GAMEPAD_BUTTON_LEFT_THUMB, 8);
MAP_BUTTON(ImGuiKey_GamepadR3, GLFW_GAMEPAD_BUTTON_RIGHT_THUMB, 9);
MAP_ANALOG(ImGuiKey_GamepadLStickLeft, GLFW_GAMEPAD_AXIS_LEFT_X, 0, -0.25f, -1.0f);
MAP_ANALOG(ImGuiKey_GamepadLStickRight, GLFW_GAMEPAD_AXIS_LEFT_X, 0, +0.25f, +1.0f);
MAP_ANALOG(ImGuiKey_GamepadLStickUp, GLFW_GAMEPAD_AXIS_LEFT_Y, 1, -0.25f, -1.0f);
MAP_ANALOG(ImGuiKey_GamepadLStickDown, GLFW_GAMEPAD_AXIS_LEFT_Y, 1, +0.25f, +1.0f);
MAP_ANALOG(ImGuiKey_GamepadRStickLeft, GLFW_GAMEPAD_AXIS_RIGHT_X, 2, -0.25f, -1.0f);
MAP_ANALOG(ImGuiKey_GamepadRStickRight, GLFW_GAMEPAD_AXIS_RIGHT_X, 2, +0.25f, +1.0f);
MAP_ANALOG(ImGuiKey_GamepadRStickUp, GLFW_GAMEPAD_AXIS_RIGHT_Y, 3, -0.25f, -1.0f);
MAP_ANALOG(ImGuiKey_GamepadRStickDown, GLFW_GAMEPAD_AXIS_RIGHT_Y, 3, +0.25f, +1.0f);
#undef MAP_BUTTON
#undef MAP_ANALOG
}
void ImGui_ImplGlfw_NewFrame()
{
ImGuiIO& io = ImGui::GetIO();
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplGlfw_InitForXXX()?");
// Setup display size (every frame to accommodate for window resizing)
int w, h;
int display_w, display_h;
glfwGetWindowSize(bd->Window, &w, &h);
glfwGetFramebufferSize(bd->Window, &display_w, &display_h);
io.DisplaySize = ImVec2((float)w, (float)h);
if (w > 0 && h > 0)
io.DisplayFramebufferScale = ImVec2((float)display_w / (float)w, (float)display_h / (float)h);
// Setup time step
// (Accept glfwGetTime() not returning a monotonically increasing value. Seems to happens on disconnecting peripherals and probably on VMs and Emscripten, see #6491, #6189, #6114, #3644)
double current_time = glfwGetTime();
if (current_time <= bd->Time)
current_time = bd->Time + 0.00001f;
io.DeltaTime = bd->Time > 0.0 ? (float)(current_time - bd->Time) : (float)(1.0f / 60.0f);
bd->Time = current_time;
ImGui_ImplGlfw_UpdateMouseData();
ImGui_ImplGlfw_UpdateMouseCursor();
// Update game controllers (if enabled and available)
ImGui_ImplGlfw_UpdateGamepads();
}
#ifdef __EMSCRIPTEN__
static EM_BOOL ImGui_ImplGlfw_OnCanvasSizeChange(int event_type, const EmscriptenUiEvent* event, void* user_data)
{
ImGui_ImplGlfw_Data* bd = (ImGui_ImplGlfw_Data*)user_data;
double canvas_width, canvas_height;
emscripten_get_element_css_size(bd->CanvasSelector, &canvas_width, &canvas_height);
glfwSetWindowSize(bd->Window, (int)canvas_width, (int)canvas_height);
return true;
}
static EM_BOOL ImGui_ImplEmscripten_FullscreenChangeCallback(int event_type, const EmscriptenFullscreenChangeEvent* event, void* user_data)
{
ImGui_ImplGlfw_Data* bd = (ImGui_ImplGlfw_Data*)user_data;
double canvas_width, canvas_height;
emscripten_get_element_css_size(bd->CanvasSelector, &canvas_width, &canvas_height);
glfwSetWindowSize(bd->Window, (int)canvas_width, (int)canvas_height);
return true;
}
// 'canvas_selector' is a CSS selector. The event listener is applied to the first element that matches the query.
// STRING MUST PERSIST FOR THE APPLICATION DURATION. PLEASE USE A STRING LITERAL OR ENSURE POINTER WILL STAY VALID.
void ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback(const char* canvas_selector)
{
IM_ASSERT(canvas_selector != nullptr);
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplGlfw_InitForXXX()?");
bd->CanvasSelector = canvas_selector;
emscripten_set_resize_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, bd, false, ImGui_ImplGlfw_OnCanvasSizeChange);
emscripten_set_fullscreenchange_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, bd, false, ImGui_ImplEmscripten_FullscreenChangeCallback);
// Change the size of the GLFW window according to the size of the canvas
ImGui_ImplGlfw_OnCanvasSizeChange(EMSCRIPTEN_EVENT_RESIZE, {}, bd);
}
#endif
//-----------------------------------------------------------------------------
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
#endif // #ifndef IMGUI_DISABLE
-58
View File
@@ -1,58 +0,0 @@
// dear imgui: Platform Backend for GLFW
// This needs to be used along with a Renderer (e.g. OpenGL3, Vulkan, WebGPU..)
// (Info: GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.)
// Implemented features:
// [X] Platform: Clipboard support.
// [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen (Windows only).
// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLFW_KEY_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set]
// [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange' (note: the resizing cursors requires GLFW 3.4+).
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#pragma once
#include "imgui.h" // IMGUI_IMPL_API
#ifndef IMGUI_DISABLE
struct GLFWwindow;
struct GLFWmonitor;
IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForOpenGL(GLFWwindow* window, bool install_callbacks);
IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForVulkan(GLFWwindow* window, bool install_callbacks);
IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForOther(GLFWwindow* window, bool install_callbacks);
IMGUI_IMPL_API void ImGui_ImplGlfw_Shutdown();
IMGUI_IMPL_API void ImGui_ImplGlfw_NewFrame();
// Emscripten related initialization phase methods
#ifdef __EMSCRIPTEN__
IMGUI_IMPL_API void ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback(const char* canvas_selector);
#endif
// GLFW callbacks install
// - When calling Init with 'install_callbacks=true': ImGui_ImplGlfw_InstallCallbacks() is called. GLFW callbacks will be installed for you. They will chain-call user's previously installed callbacks, if any.
// - When calling Init with 'install_callbacks=false': GLFW callbacks won't be installed. You will need to call individual function yourself from your own GLFW callbacks.
IMGUI_IMPL_API void ImGui_ImplGlfw_InstallCallbacks(GLFWwindow* window);
IMGUI_IMPL_API void ImGui_ImplGlfw_RestoreCallbacks(GLFWwindow* window);
// GFLW callbacks options:
// - Set 'chain_for_all_windows=true' to enable chaining callbacks for all windows (including secondary viewports created by backends or by user)
IMGUI_IMPL_API void ImGui_ImplGlfw_SetCallbacksChainForAllWindows(bool chain_for_all_windows);
// GLFW callbacks (individual callbacks to call yourself if you didn't install callbacks)
IMGUI_IMPL_API void ImGui_ImplGlfw_WindowFocusCallback(GLFWwindow* window, int focused); // Since 1.84
IMGUI_IMPL_API void ImGui_ImplGlfw_CursorEnterCallback(GLFWwindow* window, int entered); // Since 1.84
IMGUI_IMPL_API void ImGui_ImplGlfw_CursorPosCallback(GLFWwindow* window, double x, double y); // Since 1.87
IMGUI_IMPL_API void ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods);
IMGUI_IMPL_API void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset);
IMGUI_IMPL_API void ImGui_ImplGlfw_KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods);
IMGUI_IMPL_API void ImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c);
IMGUI_IMPL_API void ImGui_ImplGlfw_MonitorCallback(GLFWmonitor* monitor, int event);
#endif // #ifndef IMGUI_DISABLE
-948
View File
@@ -1,948 +0,0 @@
// dear imgui: Renderer Backend for modern OpenGL with shaders / programmatic pipeline
// - Desktop GL: 2.x 3.x 4.x
// - Embedded GL: ES 2.0 (WebGL 1.0), ES 3.0 (WebGL 2.0)
// This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..)
// Implemented features:
// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID!
// [x] Renderer: Large meshes support (64k+ vertices) with 16-bit indices (Desktop OpenGL only).
// About WebGL/ES:
// - You need to '#define IMGUI_IMPL_OPENGL_ES2' or '#define IMGUI_IMPL_OPENGL_ES3' to use WebGL or OpenGL ES.
// - This is done automatically on iOS, Android and Emscripten targets.
// - For other targets, the define needs to be visible from the imgui_impl_opengl3.cpp compilation unit. If unsure, define globally or in imconfig.h.
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// CHANGELOG
// (minor and older changes stripped away, please see git history for details)
// 2024-01-09: OpenGL: Update GL3W based imgui_impl_opengl3_loader.h to load "libGL.so" and variants, fixing regression on distros missing a symlink.
// 2023-11-08: OpenGL: Update GL3W based imgui_impl_opengl3_loader.h to load "libGL.so" instead of "libGL.so.1", accommodating for NetBSD systems having only "libGL.so.3" available. (#6983)
// 2023-10-05: OpenGL: Rename symbols in our internal loader so that LTO compilation with another copy of gl3w is possible. (#6875, #6668, #4445)
// 2023-06-20: OpenGL: Fixed erroneous use glGetIntegerv(GL_CONTEXT_PROFILE_MASK) on contexts lower than 3.2. (#6539, #6333)
// 2023-05-09: OpenGL: Support for glBindSampler() backup/restore on ES3. (#6375)
// 2023-04-18: OpenGL: Restore front and back polygon mode separately when supported by context. (#6333)
// 2023-03-23: OpenGL: Properly restoring "no shader program bound" if it was the case prior to running the rendering function. (#6267, #6220, #6224)
// 2023-03-15: OpenGL: Fixed GL loader crash when GL_VERSION returns NULL. (#6154, #4445, #3530)
// 2023-03-06: OpenGL: Fixed restoration of a potentially deleted OpenGL program, by calling glIsProgram(). (#6220, #6224)
// 2022-11-09: OpenGL: Reverted use of glBufferSubData(), too many corruptions issues + old issues seemingly can't be reproed with Intel drivers nowadays (revert 2021-12-15 and 2022-05-23 changes).
// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
// 2022-09-27: OpenGL: Added ability to '#define IMGUI_IMPL_OPENGL_DEBUG'.
// 2022-05-23: OpenGL: Reworking 2021-12-15 "Using buffer orphaning" so it only happens on Intel GPU, seems to cause problems otherwise. (#4468, #4825, #4832, #5127).
// 2022-05-13: OpenGL: Fixed state corruption on OpenGL ES 2.0 due to not preserving GL_ELEMENT_ARRAY_BUFFER_BINDING and vertex attribute states.
// 2021-12-15: OpenGL: Using buffer orphaning + glBufferSubData(), seems to fix leaks with multi-viewports with some Intel HD drivers.
// 2021-08-23: OpenGL: Fixed ES 3.0 shader ("#version 300 es") use normal precision floats to avoid wobbly rendering at HD resolutions.
// 2021-08-19: OpenGL: Embed and use our own minimal GL loader (imgui_impl_opengl3_loader.h), removing requirement and support for third-party loader.
// 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
// 2021-06-25: OpenGL: Use OES_vertex_array extension on Emscripten + backup/restore current state.
// 2021-06-21: OpenGL: Destroy individual vertex/fragment shader objects right after they are linked into the main shader.
// 2021-05-24: OpenGL: Access GL_CLIP_ORIGIN when "GL_ARB_clip_control" extension is detected, inside of just OpenGL 4.5 version.
// 2021-05-19: OpenGL: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
// 2021-04-06: OpenGL: Don't try to read GL_CLIP_ORIGIN unless we're OpenGL 4.5 or greater.
// 2021-02-18: OpenGL: Change blending equation to preserve alpha in output buffer.
// 2021-01-03: OpenGL: Backup, setup and restore GL_STENCIL_TEST state.
// 2020-10-23: OpenGL: Backup, setup and restore GL_PRIMITIVE_RESTART state.
// 2020-10-15: OpenGL: Use glGetString(GL_VERSION) instead of glGetIntegerv(GL_MAJOR_VERSION, ...) when the later returns zero (e.g. Desktop GL 2.x)
// 2020-09-17: OpenGL: Fix to avoid compiling/calling glBindSampler() on ES or pre 3.3 context which have the defines set by a loader.
// 2020-07-10: OpenGL: Added support for glad2 OpenGL loader.
// 2020-05-08: OpenGL: Made default GLSL version 150 (instead of 130) on OSX.
// 2020-04-21: OpenGL: Fixed handling of glClipControl(GL_UPPER_LEFT) by inverting projection matrix.
// 2020-04-12: OpenGL: Fixed context version check mistakenly testing for 4.0+ instead of 3.2+ to enable ImGuiBackendFlags_RendererHasVtxOffset.
// 2020-03-24: OpenGL: Added support for glbinding 2.x OpenGL loader.
// 2020-01-07: OpenGL: Added support for glbinding 3.x OpenGL loader.
// 2019-10-25: OpenGL: Using a combination of GL define and runtime GL version to decide whether to use glDrawElementsBaseVertex(). Fix building with pre-3.2 GL loaders.
// 2019-09-22: OpenGL: Detect default GL loader using __has_include compiler facility.
// 2019-09-16: OpenGL: Tweak initialization code to allow application calling ImGui_ImplOpenGL3_CreateFontsTexture() before the first NewFrame() call.
// 2019-05-29: OpenGL: Desktop GL only: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
// 2019-04-30: OpenGL: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
// 2019-03-29: OpenGL: Not calling glBindBuffer more than necessary in the render loop.
// 2019-03-15: OpenGL: Added a GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early.
// 2019-03-03: OpenGL: Fix support for ES 2.0 (WebGL 1.0).
// 2019-02-20: OpenGL: Fix for OSX not supporting OpenGL 4.5, we don't try to read GL_CLIP_ORIGIN even if defined by the headers/loader.
// 2019-02-11: OpenGL: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display.
// 2019-02-01: OpenGL: Using GLSL 410 shaders for any version over 410 (e.g. 430, 450).
// 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
// 2018-11-13: OpenGL: Support for GL 4.5's glClipControl(GL_UPPER_LEFT) / GL_CLIP_ORIGIN.
// 2018-08-29: OpenGL: Added support for more OpenGL loaders: glew and glad, with comments indicative that any loader can be used.
// 2018-08-09: OpenGL: Default to OpenGL ES 3 on iOS and Android. GLSL version default to "#version 300 ES".
// 2018-07-30: OpenGL: Support for GLSL 300 ES and 410 core. Fixes for Emscripten compilation.
// 2018-07-10: OpenGL: Support for more GLSL versions (based on the GLSL version string). Added error output when shaders fail to compile/link.
// 2018-06-08: Misc: Extracted imgui_impl_opengl3.cpp/.h away from the old combined GLFW/SDL+OpenGL3 examples.
// 2018-06-08: OpenGL: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
// 2018-05-25: OpenGL: Removed unnecessary backup/restore of GL_ELEMENT_ARRAY_BUFFER_BINDING since this is part of the VAO state.
// 2018-05-14: OpenGL: Making the call to glBindSampler() optional so 3.2 context won't fail if the function is a nullptr pointer.
// 2018-03-06: OpenGL: Added const char* glsl_version parameter to ImGui_ImplOpenGL3_Init() so user can override the GLSL version e.g. "#version 150".
// 2018-02-23: OpenGL: Create the VAO in the render function so the setup can more easily be used with multiple shared GL context.
// 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplSdlGL3_RenderDrawData() in the .h file so you can call it yourself.
// 2018-01-07: OpenGL: Changed GLSL shader version from 330 to 150.
// 2017-09-01: OpenGL: Save and restore current bound sampler. Save and restore current polygon mode.
// 2017-05-01: OpenGL: Fixed save and restore of current blend func state.
// 2017-05-01: OpenGL: Fixed save and restore of current GL_ACTIVE_TEXTURE.
// 2016-09-05: OpenGL: Fixed save and restore of current scissor rectangle.
// 2016-07-29: OpenGL: Explicitly setting GL_UNPACK_ROW_LENGTH to reduce issues because SDL changes it. (#752)
//----------------------------------------
// OpenGL GLSL GLSL
// version version string
//----------------------------------------
// 2.0 110 "#version 110"
// 2.1 120 "#version 120"
// 3.0 130 "#version 130"
// 3.1 140 "#version 140"
// 3.2 150 "#version 150"
// 3.3 330 "#version 330 core"
// 4.0 400 "#version 400 core"
// 4.1 410 "#version 410 core"
// 4.2 420 "#version 410 core"
// 4.3 430 "#version 430 core"
// ES 2.0 100 "#version 100" = WebGL 1.0
// ES 3.0 300 "#version 300 es" = WebGL 2.0
//----------------------------------------
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "imgui.h"
#ifndef IMGUI_DISABLE
#include "imgui_impl_opengl3.h"
#include <stdio.h>
#include <stdint.h> // intptr_t
#if defined(__APPLE__)
#include <TargetConditionals.h>
#endif
// Clang/GCC warnings with -Weverything
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast
#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
#pragma clang diagnostic ignored "-Wunused-macros" // warning: macro is not used
#pragma clang diagnostic ignored "-Wnonportable-system-include-path"
#pragma clang diagnostic ignored "-Wcast-function-type" // warning: cast between incompatible function types (for loader)
#endif
#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
#pragma GCC diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx'
#pragma GCC diagnostic ignored "-Wcast-function-type" // warning: cast between incompatible function types (for loader)
#endif
// GL includes
#if defined(IMGUI_IMPL_OPENGL_ES2)
#if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV))
#include <OpenGLES/ES2/gl.h> // Use GL ES 2
#else
#include <GLES2/gl2.h> // Use GL ES 2
#endif
#if defined(__EMSCRIPTEN__)
#ifndef GL_GLEXT_PROTOTYPES
#define GL_GLEXT_PROTOTYPES
#endif
#include <GLES2/gl2ext.h>
#endif
#elif defined(IMGUI_IMPL_OPENGL_ES3)
#if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV))
#include <OpenGLES/ES3/gl.h> // Use GL ES 3
#else
#include <GLES3/gl3.h> // Use GL ES 3
#endif
#elif !defined(IMGUI_IMPL_OPENGL_LOADER_CUSTOM)
// Modern desktop OpenGL doesn't have a standard portable header file to load OpenGL function pointers.
// Helper libraries are often used for this purpose! Here we are using our own minimal custom loader based on gl3w.
// In the rest of your app/engine, you can use another loader of your choice (gl3w, glew, glad, glbinding, glext, glLoadGen, etc.).
// If you happen to be developing a new feature for this backend (imgui_impl_opengl3.cpp):
// - You may need to regenerate imgui_impl_opengl3_loader.h to add new symbols. See https://github.com/dearimgui/gl3w_stripped
// - You can temporarily use an unstripped version. See https://github.com/dearimgui/gl3w_stripped/releases
// Changes to this backend using new APIs should be accompanied by a regenerated stripped loader version.
#define IMGL3W_IMPL
#include "imgui_impl_opengl3_loader.h"
#endif
// Vertex arrays are not supported on ES2/WebGL1 unless Emscripten which uses an extension
#ifndef IMGUI_IMPL_OPENGL_ES2
#define IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
#elif defined(__EMSCRIPTEN__)
#define IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
#define glBindVertexArray glBindVertexArrayOES
#define glGenVertexArrays glGenVertexArraysOES
#define glDeleteVertexArrays glDeleteVertexArraysOES
#define GL_VERTEX_ARRAY_BINDING GL_VERTEX_ARRAY_BINDING_OES
#endif
// Desktop GL 2.0+ has glPolygonMode() which GL ES and WebGL don't have.
#ifdef GL_POLYGON_MODE
#define IMGUI_IMPL_HAS_POLYGON_MODE
#endif
// Desktop GL 3.2+ has glDrawElementsBaseVertex() which GL ES and WebGL don't have.
#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && defined(GL_VERSION_3_2)
#define IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET
#endif
// Desktop GL 3.3+ and GL ES 3.0+ have glBindSampler()
#if !defined(IMGUI_IMPL_OPENGL_ES2) && (defined(IMGUI_IMPL_OPENGL_ES3) || defined(GL_VERSION_3_3))
#define IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER
#endif
// Desktop GL 3.1+ has GL_PRIMITIVE_RESTART state
#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && defined(GL_VERSION_3_1)
#define IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART
#endif
// Desktop GL use extension detection
#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3)
#define IMGUI_IMPL_OPENGL_MAY_HAVE_EXTENSIONS
#endif
// [Debugging]
//#define IMGUI_IMPL_OPENGL_DEBUG
#ifdef IMGUI_IMPL_OPENGL_DEBUG
#include <stdio.h>
#define GL_CALL(_CALL) do { _CALL; GLenum gl_err = glGetError(); if (gl_err != 0) fprintf(stderr, "GL error 0x%x returned from '%s'.\n", gl_err, #_CALL); } while (0) // Call with error check
#else
#define GL_CALL(_CALL) _CALL // Call without error check
#endif
// OpenGL Data
struct ImGui_ImplOpenGL3_Data
{
GLuint GlVersion; // Extracted at runtime using GL_MAJOR_VERSION, GL_MINOR_VERSION queries (e.g. 320 for GL 3.2)
char GlslVersionString[32]; // Specified by user or detected based on compile time GL settings.
bool GlProfileIsES2;
bool GlProfileIsES3;
bool GlProfileIsCompat;
GLint GlProfileMask;
GLuint FontTexture;
GLuint ShaderHandle;
GLint AttribLocationTex; // Uniforms location
GLint AttribLocationProjMtx;
GLuint AttribLocationVtxPos; // Vertex attributes location
GLuint AttribLocationVtxUV;
GLuint AttribLocationVtxColor;
unsigned int VboHandle, ElementsHandle;
GLsizeiptr VertexBufferSize;
GLsizeiptr IndexBufferSize;
bool HasClipOrigin;
bool UseBufferSubData;
ImGui_ImplOpenGL3_Data() { memset((void*)this, 0, sizeof(*this)); }
};
// Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
static ImGui_ImplOpenGL3_Data* ImGui_ImplOpenGL3_GetBackendData()
{
return ImGui::GetCurrentContext() ? (ImGui_ImplOpenGL3_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
}
// OpenGL vertex attribute state (for ES 1.0 and ES 2.0 only)
#ifndef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
struct ImGui_ImplOpenGL3_VtxAttribState
{
GLint Enabled, Size, Type, Normalized, Stride;
GLvoid* Ptr;
void GetState(GLint index)
{
glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &Enabled);
glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_SIZE, &Size);
glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_TYPE, &Type);
glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_NORMALIZED, &Normalized);
glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_STRIDE, &Stride);
glGetVertexAttribPointerv(index, GL_VERTEX_ATTRIB_ARRAY_POINTER, &Ptr);
}
void SetState(GLint index)
{
glVertexAttribPointer(index, Size, Type, (GLboolean)Normalized, Stride, Ptr);
if (Enabled) glEnableVertexAttribArray(index); else glDisableVertexAttribArray(index);
}
};
#endif
// Functions
bool ImGui_ImplOpenGL3_Init(const char* glsl_version)
{
ImGuiIO& io = ImGui::GetIO();
IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
// Initialize our loader
#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && !defined(IMGUI_IMPL_OPENGL_LOADER_CUSTOM)
if (imgl3wInit() != 0)
{
fprintf(stderr, "Failed to initialize OpenGL loader!\n");
return false;
}
#endif
// Setup backend capabilities flags
ImGui_ImplOpenGL3_Data* bd = IM_NEW(ImGui_ImplOpenGL3_Data)();
io.BackendRendererUserData = (void*)bd;
io.BackendRendererName = "imgui_impl_opengl3";
// Query for GL version (e.g. 320 for GL 3.2)
#if defined(IMGUI_IMPL_OPENGL_ES2)
// GLES 2
bd->GlVersion = 200;
bd->GlProfileIsES2 = true;
#else
// Desktop or GLES 3
GLint major = 0;
GLint minor = 0;
glGetIntegerv(GL_MAJOR_VERSION, &major);
glGetIntegerv(GL_MINOR_VERSION, &minor);
if (major == 0 && minor == 0)
{
// Query GL_VERSION in desktop GL 2.x, the string will start with "<major>.<minor>"
const char* gl_version = (const char*)glGetString(GL_VERSION);
sscanf(gl_version, "%d.%d", &major, &minor);
}
bd->GlVersion = (GLuint)(major * 100 + minor * 10);
#if defined(GL_CONTEXT_PROFILE_MASK)
if (bd->GlVersion >= 320)
glGetIntegerv(GL_CONTEXT_PROFILE_MASK, &bd->GlProfileMask);
bd->GlProfileIsCompat = (bd->GlProfileMask & GL_CONTEXT_COMPATIBILITY_PROFILE_BIT) != 0;
#endif
#if defined(IMGUI_IMPL_OPENGL_ES3)
bd->GlProfileIsES3 = true;
#endif
bd->UseBufferSubData = false;
/*
// Query vendor to enable glBufferSubData kludge
#ifdef _WIN32
if (const char* vendor = (const char*)glGetString(GL_VENDOR))
if (strncmp(vendor, "Intel", 5) == 0)
bd->UseBufferSubData = true;
#endif
*/
#endif
#ifdef IMGUI_IMPL_OPENGL_DEBUG
printf("GlVersion = %d\nGlProfileIsCompat = %d\nGlProfileMask = 0x%X\nGlProfileIsES2 = %d, GlProfileIsES3 = %d\nGL_VENDOR = '%s'\nGL_RENDERER = '%s'\n", bd->GlVersion, bd->GlProfileIsCompat, bd->GlProfileMask, bd->GlProfileIsES2, bd->GlProfileIsES3, (const char*)glGetString(GL_VENDOR), (const char*)glGetString(GL_RENDERER)); // [DEBUG]
#endif
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET
if (bd->GlVersion >= 320)
io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
#endif
// Store GLSL version string so we can refer to it later in case we recreate shaders.
// Note: GLSL version is NOT the same as GL version. Leave this to nullptr if unsure.
if (glsl_version == nullptr)
{
#if defined(IMGUI_IMPL_OPENGL_ES2)
glsl_version = "#version 100";
#elif defined(IMGUI_IMPL_OPENGL_ES3)
glsl_version = "#version 300 es";
#elif defined(__APPLE__)
glsl_version = "#version 150";
#else
glsl_version = "#version 130";
#endif
}
IM_ASSERT((int)strlen(glsl_version) + 2 < IM_ARRAYSIZE(bd->GlslVersionString));
strcpy(bd->GlslVersionString, glsl_version);
strcat(bd->GlslVersionString, "\n");
// Make an arbitrary GL call (we don't actually need the result)
// IF YOU GET A CRASH HERE: it probably means the OpenGL function loader didn't do its job. Let us know!
GLint current_texture;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &current_texture);
// Detect extensions we support
bd->HasClipOrigin = (bd->GlVersion >= 450);
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_EXTENSIONS
GLint num_extensions = 0;
glGetIntegerv(GL_NUM_EXTENSIONS, &num_extensions);
for (GLint i = 0; i < num_extensions; i++)
{
const char* extension = (const char*)glGetStringi(GL_EXTENSIONS, i);
if (extension != nullptr && strcmp(extension, "GL_ARB_clip_control") == 0)
bd->HasClipOrigin = true;
}
#endif
return true;
}
void ImGui_ImplOpenGL3_Shutdown()
{
ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
ImGuiIO& io = ImGui::GetIO();
ImGui_ImplOpenGL3_DestroyDeviceObjects();
io.BackendRendererName = nullptr;
io.BackendRendererUserData = nullptr;
io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset;
IM_DELETE(bd);
}
void ImGui_ImplOpenGL3_NewFrame()
{
ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplOpenGL3_Init()?");
if (!bd->ShaderHandle)
ImGui_ImplOpenGL3_CreateDeviceObjects();
}
static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_width, int fb_height, GLuint vertex_array_object)
{
ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
// Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, polygon fill
glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glDisable(GL_STENCIL_TEST);
glEnable(GL_SCISSOR_TEST);
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART
if (bd->GlVersion >= 310)
glDisable(GL_PRIMITIVE_RESTART);
#endif
#ifdef IMGUI_IMPL_HAS_POLYGON_MODE
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
#endif
// Support for GL 4.5 rarely used glClipControl(GL_UPPER_LEFT)
#if defined(GL_CLIP_ORIGIN)
bool clip_origin_lower_left = true;
if (bd->HasClipOrigin)
{
GLenum current_clip_origin = 0; glGetIntegerv(GL_CLIP_ORIGIN, (GLint*)&current_clip_origin);
if (current_clip_origin == GL_UPPER_LEFT)
clip_origin_lower_left = false;
}
#endif
// Setup viewport, orthographic projection matrix
// Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps.
GL_CALL(glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height));
float L = draw_data->DisplayPos.x;
float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
float T = draw_data->DisplayPos.y;
float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
#if defined(GL_CLIP_ORIGIN)
if (!clip_origin_lower_left) { float tmp = T; T = B; B = tmp; } // Swap top and bottom if origin is upper left
#endif
const float ortho_projection[4][4] =
{
{ 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
{ 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
{ 0.0f, 0.0f, -1.0f, 0.0f },
{ (R+L)/(L-R), (T+B)/(B-T), 0.0f, 1.0f },
};
glUseProgram(bd->ShaderHandle);
glUniform1i(bd->AttribLocationTex, 0);
glUniformMatrix4fv(bd->AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]);
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER
if (bd->GlVersion >= 330 || bd->GlProfileIsES3)
glBindSampler(0, 0); // We use combined texture/sampler state. Applications using GL 3.3 and GL ES 3.0 may set that otherwise.
#endif
(void)vertex_array_object;
#ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
glBindVertexArray(vertex_array_object);
#endif
// Bind vertex/index buffers and setup attributes for ImDrawVert
GL_CALL(glBindBuffer(GL_ARRAY_BUFFER, bd->VboHandle));
GL_CALL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bd->ElementsHandle));
GL_CALL(glEnableVertexAttribArray(bd->AttribLocationVtxPos));
GL_CALL(glEnableVertexAttribArray(bd->AttribLocationVtxUV));
GL_CALL(glEnableVertexAttribArray(bd->AttribLocationVtxColor));
GL_CALL(glVertexAttribPointer(bd->AttribLocationVtxPos, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)offsetof(ImDrawVert, pos)));
GL_CALL(glVertexAttribPointer(bd->AttribLocationVtxUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)offsetof(ImDrawVert, uv)));
GL_CALL(glVertexAttribPointer(bd->AttribLocationVtxColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)offsetof(ImDrawVert, col)));
}
// OpenGL3 Render function.
// Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly.
// This is in order to be able to run within an OpenGL engine that doesn't do so.
void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data)
{
// Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
if (fb_width <= 0 || fb_height <= 0)
return;
ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
// Backup GL state
GLenum last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, (GLint*)&last_active_texture);
glActiveTexture(GL_TEXTURE0);
GLuint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, (GLint*)&last_program);
GLuint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, (GLint*)&last_texture);
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER
GLuint last_sampler; if (bd->GlVersion >= 330 || bd->GlProfileIsES3) { glGetIntegerv(GL_SAMPLER_BINDING, (GLint*)&last_sampler); } else { last_sampler = 0; }
#endif
GLuint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, (GLint*)&last_array_buffer);
#ifndef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
// This is part of VAO on OpenGL 3.0+ and OpenGL ES 3.0+.
GLint last_element_array_buffer; glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer);
ImGui_ImplOpenGL3_VtxAttribState last_vtx_attrib_state_pos; last_vtx_attrib_state_pos.GetState(bd->AttribLocationVtxPos);
ImGui_ImplOpenGL3_VtxAttribState last_vtx_attrib_state_uv; last_vtx_attrib_state_uv.GetState(bd->AttribLocationVtxUV);
ImGui_ImplOpenGL3_VtxAttribState last_vtx_attrib_state_color; last_vtx_attrib_state_color.GetState(bd->AttribLocationVtxColor);
#endif
#ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
GLuint last_vertex_array_object; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, (GLint*)&last_vertex_array_object);
#endif
#ifdef IMGUI_IMPL_HAS_POLYGON_MODE
GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode);
#endif
GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
GLenum last_blend_src_rgb; glGetIntegerv(GL_BLEND_SRC_RGB, (GLint*)&last_blend_src_rgb);
GLenum last_blend_dst_rgb; glGetIntegerv(GL_BLEND_DST_RGB, (GLint*)&last_blend_dst_rgb);
GLenum last_blend_src_alpha; glGetIntegerv(GL_BLEND_SRC_ALPHA, (GLint*)&last_blend_src_alpha);
GLenum last_blend_dst_alpha; glGetIntegerv(GL_BLEND_DST_ALPHA, (GLint*)&last_blend_dst_alpha);
GLenum last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, (GLint*)&last_blend_equation_rgb);
GLenum last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, (GLint*)&last_blend_equation_alpha);
GLboolean last_enable_blend = glIsEnabled(GL_BLEND);
GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE);
GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST);
GLboolean last_enable_stencil_test = glIsEnabled(GL_STENCIL_TEST);
GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST);
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART
GLboolean last_enable_primitive_restart = (bd->GlVersion >= 310) ? glIsEnabled(GL_PRIMITIVE_RESTART) : GL_FALSE;
#endif
// Setup desired GL state
// Recreate the VAO every time (this is to easily allow multiple GL contexts to be rendered to. VAO are not shared among GL contexts)
// The renderer would actually work without any VAO bound, but then our VertexAttrib calls would overwrite the default one currently bound.
GLuint vertex_array_object = 0;
#ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
GL_CALL(glGenVertexArrays(1, &vertex_array_object));
#endif
ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object);
// Will project scissor/clipping rectangles into framebuffer space
ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2)
// Render command lists
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
// Upload vertex/index buffers
// - OpenGL drivers are in a very sorry state nowadays....
// During 2021 we attempted to switch from glBufferData() to orphaning+glBufferSubData() following reports
// of leaks on Intel GPU when using multi-viewports on Windows.
// - After this we kept hearing of various display corruptions issues. We started disabling on non-Intel GPU, but issues still got reported on Intel.
// - We are now back to using exclusively glBufferData(). So bd->UseBufferSubData IS ALWAYS FALSE in this code.
// We are keeping the old code path for a while in case people finding new issues may want to test the bd->UseBufferSubData path.
// - See https://github.com/ocornut/imgui/issues/4468 and please report any corruption issues.
const GLsizeiptr vtx_buffer_size = (GLsizeiptr)cmd_list->VtxBuffer.Size * (int)sizeof(ImDrawVert);
const GLsizeiptr idx_buffer_size = (GLsizeiptr)cmd_list->IdxBuffer.Size * (int)sizeof(ImDrawIdx);
if (bd->UseBufferSubData)
{
if (bd->VertexBufferSize < vtx_buffer_size)
{
bd->VertexBufferSize = vtx_buffer_size;
GL_CALL(glBufferData(GL_ARRAY_BUFFER, bd->VertexBufferSize, nullptr, GL_STREAM_DRAW));
}
if (bd->IndexBufferSize < idx_buffer_size)
{
bd->IndexBufferSize = idx_buffer_size;
GL_CALL(glBufferData(GL_ELEMENT_ARRAY_BUFFER, bd->IndexBufferSize, nullptr, GL_STREAM_DRAW));
}
GL_CALL(glBufferSubData(GL_ARRAY_BUFFER, 0, vtx_buffer_size, (const GLvoid*)cmd_list->VtxBuffer.Data));
GL_CALL(glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, idx_buffer_size, (const GLvoid*)cmd_list->IdxBuffer.Data));
}
else
{
GL_CALL(glBufferData(GL_ARRAY_BUFFER, vtx_buffer_size, (const GLvoid*)cmd_list->VtxBuffer.Data, GL_STREAM_DRAW));
GL_CALL(glBufferData(GL_ELEMENT_ARRAY_BUFFER, idx_buffer_size, (const GLvoid*)cmd_list->IdxBuffer.Data, GL_STREAM_DRAW));
}
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
{
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
if (pcmd->UserCallback != nullptr)
{
// User callback, registered via ImDrawList::AddCallback()
// (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object);
else
pcmd->UserCallback(cmd_list, pcmd);
}
else
{
// Project scissor/clipping rectangles into framebuffer space
ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
continue;
// Apply scissor/clipping rectangle (Y is inverted in OpenGL)
GL_CALL(glScissor((int)clip_min.x, (int)((float)fb_height - clip_max.y), (int)(clip_max.x - clip_min.x), (int)(clip_max.y - clip_min.y)));
// Bind texture, Draw
GL_CALL(glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->GetTexID()));
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET
if (bd->GlVersion >= 320)
GL_CALL(glDrawElementsBaseVertex(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)(intptr_t)(pcmd->IdxOffset * sizeof(ImDrawIdx)), (GLint)pcmd->VtxOffset));
else
#endif
GL_CALL(glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)(intptr_t)(pcmd->IdxOffset * sizeof(ImDrawIdx))));
}
}
}
// Destroy the temporary VAO
#ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
GL_CALL(glDeleteVertexArrays(1, &vertex_array_object));
#endif
// Restore modified GL state
// This "glIsProgram()" check is required because if the program is "pending deletion" at the time of binding backup, it will have been deleted by now and will cause an OpenGL error. See #6220.
if (last_program == 0 || glIsProgram(last_program)) glUseProgram(last_program);
glBindTexture(GL_TEXTURE_2D, last_texture);
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER
if (bd->GlVersion >= 330 || bd->GlProfileIsES3)
glBindSampler(0, last_sampler);
#endif
glActiveTexture(last_active_texture);
#ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
glBindVertexArray(last_vertex_array_object);
#endif
glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
#ifndef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer);
last_vtx_attrib_state_pos.SetState(bd->AttribLocationVtxPos);
last_vtx_attrib_state_uv.SetState(bd->AttribLocationVtxUV);
last_vtx_attrib_state_color.SetState(bd->AttribLocationVtxColor);
#endif
glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha);
glBlendFuncSeparate(last_blend_src_rgb, last_blend_dst_rgb, last_blend_src_alpha, last_blend_dst_alpha);
if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND);
if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE);
if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST);
if (last_enable_stencil_test) glEnable(GL_STENCIL_TEST); else glDisable(GL_STENCIL_TEST);
if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST);
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART
if (bd->GlVersion >= 310) { if (last_enable_primitive_restart) glEnable(GL_PRIMITIVE_RESTART); else glDisable(GL_PRIMITIVE_RESTART); }
#endif
#ifdef IMGUI_IMPL_HAS_POLYGON_MODE
// Desktop OpenGL 3.0 and OpenGL 3.1 had separate polygon draw modes for front-facing and back-facing faces of polygons
if (bd->GlVersion <= 310 || bd->GlProfileIsCompat)
{
glPolygonMode(GL_FRONT, (GLenum)last_polygon_mode[0]);
glPolygonMode(GL_BACK, (GLenum)last_polygon_mode[1]);
}
else
{
glPolygonMode(GL_FRONT_AND_BACK, (GLenum)last_polygon_mode[0]);
}
#endif // IMGUI_IMPL_HAS_POLYGON_MODE
glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]);
(void)bd; // Not all compilation paths use this
}
bool ImGui_ImplOpenGL3_CreateFontsTexture()
{
ImGuiIO& io = ImGui::GetIO();
ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
// Build texture atlas
unsigned char* pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory.
// Upload texture to graphics system
// (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
GLint last_texture;
GL_CALL(glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture));
GL_CALL(glGenTextures(1, &bd->FontTexture));
GL_CALL(glBindTexture(GL_TEXTURE_2D, bd->FontTexture));
GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
#ifdef GL_UNPACK_ROW_LENGTH // Not on WebGL/ES
GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0));
#endif
GL_CALL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels));
// Store our identifier
io.Fonts->SetTexID((ImTextureID)(intptr_t)bd->FontTexture);
// Restore state
GL_CALL(glBindTexture(GL_TEXTURE_2D, last_texture));
return true;
}
void ImGui_ImplOpenGL3_DestroyFontsTexture()
{
ImGuiIO& io = ImGui::GetIO();
ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
if (bd->FontTexture)
{
glDeleteTextures(1, &bd->FontTexture);
io.Fonts->SetTexID(0);
bd->FontTexture = 0;
}
}
// If you get an error please report on github. You may try different GL context version or GLSL version. See GL<>GLSL version table at the top of this file.
static bool CheckShader(GLuint handle, const char* desc)
{
ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
GLint status = 0, log_length = 0;
glGetShaderiv(handle, GL_COMPILE_STATUS, &status);
glGetShaderiv(handle, GL_INFO_LOG_LENGTH, &log_length);
if ((GLboolean)status == GL_FALSE)
fprintf(stderr, "ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to compile %s! With GLSL: %s\n", desc, bd->GlslVersionString);
if (log_length > 1)
{
ImVector<char> buf;
buf.resize((int)(log_length + 1));
glGetShaderInfoLog(handle, log_length, nullptr, (GLchar*)buf.begin());
fprintf(stderr, "%s\n", buf.begin());
}
return (GLboolean)status == GL_TRUE;
}
// If you get an error please report on GitHub. You may try different GL context version or GLSL version.
static bool CheckProgram(GLuint handle, const char* desc)
{
ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
GLint status = 0, log_length = 0;
glGetProgramiv(handle, GL_LINK_STATUS, &status);
glGetProgramiv(handle, GL_INFO_LOG_LENGTH, &log_length);
if ((GLboolean)status == GL_FALSE)
fprintf(stderr, "ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to link %s! With GLSL %s\n", desc, bd->GlslVersionString);
if (log_length > 1)
{
ImVector<char> buf;
buf.resize((int)(log_length + 1));
glGetProgramInfoLog(handle, log_length, nullptr, (GLchar*)buf.begin());
fprintf(stderr, "%s\n", buf.begin());
}
return (GLboolean)status == GL_TRUE;
}
bool ImGui_ImplOpenGL3_CreateDeviceObjects()
{
ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
// Backup GL state
GLint last_texture, last_array_buffer;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
#ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
GLint last_vertex_array;
glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
#endif
// Parse GLSL version string
int glsl_version = 130;
sscanf(bd->GlslVersionString, "#version %d", &glsl_version);
const GLchar* vertex_shader_glsl_120 =
"uniform mat4 ProjMtx;\n"
"attribute vec2 Position;\n"
"attribute vec2 UV;\n"
"attribute vec4 Color;\n"
"varying vec2 Frag_UV;\n"
"varying vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Color = Color;\n"
" gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
"}\n";
const GLchar* vertex_shader_glsl_130 =
"uniform mat4 ProjMtx;\n"
"in vec2 Position;\n"
"in vec2 UV;\n"
"in vec4 Color;\n"
"out vec2 Frag_UV;\n"
"out vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Color = Color;\n"
" gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
"}\n";
const GLchar* vertex_shader_glsl_300_es =
"precision highp float;\n"
"layout (location = 0) in vec2 Position;\n"
"layout (location = 1) in vec2 UV;\n"
"layout (location = 2) in vec4 Color;\n"
"uniform mat4 ProjMtx;\n"
"out vec2 Frag_UV;\n"
"out vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Color = Color;\n"
" gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
"}\n";
const GLchar* vertex_shader_glsl_410_core =
"layout (location = 0) in vec2 Position;\n"
"layout (location = 1) in vec2 UV;\n"
"layout (location = 2) in vec4 Color;\n"
"uniform mat4 ProjMtx;\n"
"out vec2 Frag_UV;\n"
"out vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Color = Color;\n"
" gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
"}\n";
const GLchar* fragment_shader_glsl_120 =
"#ifdef GL_ES\n"
" precision mediump float;\n"
"#endif\n"
"uniform sampler2D Texture;\n"
"varying vec2 Frag_UV;\n"
"varying vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" gl_FragColor = Frag_Color * texture2D(Texture, Frag_UV.st);\n"
"}\n";
const GLchar* fragment_shader_glsl_130 =
"uniform sampler2D Texture;\n"
"in vec2 Frag_UV;\n"
"in vec4 Frag_Color;\n"
"out vec4 Out_Color;\n"
"void main()\n"
"{\n"
" Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
"}\n";
const GLchar* fragment_shader_glsl_300_es =
"precision mediump float;\n"
"uniform sampler2D Texture;\n"
"in vec2 Frag_UV;\n"
"in vec4 Frag_Color;\n"
"layout (location = 0) out vec4 Out_Color;\n"
"void main()\n"
"{\n"
" Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
"}\n";
const GLchar* fragment_shader_glsl_410_core =
"in vec2 Frag_UV;\n"
"in vec4 Frag_Color;\n"
"uniform sampler2D Texture;\n"
"layout (location = 0) out vec4 Out_Color;\n"
"void main()\n"
"{\n"
" Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
"}\n";
// Select shaders matching our GLSL versions
const GLchar* vertex_shader = nullptr;
const GLchar* fragment_shader = nullptr;
if (glsl_version < 130)
{
vertex_shader = vertex_shader_glsl_120;
fragment_shader = fragment_shader_glsl_120;
}
else if (glsl_version >= 410)
{
vertex_shader = vertex_shader_glsl_410_core;
fragment_shader = fragment_shader_glsl_410_core;
}
else if (glsl_version == 300)
{
vertex_shader = vertex_shader_glsl_300_es;
fragment_shader = fragment_shader_glsl_300_es;
}
else
{
vertex_shader = vertex_shader_glsl_130;
fragment_shader = fragment_shader_glsl_130;
}
// Create shaders
const GLchar* vertex_shader_with_version[2] = { bd->GlslVersionString, vertex_shader };
GLuint vert_handle = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vert_handle, 2, vertex_shader_with_version, nullptr);
glCompileShader(vert_handle);
CheckShader(vert_handle, "vertex shader");
const GLchar* fragment_shader_with_version[2] = { bd->GlslVersionString, fragment_shader };
GLuint frag_handle = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(frag_handle, 2, fragment_shader_with_version, nullptr);
glCompileShader(frag_handle);
CheckShader(frag_handle, "fragment shader");
// Link
bd->ShaderHandle = glCreateProgram();
glAttachShader(bd->ShaderHandle, vert_handle);
glAttachShader(bd->ShaderHandle, frag_handle);
glLinkProgram(bd->ShaderHandle);
CheckProgram(bd->ShaderHandle, "shader program");
glDetachShader(bd->ShaderHandle, vert_handle);
glDetachShader(bd->ShaderHandle, frag_handle);
glDeleteShader(vert_handle);
glDeleteShader(frag_handle);
bd->AttribLocationTex = glGetUniformLocation(bd->ShaderHandle, "Texture");
bd->AttribLocationProjMtx = glGetUniformLocation(bd->ShaderHandle, "ProjMtx");
bd->AttribLocationVtxPos = (GLuint)glGetAttribLocation(bd->ShaderHandle, "Position");
bd->AttribLocationVtxUV = (GLuint)glGetAttribLocation(bd->ShaderHandle, "UV");
bd->AttribLocationVtxColor = (GLuint)glGetAttribLocation(bd->ShaderHandle, "Color");
// Create buffers
glGenBuffers(1, &bd->VboHandle);
glGenBuffers(1, &bd->ElementsHandle);
ImGui_ImplOpenGL3_CreateFontsTexture();
// Restore modified GL state
glBindTexture(GL_TEXTURE_2D, last_texture);
glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
#ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
glBindVertexArray(last_vertex_array);
#endif
return true;
}
void ImGui_ImplOpenGL3_DestroyDeviceObjects()
{
ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
if (bd->VboHandle) { glDeleteBuffers(1, &bd->VboHandle); bd->VboHandle = 0; }
if (bd->ElementsHandle) { glDeleteBuffers(1, &bd->ElementsHandle); bd->ElementsHandle = 0; }
if (bd->ShaderHandle) { glDeleteProgram(bd->ShaderHandle); bd->ShaderHandle = 0; }
ImGui_ImplOpenGL3_DestroyFontsTexture();
}
//-----------------------------------------------------------------------------
#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
#endif // #ifndef IMGUI_DISABLE
-66
View File
@@ -1,66 +0,0 @@
// dear imgui: Renderer Backend for modern OpenGL with shaders / programmatic pipeline
// - Desktop GL: 2.x 3.x 4.x
// - Embedded GL: ES 2.0 (WebGL 1.0), ES 3.0 (WebGL 2.0)
// This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..)
// Implemented features:
// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID!
// [x] Renderer: Large meshes support (64k+ vertices) with 16-bit indices (Desktop OpenGL only).
// About WebGL/ES:
// - You need to '#define IMGUI_IMPL_OPENGL_ES2' or '#define IMGUI_IMPL_OPENGL_ES3' to use WebGL or OpenGL ES.
// - This is done automatically on iOS, Android and Emscripten targets.
// - For other targets, the define needs to be visible from the imgui_impl_opengl3.cpp compilation unit. If unsure, define globally or in imconfig.h.
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// About GLSL version:
// The 'glsl_version' initialization parameter should be nullptr (default) or a "#version XXX" string.
// On computer platform the GLSL version default to "#version 130". On OpenGL ES 3 platform it defaults to "#version 300 es"
// Only override if your GL version doesn't handle this GLSL version. See GLSL version table at the top of imgui_impl_opengl3.cpp.
#pragma once
#include "imgui.h" // IMGUI_IMPL_API
#ifndef IMGUI_DISABLE
// Backend API
IMGUI_IMPL_API bool ImGui_ImplOpenGL3_Init(const char* glsl_version = nullptr);
IMGUI_IMPL_API void ImGui_ImplOpenGL3_Shutdown();
IMGUI_IMPL_API void ImGui_ImplOpenGL3_NewFrame();
IMGUI_IMPL_API void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data);
// (Optional) Called by Init/NewFrame/Shutdown
IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateFontsTexture();
IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyFontsTexture();
IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateDeviceObjects();
IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyDeviceObjects();
// Specific OpenGL ES versions
//#define IMGUI_IMPL_OPENGL_ES2 // Auto-detected on Emscripten
//#define IMGUI_IMPL_OPENGL_ES3 // Auto-detected on iOS/Android
// You can explicitly select GLES2 or GLES3 API by using one of the '#define IMGUI_IMPL_OPENGL_LOADER_XXX' in imconfig.h or compiler command-line.
#if !defined(IMGUI_IMPL_OPENGL_ES2) \
&& !defined(IMGUI_IMPL_OPENGL_ES3)
// Try to detect GLES on matching platforms
#if defined(__APPLE__)
#include <TargetConditionals.h>
#endif
#if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV)) || (defined(__ANDROID__))
#define IMGUI_IMPL_OPENGL_ES3 // iOS, Android -> GL ES 3, "#version 300 es"
#elif defined(__EMSCRIPTEN__) || defined(__amigaos4__)
#define IMGUI_IMPL_OPENGL_ES2 // Emscripten -> GL ES 2, "#version 100"
#else
// Otherwise imgui_impl_opengl3_loader.h will be used.
#endif
#endif
#endif // #ifndef IMGUI_DISABLE
-814
View File
@@ -1,814 +0,0 @@
//-----------------------------------------------------------------------------
// About imgui_impl_opengl3_loader.h:
//
// We embed our own OpenGL loader to not require user to provide their own or to have to use ours,
// which proved to be endless problems for users.
// Our loader is custom-generated, based on gl3w but automatically filtered to only include
// enums/functions that we use in our imgui_impl_opengl3.cpp source file in order to be small.
//
// YOU SHOULD NOT NEED TO INCLUDE/USE THIS DIRECTLY. THIS IS USED BY imgui_impl_opengl3.cpp ONLY.
// THE REST OF YOUR APP SHOULD USE A DIFFERENT GL LOADER: ANY GL LOADER OF YOUR CHOICE.
//
// IF YOU GET BUILD ERRORS IN THIS FILE (commonly macro redefinitions or function redefinitions):
// IT LIKELY MEANS THAT YOU ARE BUILDING 'imgui_impl_opengl3.cpp' OR INCUDING 'imgui_impl_opengl3_loader.h'
// IN THE SAME COMPILATION UNIT AS ONE OF YOUR FILE WHICH IS USING A THIRD-PARTY OPENGL LOADER.
// (e.g. COULD HAPPEN IF YOU ARE DOING A UNITY/JUMBO BUILD, OR INCLUDING .CPP FILES FROM OTHERS)
// YOU SHOULD NOT BUILD BOTH IN THE SAME COMPILATION UNIT.
// BUT IF YOU REALLY WANT TO, you can '#define IMGUI_IMPL_OPENGL_LOADER_CUSTOM' and imgui_impl_opengl3.cpp
// WILL NOT BE USING OUR LOADER, AND INSTEAD EXPECT ANOTHER/YOUR LOADER TO BE AVAILABLE IN THE COMPILATION UNIT.
//
// Regenerate with:
// python gl3w_gen.py --output ../imgui/backends/imgui_impl_opengl3_loader.h --ref ../imgui/backends/imgui_impl_opengl3.cpp ./extra_symbols.txt
//
// More info:
// https://github.com/dearimgui/gl3w_stripped
// https://github.com/ocornut/imgui/issues/4445
//-----------------------------------------------------------------------------
/*
* This file was generated with gl3w_gen.py, part of imgl3w
* (hosted at https://github.com/dearimgui/gl3w_stripped)
*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef __gl3w_h_
#define __gl3w_h_
// Adapted from KHR/khrplatform.h to avoid including entire file.
#ifndef __khrplatform_h_
typedef float khronos_float_t;
typedef signed char khronos_int8_t;
typedef unsigned char khronos_uint8_t;
typedef signed short int khronos_int16_t;
typedef unsigned short int khronos_uint16_t;
#ifdef _WIN64
typedef signed long long int khronos_intptr_t;
typedef signed long long int khronos_ssize_t;
#else
typedef signed long int khronos_intptr_t;
typedef signed long int khronos_ssize_t;
#endif
#if defined(_MSC_VER) && !defined(__clang__)
typedef signed __int64 khronos_int64_t;
typedef unsigned __int64 khronos_uint64_t;
#elif (defined(__clang__) || defined(__GNUC__)) && (__cplusplus < 201100)
#include <stdint.h>
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#else
typedef signed long long khronos_int64_t;
typedef unsigned long long khronos_uint64_t;
#endif
#endif // __khrplatform_h_
#ifndef __gl_glcorearb_h_
#define __gl_glcorearb_h_ 1
#ifdef __cplusplus
extern "C" {
#endif
/*
** Copyright 2013-2020 The Khronos Group Inc.
** SPDX-License-Identifier: MIT
**
** This header is generated from the Khronos OpenGL / OpenGL ES XML
** API Registry. The current version of the Registry, generator scripts
** used to make the header, and the header can be found at
** https://github.com/KhronosGroup/OpenGL-Registry
*/
#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1
#endif
#include <windows.h>
#endif
#ifndef APIENTRY
#define APIENTRY
#endif
#ifndef APIENTRYP
#define APIENTRYP APIENTRY *
#endif
#ifndef GLAPI
#define GLAPI extern
#endif
/* glcorearb.h is for use with OpenGL core profile implementations.
** It should should be placed in the same directory as gl.h and
** included as <GL/glcorearb.h>.
**
** glcorearb.h includes only APIs in the latest OpenGL core profile
** implementation together with APIs in newer ARB extensions which
** can be supported by the core profile. It does not, and never will
** include functionality removed from the core profile, such as
** fixed-function vertex and fragment processing.
**
** Do not #include both <GL/glcorearb.h> and either of <GL/gl.h> or
** <GL/glext.h> in the same source file.
*/
/* Generated C header for:
* API: gl
* Profile: core
* Versions considered: .*
* Versions emitted: .*
* Default extensions included: glcore
* Additional extensions included: _nomatch_^
* Extensions removed: _nomatch_^
*/
#ifndef GL_VERSION_1_0
typedef void GLvoid;
typedef unsigned int GLenum;
typedef khronos_float_t GLfloat;
typedef int GLint;
typedef int GLsizei;
typedef unsigned int GLbitfield;
typedef double GLdouble;
typedef unsigned int GLuint;
typedef unsigned char GLboolean;
typedef khronos_uint8_t GLubyte;
#define GL_COLOR_BUFFER_BIT 0x00004000
#define GL_FALSE 0
#define GL_TRUE 1
#define GL_TRIANGLES 0x0004
#define GL_ONE 1
#define GL_SRC_ALPHA 0x0302
#define GL_ONE_MINUS_SRC_ALPHA 0x0303
#define GL_FRONT 0x0404
#define GL_BACK 0x0405
#define GL_FRONT_AND_BACK 0x0408
#define GL_POLYGON_MODE 0x0B40
#define GL_CULL_FACE 0x0B44
#define GL_DEPTH_TEST 0x0B71
#define GL_STENCIL_TEST 0x0B90
#define GL_VIEWPORT 0x0BA2
#define GL_BLEND 0x0BE2
#define GL_SCISSOR_BOX 0x0C10
#define GL_SCISSOR_TEST 0x0C11
#define GL_UNPACK_ROW_LENGTH 0x0CF2
#define GL_PACK_ALIGNMENT 0x0D05
#define GL_TEXTURE_2D 0x0DE1
#define GL_UNSIGNED_BYTE 0x1401
#define GL_UNSIGNED_SHORT 0x1403
#define GL_UNSIGNED_INT 0x1405
#define GL_FLOAT 0x1406
#define GL_RGBA 0x1908
#define GL_FILL 0x1B02
#define GL_VENDOR 0x1F00
#define GL_RENDERER 0x1F01
#define GL_VERSION 0x1F02
#define GL_EXTENSIONS 0x1F03
#define GL_LINEAR 0x2601
#define GL_TEXTURE_MAG_FILTER 0x2800
#define GL_TEXTURE_MIN_FILTER 0x2801
typedef void (APIENTRYP PFNGLPOLYGONMODEPROC) (GLenum face, GLenum mode);
typedef void (APIENTRYP PFNGLSCISSORPROC) (GLint x, GLint y, GLsizei width, GLsizei height);
typedef void (APIENTRYP PFNGLTEXPARAMETERIPROC) (GLenum target, GLenum pname, GLint param);
typedef void (APIENTRYP PFNGLTEXIMAGE2DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels);
typedef void (APIENTRYP PFNGLCLEARPROC) (GLbitfield mask);
typedef void (APIENTRYP PFNGLCLEARCOLORPROC) (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
typedef void (APIENTRYP PFNGLDISABLEPROC) (GLenum cap);
typedef void (APIENTRYP PFNGLENABLEPROC) (GLenum cap);
typedef void (APIENTRYP PFNGLFLUSHPROC) (void);
typedef void (APIENTRYP PFNGLPIXELSTOREIPROC) (GLenum pname, GLint param);
typedef void (APIENTRYP PFNGLREADPIXELSPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels);
typedef GLenum (APIENTRYP PFNGLGETERRORPROC) (void);
typedef void (APIENTRYP PFNGLGETINTEGERVPROC) (GLenum pname, GLint *data);
typedef const GLubyte *(APIENTRYP PFNGLGETSTRINGPROC) (GLenum name);
typedef GLboolean (APIENTRYP PFNGLISENABLEDPROC) (GLenum cap);
typedef void (APIENTRYP PFNGLVIEWPORTPROC) (GLint x, GLint y, GLsizei width, GLsizei height);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI void APIENTRY glPolygonMode (GLenum face, GLenum mode);
GLAPI void APIENTRY glScissor (GLint x, GLint y, GLsizei width, GLsizei height);
GLAPI void APIENTRY glTexParameteri (GLenum target, GLenum pname, GLint param);
GLAPI void APIENTRY glTexImage2D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels);
GLAPI void APIENTRY glClear (GLbitfield mask);
GLAPI void APIENTRY glClearColor (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
GLAPI void APIENTRY glDisable (GLenum cap);
GLAPI void APIENTRY glEnable (GLenum cap);
GLAPI void APIENTRY glFlush (void);
GLAPI void APIENTRY glPixelStorei (GLenum pname, GLint param);
GLAPI void APIENTRY glReadPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels);
GLAPI GLenum APIENTRY glGetError (void);
GLAPI void APIENTRY glGetIntegerv (GLenum pname, GLint *data);
GLAPI const GLubyte *APIENTRY glGetString (GLenum name);
GLAPI GLboolean APIENTRY glIsEnabled (GLenum cap);
GLAPI void APIENTRY glViewport (GLint x, GLint y, GLsizei width, GLsizei height);
#endif
#endif /* GL_VERSION_1_0 */
#ifndef GL_VERSION_1_1
typedef khronos_float_t GLclampf;
typedef double GLclampd;
#define GL_TEXTURE_BINDING_2D 0x8069
typedef void (APIENTRYP PFNGLDRAWELEMENTSPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices);
typedef void (APIENTRYP PFNGLBINDTEXTUREPROC) (GLenum target, GLuint texture);
typedef void (APIENTRYP PFNGLDELETETEXTURESPROC) (GLsizei n, const GLuint *textures);
typedef void (APIENTRYP PFNGLGENTEXTURESPROC) (GLsizei n, GLuint *textures);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI void APIENTRY glDrawElements (GLenum mode, GLsizei count, GLenum type, const void *indices);
GLAPI void APIENTRY glBindTexture (GLenum target, GLuint texture);
GLAPI void APIENTRY glDeleteTextures (GLsizei n, const GLuint *textures);
GLAPI void APIENTRY glGenTextures (GLsizei n, GLuint *textures);
#endif
#endif /* GL_VERSION_1_1 */
#ifndef GL_VERSION_1_3
#define GL_TEXTURE0 0x84C0
#define GL_ACTIVE_TEXTURE 0x84E0
typedef void (APIENTRYP PFNGLACTIVETEXTUREPROC) (GLenum texture);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI void APIENTRY glActiveTexture (GLenum texture);
#endif
#endif /* GL_VERSION_1_3 */
#ifndef GL_VERSION_1_4
#define GL_BLEND_DST_RGB 0x80C8
#define GL_BLEND_SRC_RGB 0x80C9
#define GL_BLEND_DST_ALPHA 0x80CA
#define GL_BLEND_SRC_ALPHA 0x80CB
#define GL_FUNC_ADD 0x8006
typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
typedef void (APIENTRYP PFNGLBLENDEQUATIONPROC) (GLenum mode);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI void APIENTRY glBlendFuncSeparate (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
GLAPI void APIENTRY glBlendEquation (GLenum mode);
#endif
#endif /* GL_VERSION_1_4 */
#ifndef GL_VERSION_1_5
typedef khronos_ssize_t GLsizeiptr;
typedef khronos_intptr_t GLintptr;
#define GL_ARRAY_BUFFER 0x8892
#define GL_ELEMENT_ARRAY_BUFFER 0x8893
#define GL_ARRAY_BUFFER_BINDING 0x8894
#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895
#define GL_STREAM_DRAW 0x88E0
typedef void (APIENTRYP PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer);
typedef void (APIENTRYP PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint *buffers);
typedef void (APIENTRYP PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers);
typedef void (APIENTRYP PFNGLBUFFERDATAPROC) (GLenum target, GLsizeiptr size, const void *data, GLenum usage);
typedef void (APIENTRYP PFNGLBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, const void *data);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI void APIENTRY glBindBuffer (GLenum target, GLuint buffer);
GLAPI void APIENTRY glDeleteBuffers (GLsizei n, const GLuint *buffers);
GLAPI void APIENTRY glGenBuffers (GLsizei n, GLuint *buffers);
GLAPI void APIENTRY glBufferData (GLenum target, GLsizeiptr size, const void *data, GLenum usage);
GLAPI void APIENTRY glBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, const void *data);
#endif
#endif /* GL_VERSION_1_5 */
#ifndef GL_VERSION_2_0
typedef char GLchar;
typedef khronos_int16_t GLshort;
typedef khronos_int8_t GLbyte;
typedef khronos_uint16_t GLushort;
#define GL_BLEND_EQUATION_RGB 0x8009
#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622
#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623
#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624
#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625
#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645
#define GL_BLEND_EQUATION_ALPHA 0x883D
#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A
#define GL_FRAGMENT_SHADER 0x8B30
#define GL_VERTEX_SHADER 0x8B31
#define GL_COMPILE_STATUS 0x8B81
#define GL_LINK_STATUS 0x8B82
#define GL_INFO_LOG_LENGTH 0x8B84
#define GL_CURRENT_PROGRAM 0x8B8D
#define GL_UPPER_LEFT 0x8CA2
typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC) (GLenum modeRGB, GLenum modeAlpha);
typedef void (APIENTRYP PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader);
typedef void (APIENTRYP PFNGLCOMPILESHADERPROC) (GLuint shader);
typedef GLuint (APIENTRYP PFNGLCREATEPROGRAMPROC) (void);
typedef GLuint (APIENTRYP PFNGLCREATESHADERPROC) (GLenum type);
typedef void (APIENTRYP PFNGLDELETEPROGRAMPROC) (GLuint program);
typedef void (APIENTRYP PFNGLDELETESHADERPROC) (GLuint shader);
typedef void (APIENTRYP PFNGLDETACHSHADERPROC) (GLuint program, GLuint shader);
typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC) (GLuint index);
typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index);
typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const GLchar *name);
typedef void (APIENTRYP PFNGLGETPROGRAMIVPROC) (GLuint program, GLenum pname, GLint *params);
typedef void (APIENTRYP PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
typedef void (APIENTRYP PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params);
typedef void (APIENTRYP PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const GLchar *name);
typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVPROC) (GLuint index, GLenum pname, GLint *params);
typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC) (GLuint index, GLenum pname, void **pointer);
typedef GLboolean (APIENTRYP PFNGLISPROGRAMPROC) (GLuint program);
typedef void (APIENTRYP PFNGLLINKPROGRAMPROC) (GLuint program);
typedef void (APIENTRYP PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length);
typedef void (APIENTRYP PFNGLUSEPROGRAMPROC) (GLuint program);
typedef void (APIENTRYP PFNGLUNIFORM1IPROC) (GLint location, GLint v0);
typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI void APIENTRY glBlendEquationSeparate (GLenum modeRGB, GLenum modeAlpha);
GLAPI void APIENTRY glAttachShader (GLuint program, GLuint shader);
GLAPI void APIENTRY glCompileShader (GLuint shader);
GLAPI GLuint APIENTRY glCreateProgram (void);
GLAPI GLuint APIENTRY glCreateShader (GLenum type);
GLAPI void APIENTRY glDeleteProgram (GLuint program);
GLAPI void APIENTRY glDeleteShader (GLuint shader);
GLAPI void APIENTRY glDetachShader (GLuint program, GLuint shader);
GLAPI void APIENTRY glDisableVertexAttribArray (GLuint index);
GLAPI void APIENTRY glEnableVertexAttribArray (GLuint index);
GLAPI GLint APIENTRY glGetAttribLocation (GLuint program, const GLchar *name);
GLAPI void APIENTRY glGetProgramiv (GLuint program, GLenum pname, GLint *params);
GLAPI void APIENTRY glGetProgramInfoLog (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
GLAPI void APIENTRY glGetShaderiv (GLuint shader, GLenum pname, GLint *params);
GLAPI void APIENTRY glGetShaderInfoLog (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
GLAPI GLint APIENTRY glGetUniformLocation (GLuint program, const GLchar *name);
GLAPI void APIENTRY glGetVertexAttribiv (GLuint index, GLenum pname, GLint *params);
GLAPI void APIENTRY glGetVertexAttribPointerv (GLuint index, GLenum pname, void **pointer);
GLAPI GLboolean APIENTRY glIsProgram (GLuint program);
GLAPI void APIENTRY glLinkProgram (GLuint program);
GLAPI void APIENTRY glShaderSource (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length);
GLAPI void APIENTRY glUseProgram (GLuint program);
GLAPI void APIENTRY glUniform1i (GLint location, GLint v0);
GLAPI void APIENTRY glUniformMatrix4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
GLAPI void APIENTRY glVertexAttribPointer (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer);
#endif
#endif /* GL_VERSION_2_0 */
#ifndef GL_VERSION_3_0
typedef khronos_uint16_t GLhalf;
#define GL_MAJOR_VERSION 0x821B
#define GL_MINOR_VERSION 0x821C
#define GL_NUM_EXTENSIONS 0x821D
#define GL_FRAMEBUFFER_SRGB 0x8DB9
#define GL_VERTEX_ARRAY_BINDING 0x85B5
typedef void (APIENTRYP PFNGLGETBOOLEANI_VPROC) (GLenum target, GLuint index, GLboolean *data);
typedef void (APIENTRYP PFNGLGETINTEGERI_VPROC) (GLenum target, GLuint index, GLint *data);
typedef const GLubyte *(APIENTRYP PFNGLGETSTRINGIPROC) (GLenum name, GLuint index);
typedef void (APIENTRYP PFNGLBINDVERTEXARRAYPROC) (GLuint array);
typedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSPROC) (GLsizei n, const GLuint *arrays);
typedef void (APIENTRYP PFNGLGENVERTEXARRAYSPROC) (GLsizei n, GLuint *arrays);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI const GLubyte *APIENTRY glGetStringi (GLenum name, GLuint index);
GLAPI void APIENTRY glBindVertexArray (GLuint array);
GLAPI void APIENTRY glDeleteVertexArrays (GLsizei n, const GLuint *arrays);
GLAPI void APIENTRY glGenVertexArrays (GLsizei n, GLuint *arrays);
#endif
#endif /* GL_VERSION_3_0 */
#ifndef GL_VERSION_3_1
#define GL_VERSION_3_1 1
#define GL_PRIMITIVE_RESTART 0x8F9D
#endif /* GL_VERSION_3_1 */
#ifndef GL_VERSION_3_2
#define GL_VERSION_3_2 1
typedef struct __GLsync *GLsync;
typedef khronos_uint64_t GLuint64;
typedef khronos_int64_t GLint64;
#define GL_CONTEXT_COMPATIBILITY_PROFILE_BIT 0x00000002
#define GL_CONTEXT_PROFILE_MASK 0x9126
typedef void (APIENTRYP PFNGLDRAWELEMENTSBASEVERTEXPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex);
typedef void (APIENTRYP PFNGLGETINTEGER64I_VPROC) (GLenum target, GLuint index, GLint64 *data);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI void APIENTRY glDrawElementsBaseVertex (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex);
#endif
#endif /* GL_VERSION_3_2 */
#ifndef GL_VERSION_3_3
#define GL_VERSION_3_3 1
#define GL_SAMPLER_BINDING 0x8919
typedef void (APIENTRYP PFNGLBINDSAMPLERPROC) (GLuint unit, GLuint sampler);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI void APIENTRY glBindSampler (GLuint unit, GLuint sampler);
#endif
#endif /* GL_VERSION_3_3 */
#ifndef GL_VERSION_4_1
typedef void (APIENTRYP PFNGLGETFLOATI_VPROC) (GLenum target, GLuint index, GLfloat *data);
typedef void (APIENTRYP PFNGLGETDOUBLEI_VPROC) (GLenum target, GLuint index, GLdouble *data);
#endif /* GL_VERSION_4_1 */
#ifndef GL_VERSION_4_3
typedef void (APIENTRY *GLDEBUGPROC)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam);
#endif /* GL_VERSION_4_3 */
#ifndef GL_VERSION_4_5
#define GL_CLIP_ORIGIN 0x935C
typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKI_VPROC) (GLuint xfb, GLenum pname, GLuint index, GLint *param);
typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKI64_VPROC) (GLuint xfb, GLenum pname, GLuint index, GLint64 *param);
#endif /* GL_VERSION_4_5 */
#ifndef GL_ARB_bindless_texture
typedef khronos_uint64_t GLuint64EXT;
#endif /* GL_ARB_bindless_texture */
#ifndef GL_ARB_cl_event
struct _cl_context;
struct _cl_event;
#endif /* GL_ARB_cl_event */
#ifndef GL_ARB_clip_control
#define GL_ARB_clip_control 1
#endif /* GL_ARB_clip_control */
#ifndef GL_ARB_debug_output
typedef void (APIENTRY *GLDEBUGPROCARB)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam);
#endif /* GL_ARB_debug_output */
#ifndef GL_EXT_EGL_image_storage
typedef void *GLeglImageOES;
#endif /* GL_EXT_EGL_image_storage */
#ifndef GL_EXT_direct_state_access
typedef void (APIENTRYP PFNGLGETFLOATI_VEXTPROC) (GLenum pname, GLuint index, GLfloat *params);
typedef void (APIENTRYP PFNGLGETDOUBLEI_VEXTPROC) (GLenum pname, GLuint index, GLdouble *params);
typedef void (APIENTRYP PFNGLGETPOINTERI_VEXTPROC) (GLenum pname, GLuint index, void **params);
typedef void (APIENTRYP PFNGLGETVERTEXARRAYINTEGERI_VEXTPROC) (GLuint vaobj, GLuint index, GLenum pname, GLint *param);
typedef void (APIENTRYP PFNGLGETVERTEXARRAYPOINTERI_VEXTPROC) (GLuint vaobj, GLuint index, GLenum pname, void **param);
#endif /* GL_EXT_direct_state_access */
#ifndef GL_NV_draw_vulkan_image
typedef void (APIENTRY *GLVULKANPROCNV)(void);
#endif /* GL_NV_draw_vulkan_image */
#ifndef GL_NV_gpu_shader5
typedef khronos_int64_t GLint64EXT;
#endif /* GL_NV_gpu_shader5 */
#ifndef GL_NV_vertex_buffer_unified_memory
typedef void (APIENTRYP PFNGLGETINTEGERUI64I_VNVPROC) (GLenum value, GLuint index, GLuint64EXT *result);
#endif /* GL_NV_vertex_buffer_unified_memory */
#ifdef __cplusplus
}
#endif
#endif
#ifndef GL3W_API
#define GL3W_API
#endif
#ifndef __gl_h_
#define __gl_h_
#endif
#ifdef __cplusplus
extern "C" {
#endif
#define GL3W_OK 0
#define GL3W_ERROR_INIT -1
#define GL3W_ERROR_LIBRARY_OPEN -2
#define GL3W_ERROR_OPENGL_VERSION -3
typedef void (*GL3WglProc)(void);
typedef GL3WglProc (*GL3WGetProcAddressProc)(const char *proc);
/* gl3w api */
GL3W_API int imgl3wInit(void);
GL3W_API int imgl3wInit2(GL3WGetProcAddressProc proc);
GL3W_API int imgl3wIsSupported(int major, int minor);
GL3W_API GL3WglProc imgl3wGetProcAddress(const char *proc);
/* gl3w internal state */
union ImGL3WProcs {
GL3WglProc ptr[59];
struct {
PFNGLACTIVETEXTUREPROC ActiveTexture;
PFNGLATTACHSHADERPROC AttachShader;
PFNGLBINDBUFFERPROC BindBuffer;
PFNGLBINDSAMPLERPROC BindSampler;
PFNGLBINDTEXTUREPROC BindTexture;
PFNGLBINDVERTEXARRAYPROC BindVertexArray;
PFNGLBLENDEQUATIONPROC BlendEquation;
PFNGLBLENDEQUATIONSEPARATEPROC BlendEquationSeparate;
PFNGLBLENDFUNCSEPARATEPROC BlendFuncSeparate;
PFNGLBUFFERDATAPROC BufferData;
PFNGLBUFFERSUBDATAPROC BufferSubData;
PFNGLCLEARPROC Clear;
PFNGLCLEARCOLORPROC ClearColor;
PFNGLCOMPILESHADERPROC CompileShader;
PFNGLCREATEPROGRAMPROC CreateProgram;
PFNGLCREATESHADERPROC CreateShader;
PFNGLDELETEBUFFERSPROC DeleteBuffers;
PFNGLDELETEPROGRAMPROC DeleteProgram;
PFNGLDELETESHADERPROC DeleteShader;
PFNGLDELETETEXTURESPROC DeleteTextures;
PFNGLDELETEVERTEXARRAYSPROC DeleteVertexArrays;
PFNGLDETACHSHADERPROC DetachShader;
PFNGLDISABLEPROC Disable;
PFNGLDISABLEVERTEXATTRIBARRAYPROC DisableVertexAttribArray;
PFNGLDRAWELEMENTSPROC DrawElements;
PFNGLDRAWELEMENTSBASEVERTEXPROC DrawElementsBaseVertex;
PFNGLENABLEPROC Enable;
PFNGLENABLEVERTEXATTRIBARRAYPROC EnableVertexAttribArray;
PFNGLFLUSHPROC Flush;
PFNGLGENBUFFERSPROC GenBuffers;
PFNGLGENTEXTURESPROC GenTextures;
PFNGLGENVERTEXARRAYSPROC GenVertexArrays;
PFNGLGETATTRIBLOCATIONPROC GetAttribLocation;
PFNGLGETERRORPROC GetError;
PFNGLGETINTEGERVPROC GetIntegerv;
PFNGLGETPROGRAMINFOLOGPROC GetProgramInfoLog;
PFNGLGETPROGRAMIVPROC GetProgramiv;
PFNGLGETSHADERINFOLOGPROC GetShaderInfoLog;
PFNGLGETSHADERIVPROC GetShaderiv;
PFNGLGETSTRINGPROC GetString;
PFNGLGETSTRINGIPROC GetStringi;
PFNGLGETUNIFORMLOCATIONPROC GetUniformLocation;
PFNGLGETVERTEXATTRIBPOINTERVPROC GetVertexAttribPointerv;
PFNGLGETVERTEXATTRIBIVPROC GetVertexAttribiv;
PFNGLISENABLEDPROC IsEnabled;
PFNGLISPROGRAMPROC IsProgram;
PFNGLLINKPROGRAMPROC LinkProgram;
PFNGLPIXELSTOREIPROC PixelStorei;
PFNGLPOLYGONMODEPROC PolygonMode;
PFNGLREADPIXELSPROC ReadPixels;
PFNGLSCISSORPROC Scissor;
PFNGLSHADERSOURCEPROC ShaderSource;
PFNGLTEXIMAGE2DPROC TexImage2D;
PFNGLTEXPARAMETERIPROC TexParameteri;
PFNGLUNIFORM1IPROC Uniform1i;
PFNGLUNIFORMMATRIX4FVPROC UniformMatrix4fv;
PFNGLUSEPROGRAMPROC UseProgram;
PFNGLVERTEXATTRIBPOINTERPROC VertexAttribPointer;
PFNGLVIEWPORTPROC Viewport;
} gl;
};
GL3W_API extern union ImGL3WProcs imgl3wProcs;
/* OpenGL functions */
#define glActiveTexture imgl3wProcs.gl.ActiveTexture
#define glAttachShader imgl3wProcs.gl.AttachShader
#define glBindBuffer imgl3wProcs.gl.BindBuffer
#define glBindSampler imgl3wProcs.gl.BindSampler
#define glBindTexture imgl3wProcs.gl.BindTexture
#define glBindVertexArray imgl3wProcs.gl.BindVertexArray
#define glBlendEquation imgl3wProcs.gl.BlendEquation
#define glBlendEquationSeparate imgl3wProcs.gl.BlendEquationSeparate
#define glBlendFuncSeparate imgl3wProcs.gl.BlendFuncSeparate
#define glBufferData imgl3wProcs.gl.BufferData
#define glBufferSubData imgl3wProcs.gl.BufferSubData
#define glClear imgl3wProcs.gl.Clear
#define glClearColor imgl3wProcs.gl.ClearColor
#define glCompileShader imgl3wProcs.gl.CompileShader
#define glCreateProgram imgl3wProcs.gl.CreateProgram
#define glCreateShader imgl3wProcs.gl.CreateShader
#define glDeleteBuffers imgl3wProcs.gl.DeleteBuffers
#define glDeleteProgram imgl3wProcs.gl.DeleteProgram
#define glDeleteShader imgl3wProcs.gl.DeleteShader
#define glDeleteTextures imgl3wProcs.gl.DeleteTextures
#define glDeleteVertexArrays imgl3wProcs.gl.DeleteVertexArrays
#define glDetachShader imgl3wProcs.gl.DetachShader
#define glDisable imgl3wProcs.gl.Disable
#define glDisableVertexAttribArray imgl3wProcs.gl.DisableVertexAttribArray
#define glDrawElements imgl3wProcs.gl.DrawElements
#define glDrawElementsBaseVertex imgl3wProcs.gl.DrawElementsBaseVertex
#define glEnable imgl3wProcs.gl.Enable
#define glEnableVertexAttribArray imgl3wProcs.gl.EnableVertexAttribArray
#define glFlush imgl3wProcs.gl.Flush
#define glGenBuffers imgl3wProcs.gl.GenBuffers
#define glGenTextures imgl3wProcs.gl.GenTextures
#define glGenVertexArrays imgl3wProcs.gl.GenVertexArrays
#define glGetAttribLocation imgl3wProcs.gl.GetAttribLocation
#define glGetError imgl3wProcs.gl.GetError
#define glGetIntegerv imgl3wProcs.gl.GetIntegerv
#define glGetProgramInfoLog imgl3wProcs.gl.GetProgramInfoLog
#define glGetProgramiv imgl3wProcs.gl.GetProgramiv
#define glGetShaderInfoLog imgl3wProcs.gl.GetShaderInfoLog
#define glGetShaderiv imgl3wProcs.gl.GetShaderiv
#define glGetString imgl3wProcs.gl.GetString
#define glGetStringi imgl3wProcs.gl.GetStringi
#define glGetUniformLocation imgl3wProcs.gl.GetUniformLocation
#define glGetVertexAttribPointerv imgl3wProcs.gl.GetVertexAttribPointerv
#define glGetVertexAttribiv imgl3wProcs.gl.GetVertexAttribiv
#define glIsEnabled imgl3wProcs.gl.IsEnabled
#define glIsProgram imgl3wProcs.gl.IsProgram
#define glLinkProgram imgl3wProcs.gl.LinkProgram
#define glPixelStorei imgl3wProcs.gl.PixelStorei
#define glPolygonMode imgl3wProcs.gl.PolygonMode
#define glReadPixels imgl3wProcs.gl.ReadPixels
#define glScissor imgl3wProcs.gl.Scissor
#define glShaderSource imgl3wProcs.gl.ShaderSource
#define glTexImage2D imgl3wProcs.gl.TexImage2D
#define glTexParameteri imgl3wProcs.gl.TexParameteri
#define glUniform1i imgl3wProcs.gl.Uniform1i
#define glUniformMatrix4fv imgl3wProcs.gl.UniformMatrix4fv
#define glUseProgram imgl3wProcs.gl.UseProgram
#define glVertexAttribPointer imgl3wProcs.gl.VertexAttribPointer
#define glViewport imgl3wProcs.gl.Viewport
#ifdef __cplusplus
}
#endif
#endif
#ifdef IMGL3W_IMPL
#ifdef __cplusplus
extern "C" {
#endif
#include <stdlib.h>
#define GL3W_ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
#if defined(_WIN32)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1
#endif
#include <windows.h>
static HMODULE libgl;
typedef PROC(__stdcall* GL3WglGetProcAddr)(LPCSTR);
static GL3WglGetProcAddr wgl_get_proc_address;
static int open_libgl(void)
{
libgl = LoadLibraryA("opengl32.dll");
if (!libgl)
return GL3W_ERROR_LIBRARY_OPEN;
wgl_get_proc_address = (GL3WglGetProcAddr)GetProcAddress(libgl, "wglGetProcAddress");
return GL3W_OK;
}
static void close_libgl(void) { FreeLibrary(libgl); }
static GL3WglProc get_proc(const char *proc)
{
GL3WglProc res;
res = (GL3WglProc)wgl_get_proc_address(proc);
if (!res)
res = (GL3WglProc)GetProcAddress(libgl, proc);
return res;
}
#elif defined(__APPLE__)
#include <dlfcn.h>
static void *libgl;
static int open_libgl(void)
{
libgl = dlopen("/System/Library/Frameworks/OpenGL.framework/OpenGL", RTLD_LAZY | RTLD_LOCAL);
if (!libgl)
return GL3W_ERROR_LIBRARY_OPEN;
return GL3W_OK;
}
static void close_libgl(void) { dlclose(libgl); }
static GL3WglProc get_proc(const char *proc)
{
GL3WglProc res;
*(void **)(&res) = dlsym(libgl, proc);
return res;
}
#else
#include <dlfcn.h>
static void *libgl;
static GL3WglProc (*glx_get_proc_address)(const GLubyte *);
static int open_libgl(void)
{
// While most systems use libGL.so.1, NetBSD seems to use that libGL.so.3. See https://github.com/ocornut/imgui/issues/6983
libgl = dlopen("libGL.so", RTLD_LAZY | RTLD_LOCAL);
if (!libgl)
libgl = dlopen("libGL.so.1", RTLD_LAZY | RTLD_LOCAL);
if (!libgl)
libgl = dlopen("libGL.so.3", RTLD_LAZY | RTLD_LOCAL);
if (!libgl)
return GL3W_ERROR_LIBRARY_OPEN;
*(void **)(&glx_get_proc_address) = dlsym(libgl, "glXGetProcAddressARB");
return GL3W_OK;
}
static void close_libgl(void) { dlclose(libgl); }
static GL3WglProc get_proc(const char *proc)
{
GL3WglProc res;
res = glx_get_proc_address((const GLubyte *)proc);
if (!res)
*(void **)(&res) = dlsym(libgl, proc);
return res;
}
#endif
static struct { int major, minor; } version;
static int parse_version(void)
{
if (!glGetIntegerv)
return GL3W_ERROR_INIT;
glGetIntegerv(GL_MAJOR_VERSION, &version.major);
glGetIntegerv(GL_MINOR_VERSION, &version.minor);
if (version.major == 0 && version.minor == 0)
{
// Query GL_VERSION in desktop GL 2.x, the string will start with "<major>.<minor>"
if (const char* gl_version = (const char*)glGetString(GL_VERSION))
sscanf(gl_version, "%d.%d", &version.major, &version.minor);
}
if (version.major < 2)
return GL3W_ERROR_OPENGL_VERSION;
return GL3W_OK;
}
static void load_procs(GL3WGetProcAddressProc proc);
int imgl3wInit(void)
{
int res = open_libgl();
if (res)
return res;
atexit(close_libgl);
return imgl3wInit2(get_proc);
}
int imgl3wInit2(GL3WGetProcAddressProc proc)
{
load_procs(proc);
return parse_version();
}
int imgl3wIsSupported(int major, int minor)
{
if (major < 2)
return 0;
if (version.major == major)
return version.minor >= minor;
return version.major >= major;
}
GL3WglProc imgl3wGetProcAddress(const char *proc) { return get_proc(proc); }
static const char *proc_names[] = {
"glActiveTexture",
"glAttachShader",
"glBindBuffer",
"glBindSampler",
"glBindTexture",
"glBindVertexArray",
"glBlendEquation",
"glBlendEquationSeparate",
"glBlendFuncSeparate",
"glBufferData",
"glBufferSubData",
"glClear",
"glClearColor",
"glCompileShader",
"glCreateProgram",
"glCreateShader",
"glDeleteBuffers",
"glDeleteProgram",
"glDeleteShader",
"glDeleteTextures",
"glDeleteVertexArrays",
"glDetachShader",
"glDisable",
"glDisableVertexAttribArray",
"glDrawElements",
"glDrawElementsBaseVertex",
"glEnable",
"glEnableVertexAttribArray",
"glFlush",
"glGenBuffers",
"glGenTextures",
"glGenVertexArrays",
"glGetAttribLocation",
"glGetError",
"glGetIntegerv",
"glGetProgramInfoLog",
"glGetProgramiv",
"glGetShaderInfoLog",
"glGetShaderiv",
"glGetString",
"glGetStringi",
"glGetUniformLocation",
"glGetVertexAttribPointerv",
"glGetVertexAttribiv",
"glIsEnabled",
"glIsProgram",
"glLinkProgram",
"glPixelStorei",
"glPolygonMode",
"glReadPixels",
"glScissor",
"glShaderSource",
"glTexImage2D",
"glTexParameteri",
"glUniform1i",
"glUniformMatrix4fv",
"glUseProgram",
"glVertexAttribPointer",
"glViewport",
};
GL3W_API union ImGL3WProcs imgl3wProcs;
static void load_procs(GL3WGetProcAddressProc proc)
{
size_t i;
for (i = 0; i < GL3W_ARRAY_SIZE(proc_names); i++)
imgl3wProcs.ptr[i] = proc(proc_names[i]);
}
#ifdef __cplusplus
}
#endif
#endif
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-627
View File
@@ -1,627 +0,0 @@
// [DEAR IMGUI]
// This is a slightly modified version of stb_rect_pack.h 1.01.
// Grep for [DEAR IMGUI] to find the changes.
//
// stb_rect_pack.h - v1.01 - public domain - rectangle packing
// Sean Barrett 2014
//
// Useful for e.g. packing rectangular textures into an atlas.
// Does not do rotation.
//
// Before #including,
//
// #define STB_RECT_PACK_IMPLEMENTATION
//
// in the file that you want to have the implementation.
//
// Not necessarily the awesomest packing method, but better than
// the totally naive one in stb_truetype (which is primarily what
// this is meant to replace).
//
// Has only had a few tests run, may have issues.
//
// More docs to come.
//
// No memory allocations; uses qsort() and assert() from stdlib.
// Can override those by defining STBRP_SORT and STBRP_ASSERT.
//
// This library currently uses the Skyline Bottom-Left algorithm.
//
// Please note: better rectangle packers are welcome! Please
// implement them to the same API, but with a different init
// function.
//
// Credits
//
// Library
// Sean Barrett
// Minor features
// Martins Mozeiko
// github:IntellectualKitty
//
// Bugfixes / warning fixes
// Jeremy Jaussaud
// Fabian Giesen
//
// Version history:
//
// 1.01 (2021-07-11) always use large rect mode, expose STBRP__MAXVAL in public section
// 1.00 (2019-02-25) avoid small space waste; gracefully fail too-wide rectangles
// 0.99 (2019-02-07) warning fixes
// 0.11 (2017-03-03) return packing success/fail result
// 0.10 (2016-10-25) remove cast-away-const to avoid warnings
// 0.09 (2016-08-27) fix compiler warnings
// 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0)
// 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0)
// 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort
// 0.05: added STBRP_ASSERT to allow replacing assert
// 0.04: fixed minor bug in STBRP_LARGE_RECTS support
// 0.01: initial release
//
// LICENSE
//
// See end of file for license information.
//////////////////////////////////////////////////////////////////////////////
//
// INCLUDE SECTION
//
#ifndef STB_INCLUDE_STB_RECT_PACK_H
#define STB_INCLUDE_STB_RECT_PACK_H
#define STB_RECT_PACK_VERSION 1
#ifdef STBRP_STATIC
#define STBRP_DEF static
#else
#define STBRP_DEF extern
#endif
#ifdef __cplusplus
extern "C" {
#endif
typedef struct stbrp_context stbrp_context;
typedef struct stbrp_node stbrp_node;
typedef struct stbrp_rect stbrp_rect;
typedef int stbrp_coord;
#define STBRP__MAXVAL 0x7fffffff
// Mostly for internal use, but this is the maximum supported coordinate value.
STBRP_DEF int stbrp_pack_rects (stbrp_context *context, stbrp_rect *rects, int num_rects);
// Assign packed locations to rectangles. The rectangles are of type
// 'stbrp_rect' defined below, stored in the array 'rects', and there
// are 'num_rects' many of them.
//
// Rectangles which are successfully packed have the 'was_packed' flag
// set to a non-zero value and 'x' and 'y' store the minimum location
// on each axis (i.e. bottom-left in cartesian coordinates, top-left
// if you imagine y increasing downwards). Rectangles which do not fit
// have the 'was_packed' flag set to 0.
//
// You should not try to access the 'rects' array from another thread
// while this function is running, as the function temporarily reorders
// the array while it executes.
//
// To pack into another rectangle, you need to call stbrp_init_target
// again. To continue packing into the same rectangle, you can call
// this function again. Calling this multiple times with multiple rect
// arrays will probably produce worse packing results than calling it
// a single time with the full rectangle array, but the option is
// available.
//
// The function returns 1 if all of the rectangles were successfully
// packed and 0 otherwise.
struct stbrp_rect
{
// reserved for your use:
int id;
// input:
stbrp_coord w, h;
// output:
stbrp_coord x, y;
int was_packed; // non-zero if valid packing
}; // 16 bytes, nominally
STBRP_DEF void stbrp_init_target (stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes);
// Initialize a rectangle packer to:
// pack a rectangle that is 'width' by 'height' in dimensions
// using temporary storage provided by the array 'nodes', which is 'num_nodes' long
//
// You must call this function every time you start packing into a new target.
//
// There is no "shutdown" function. The 'nodes' memory must stay valid for
// the following stbrp_pack_rects() call (or calls), but can be freed after
// the call (or calls) finish.
//
// Note: to guarantee best results, either:
// 1. make sure 'num_nodes' >= 'width'
// or 2. call stbrp_allow_out_of_mem() defined below with 'allow_out_of_mem = 1'
//
// If you don't do either of the above things, widths will be quantized to multiples
// of small integers to guarantee the algorithm doesn't run out of temporary storage.
//
// If you do #2, then the non-quantized algorithm will be used, but the algorithm
// may run out of temporary storage and be unable to pack some rectangles.
STBRP_DEF void stbrp_setup_allow_out_of_mem (stbrp_context *context, int allow_out_of_mem);
// Optionally call this function after init but before doing any packing to
// change the handling of the out-of-temp-memory scenario, described above.
// If you call init again, this will be reset to the default (false).
STBRP_DEF void stbrp_setup_heuristic (stbrp_context *context, int heuristic);
// Optionally select which packing heuristic the library should use. Different
// heuristics will produce better/worse results for different data sets.
// If you call init again, this will be reset to the default.
enum
{
STBRP_HEURISTIC_Skyline_default=0,
STBRP_HEURISTIC_Skyline_BL_sortHeight = STBRP_HEURISTIC_Skyline_default,
STBRP_HEURISTIC_Skyline_BF_sortHeight
};
//////////////////////////////////////////////////////////////////////////////
//
// the details of the following structures don't matter to you, but they must
// be visible so you can handle the memory allocations for them
struct stbrp_node
{
stbrp_coord x,y;
stbrp_node *next;
};
struct stbrp_context
{
int width;
int height;
int align;
int init_mode;
int heuristic;
int num_nodes;
stbrp_node *active_head;
stbrp_node *free_head;
stbrp_node extra[2]; // we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2'
};
#ifdef __cplusplus
}
#endif
#endif
//////////////////////////////////////////////////////////////////////////////
//
// IMPLEMENTATION SECTION
//
#ifdef STB_RECT_PACK_IMPLEMENTATION
#ifndef STBRP_SORT
#include <stdlib.h>
#define STBRP_SORT qsort
#endif
#ifndef STBRP_ASSERT
#include <assert.h>
#define STBRP_ASSERT assert
#endif
#ifdef _MSC_VER
#define STBRP__NOTUSED(v) (void)(v)
#define STBRP__CDECL __cdecl
#else
#define STBRP__NOTUSED(v) (void)sizeof(v)
#define STBRP__CDECL
#endif
enum
{
STBRP__INIT_skyline = 1
};
STBRP_DEF void stbrp_setup_heuristic(stbrp_context *context, int heuristic)
{
switch (context->init_mode) {
case STBRP__INIT_skyline:
STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight || heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight);
context->heuristic = heuristic;
break;
default:
STBRP_ASSERT(0);
}
}
STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context *context, int allow_out_of_mem)
{
if (allow_out_of_mem)
// if it's ok to run out of memory, then don't bother aligning them;
// this gives better packing, but may fail due to OOM (even though
// the rectangles easily fit). @TODO a smarter approach would be to only
// quantize once we've hit OOM, then we could get rid of this parameter.
context->align = 1;
else {
// if it's not ok to run out of memory, then quantize the widths
// so that num_nodes is always enough nodes.
//
// I.e. num_nodes * align >= width
// align >= width / num_nodes
// align = ceil(width/num_nodes)
context->align = (context->width + context->num_nodes-1) / context->num_nodes;
}
}
STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes)
{
int i;
for (i=0; i < num_nodes-1; ++i)
nodes[i].next = &nodes[i+1];
nodes[i].next = NULL;
context->init_mode = STBRP__INIT_skyline;
context->heuristic = STBRP_HEURISTIC_Skyline_default;
context->free_head = &nodes[0];
context->active_head = &context->extra[0];
context->width = width;
context->height = height;
context->num_nodes = num_nodes;
stbrp_setup_allow_out_of_mem(context, 0);
// node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly)
context->extra[0].x = 0;
context->extra[0].y = 0;
context->extra[0].next = &context->extra[1];
context->extra[1].x = (stbrp_coord) width;
context->extra[1].y = (1<<30);
context->extra[1].next = NULL;
}
// find minimum y position if it starts at x1
static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0, int width, int *pwaste)
{
stbrp_node *node = first;
int x1 = x0 + width;
int min_y, visited_width, waste_area;
STBRP__NOTUSED(c);
STBRP_ASSERT(first->x <= x0);
#if 0
// skip in case we're past the node
while (node->next->x <= x0)
++node;
#else
STBRP_ASSERT(node->next->x > x0); // we ended up handling this in the caller for efficiency
#endif
STBRP_ASSERT(node->x <= x0);
min_y = 0;
waste_area = 0;
visited_width = 0;
while (node->x < x1) {
if (node->y > min_y) {
// raise min_y higher.
// we've accounted for all waste up to min_y,
// but we'll now add more waste for everything we've visted
waste_area += visited_width * (node->y - min_y);
min_y = node->y;
// the first time through, visited_width might be reduced
if (node->x < x0)
visited_width += node->next->x - x0;
else
visited_width += node->next->x - node->x;
} else {
// add waste area
int under_width = node->next->x - node->x;
if (under_width + visited_width > width)
under_width = width - visited_width;
waste_area += under_width * (min_y - node->y);
visited_width += under_width;
}
node = node->next;
}
*pwaste = waste_area;
return min_y;
}
typedef struct
{
int x,y;
stbrp_node **prev_link;
} stbrp__findresult;
static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int width, int height)
{
int best_waste = (1<<30), best_x, best_y = (1 << 30);
stbrp__findresult fr;
stbrp_node **prev, *node, *tail, **best = NULL;
// align to multiple of c->align
width = (width + c->align - 1);
width -= width % c->align;
STBRP_ASSERT(width % c->align == 0);
// if it can't possibly fit, bail immediately
if (width > c->width || height > c->height) {
fr.prev_link = NULL;
fr.x = fr.y = 0;
return fr;
}
node = c->active_head;
prev = &c->active_head;
while (node->x + width <= c->width) {
int y,waste;
y = stbrp__skyline_find_min_y(c, node, node->x, width, &waste);
if (c->heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight) { // actually just want to test BL
// bottom left
if (y < best_y) {
best_y = y;
best = prev;
}
} else {
// best-fit
if (y + height <= c->height) {
// can only use it if it first vertically
if (y < best_y || (y == best_y && waste < best_waste)) {
best_y = y;
best_waste = waste;
best = prev;
}
}
}
prev = &node->next;
node = node->next;
}
best_x = (best == NULL) ? 0 : (*best)->x;
// if doing best-fit (BF), we also have to try aligning right edge to each node position
//
// e.g, if fitting
//
// ____________________
// |____________________|
//
// into
//
// | |
// | ____________|
// |____________|
//
// then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned
//
// This makes BF take about 2x the time
if (c->heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight) {
tail = c->active_head;
node = c->active_head;
prev = &c->active_head;
// find first node that's admissible
while (tail->x < width)
tail = tail->next;
while (tail) {
int xpos = tail->x - width;
int y,waste;
STBRP_ASSERT(xpos >= 0);
// find the left position that matches this
while (node->next->x <= xpos) {
prev = &node->next;
node = node->next;
}
STBRP_ASSERT(node->next->x > xpos && node->x <= xpos);
y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste);
if (y + height <= c->height) {
if (y <= best_y) {
if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) {
best_x = xpos;
//STBRP_ASSERT(y <= best_y); [DEAR IMGUI]
best_y = y;
best_waste = waste;
best = prev;
}
}
}
tail = tail->next;
}
}
fr.prev_link = best;
fr.x = best_x;
fr.y = best_y;
return fr;
}
static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, int width, int height)
{
// find best position according to heuristic
stbrp__findresult res = stbrp__skyline_find_best_pos(context, width, height);
stbrp_node *node, *cur;
// bail if:
// 1. it failed
// 2. the best node doesn't fit (we don't always check this)
// 3. we're out of memory
if (res.prev_link == NULL || res.y + height > context->height || context->free_head == NULL) {
res.prev_link = NULL;
return res;
}
// on success, create new node
node = context->free_head;
node->x = (stbrp_coord) res.x;
node->y = (stbrp_coord) (res.y + height);
context->free_head = node->next;
// insert the new node into the right starting point, and
// let 'cur' point to the remaining nodes needing to be
// stiched back in
cur = *res.prev_link;
if (cur->x < res.x) {
// preserve the existing one, so start testing with the next one
stbrp_node *next = cur->next;
cur->next = node;
cur = next;
} else {
*res.prev_link = node;
}
// from here, traverse cur and free the nodes, until we get to one
// that shouldn't be freed
while (cur->next && cur->next->x <= res.x + width) {
stbrp_node *next = cur->next;
// move the current node to the free list
cur->next = context->free_head;
context->free_head = cur;
cur = next;
}
// stitch the list back in
node->next = cur;
if (cur->x < res.x + width)
cur->x = (stbrp_coord) (res.x + width);
#ifdef _DEBUG
cur = context->active_head;
while (cur->x < context->width) {
STBRP_ASSERT(cur->x < cur->next->x);
cur = cur->next;
}
STBRP_ASSERT(cur->next == NULL);
{
int count=0;
cur = context->active_head;
while (cur) {
cur = cur->next;
++count;
}
cur = context->free_head;
while (cur) {
cur = cur->next;
++count;
}
STBRP_ASSERT(count == context->num_nodes+2);
}
#endif
return res;
}
static int STBRP__CDECL rect_height_compare(const void *a, const void *b)
{
const stbrp_rect *p = (const stbrp_rect *) a;
const stbrp_rect *q = (const stbrp_rect *) b;
if (p->h > q->h)
return -1;
if (p->h < q->h)
return 1;
return (p->w > q->w) ? -1 : (p->w < q->w);
}
static int STBRP__CDECL rect_original_order(const void *a, const void *b)
{
const stbrp_rect *p = (const stbrp_rect *) a;
const stbrp_rect *q = (const stbrp_rect *) b;
return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed);
}
STBRP_DEF int stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects)
{
int i, all_rects_packed = 1;
// we use the 'was_packed' field internally to allow sorting/unsorting
for (i=0; i < num_rects; ++i) {
rects[i].was_packed = i;
}
// sort according to heuristic
STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare);
for (i=0; i < num_rects; ++i) {
if (rects[i].w == 0 || rects[i].h == 0) {
rects[i].x = rects[i].y = 0; // empty rect needs no space
} else {
stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h);
if (fr.prev_link) {
rects[i].x = (stbrp_coord) fr.x;
rects[i].y = (stbrp_coord) fr.y;
} else {
rects[i].x = rects[i].y = STBRP__MAXVAL;
}
}
}
// unsort
STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order);
// set was_packed flags and all_rects_packed status
for (i=0; i < num_rects; ++i) {
rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL);
if (!rects[i].was_packed)
all_rects_packed = 0;
}
// return the all_rects_packed status
return all_rects_packed;
}
#endif
/*
------------------------------------------------------------------------------
This software is available under 2 licenses -- choose whichever you prefer.
------------------------------------------------------------------------------
ALTERNATIVE A - MIT License
Copyright (c) 2017 Sean Barrett
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
ALTERNATIVE B - Public Domain (www.unlicense.org)
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
*/
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+22 -1
View File
@@ -1,8 +1,29 @@
## Copyright 2009 Intel Corporation
## SPDX-License-Identifier: Apache-2.0
cmake_minimum_required(VERSION 3.14)
include(FetchContent)
set(FETCHCONTENT_QUIET ON)
set(FETCHCONTENT_TRY_FIND_PACKAGE_MODE NEVER)
FetchContent_Declare(
stb
GIT_REPOSITORY https://github.com/nothings/stb
GIT_TAG ${OSPRAY_STB_GIT_TAG}
)
FetchContent_MakeAvailable(stb)
mark_as_advanced(FETCHCONTENT_BASE_DIR)
mark_as_advanced(FETCHCONTENT_FULLY_DISCONNECTED)
mark_as_advanced(FETCHCONTENT_QUIET)
mark_as_advanced(FETCHCONTENT_SOURCE_DIR_STB)
mark_as_advanced(FETCHCONTENT_UPDATES_DISCONNECTED)
mark_as_advanced(FETCHCONTENT_UPDATES_DISCONNECTED_STB)
add_library(stb_image INTERFACE)
target_include_directories(stb_image
INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_LIST_DIR}>
$<BUILD_INTERFACE:${stb_SOURCE_DIR}>
)
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -17,6 +17,7 @@ add_library(ospray_testing SHARED
builders/GravitySpheresVolume.cpp
builders/Instancing.cpp
builders/Interpolation.cpp
builders/MipMapTextures.cpp
builders/Noise.cpp
builders/ParticleVolume.cpp
builders/PerlinNoiseVolumes.cpp
@@ -75,6 +75,8 @@ cpp::Group Curves::buildGroup() const
cpp::CopiedData((vec3f *)points.data(), points.size(), sizeof(vec4f)));
} else if (curveVariant == "bspline") {
geom.setParam("basis", OSP_BSPLINE);
} else if (curveVariant == "bezier") {
geom.setParam("basis", OSP_BEZIER);
}
for (auto &c : s_colors) {
@@ -0,0 +1,104 @@
// Copyright 2023 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#include "Builder.h"
#include "ospray_testing.h"
#include "rkcommon/utility/multidim_index_sequence.h"
using namespace rkcommon::math;
namespace ospray {
namespace testing {
struct MipMapTextures : public detail::Builder
{
MipMapTextures() = default;
~MipMapTextures() override = default;
void commit() override;
cpp::Group buildGroup() const override;
private:
float scale{1.0f};
OSPTextureFilter filter{OSP_TEXTURE_FILTER_LINEAR};
};
// Inlined definitions ////////////////////////////////////////////////////
void MipMapTextures::commit()
{
Builder::commit();
scale = getParam<float>("tcScale", 1.0f);
filter = static_cast<OSPTextureFilter>(
getParam<uint32_t>("filter", OSP_TEXTURE_FILTER_LINEAR));
addPlane = false;
}
cpp::Group MipMapTextures::buildGroup() const
{
std::vector<vec3f> v_position = {{-2.5f, -1.5f, -4.f},
{2.5f, -1.5f, -4.f},
{2.5f, 1.5f, 0.f},
{-2.5f, 1.5f, 0.f},
{-1.25f, 1.5f, -2.f},
{1.25f, 1.5f, -2.f},
{1.25f, 3.5f, -0.5f},
{-1.25f, 3.5f, -0.5f}};
std::vector<vec2f> v_texcoord = {{0.f, 0.f},
{scale, 0.f},
{scale, scale},
{0.f, scale},
{0.f, 0.f},
{scale, 0.f},
{scale, scale},
{0.f, scale}};
cpp::Geometry planeGeometry("mesh");
planeGeometry.setParam("vertex.position", cpp::CopiedData(v_position));
planeGeometry.setParam("vertex.texcoord", cpp::CopiedData(v_texcoord));
planeGeometry.setParam("quadSoup", true);
planeGeometry.commit();
vec2ul texSize(500, 500);
std::vector<uint8_t> texData(texSize.product());
uint8_t grayTexel{50};
uint8_t lightTexel{200};
for (size_t i = 0; i < texSize.x; i++) {
const int sz = 1 + i * 4 / texSize.x;
for (size_t j = 0; j < texSize.y; j++) {
texData[j * texSize.x + i] =
(i / sz + j / sz) % 2 ? lightTexel : grayTexel;
}
}
cpp::Texture procTex("texture2d");
procTex.setParam("format", OSP_TEXTURE_L8);
procTex.setParam("filter", filter);
procTex.setParam("data", cpp::CopiedData(texData.data(), texSize));
procTex.commit();
cpp::GeometricModel plane(planeGeometry);
cpp::Material material("obj");
material.setParam("map_kd", procTex);
material.setParam("map_kd.scale", vec2f(scale));
material.setParam("map_kd.translation", vec2f(0.5f - 0.5f / scale));
material.commit();
plane.setParam("material", material);
plane.commit();
cpp::Group planeGroup;
planeGroup.setParam("geometry", cpp::CopiedData(plane));
planeGroup.commit();
return planeGroup;
}
OSP_REGISTER_TESTING_BUILDER(MipMapTextures, mip_map_textures);
} // namespace testing
} // namespace ospray
@@ -18,7 +18,7 @@ struct PtMixTex : public PtTex
// Inlined definitions ////////////////////////////////////////////////////
std::vector<cpp::Material> PtMixTex::buildMaterials(
const cpp::Texture &texR, const cpp::Texture &) const
const cpp::Texture &texR, const cpp::Texture &texRGBA) const
{
std::vector<cpp::Material> materials;
@@ -80,6 +80,23 @@ std::vector<cpp::Material> PtMixTex::buildMaterials(
setTexture<float>(materials.back(), "factor", texR);
}
// emission: principled & luminous
{
cpp::Material principled("principled");
setTexture<vec3f>(principled, "emissiveColor", texRGBA, vec3f(4.6f, 0.1f, 0.1f));
principled.setParam("map_emissiveColor.scale", vec2f(0.7f, 0.3f));
principled.commit();
cpp::Material luminous("luminous");
luminous.setParam("color", vec3f(0.1f, 0.6f, 0.1f));
luminous.setParam("intensity", 5.0f);
luminous.commit();
cpp::Material mix("mix");
mix.setParam("material1", principled);
mix.setParam("material2", luminous);
materials.push_back(mix);
setTexture<float>(materials.back(), "factor", texR);
}
return materials;
}
@@ -141,9 +141,22 @@ std::vector<cpp::Material> PtPrincipledTex::buildMaterials(
setTexture<float>(materials.back(), "backlight", texR, 2.f);
}
materials.push_back(cpp::Material("principled"));
materials.back().setParam("baseColor", vec3f(1.f, 0.8f, 0.7f));
setTexture<vec3f>(materials.back(), "emissiveColor", texRGBA);
{
// emissive
materials.push_back(cpp::Material("principled"));
materials.back().setParam("baseColor", vec3f(1.f, 0.8f, 0.7f));
setTexture<vec3f>(materials.back(), "emissiveColor", texRGBA);
// transparency
materials.push_back(cpp::Material("principled"));
materials.back().setParam("baseColor", vec3f(0.860f, 0.0258f, 0.0536f));
setTexture<vec3f>(materials.back(), "baseColor", texRGBA);
// opacity
materials.push_back(cpp::Material("principled"));
materials.back().setParam("baseColor", vec3f(0.860f, 0.0258f, 0.0536f));
setTexture<float>(materials.back(), "opacity", texR);
}
return materials;
}
@@ -54,7 +54,7 @@ static cpp::Texture makeCheckerboardTextureRGBA8()
index_sequence_2D idx(vec2i(width, height));
for (auto i : idx) {
uint8_t v = ((i.x & 2) ^ (i.y & 2)) * 255;
dbyte[idx.flatten(i)] = vec4uc(v, v, v, 255);
dbyte[idx.flatten(i)] = vec4uc(v, v, v, 128 + v / 2);
}
// Create texture object
@@ -202,8 +202,10 @@ inline cpp::World PtTex::buildWorld() const
cpp::Texture texRGBA = makeCheckerboardTextureRGBA8();
std::vector<cpp::Material> materials = buildMaterials(texR, texRGBA);
const int dimCount = sqrtf(materials.size());
const int dimSize = dimCount - 1;
size_t dimCount = sqrtf(materials.size());
if (dimCount * dimCount < materials.size())
dimCount++;
const size_t dimSize = dimCount - 1;
cpp::Geometry sphereGeometry = makeSphereMesh(25, 50);
@@ -212,10 +214,12 @@ inline cpp::World PtTex::buildWorld() const
box3f bbox(empty);
index_sequence_2D numSpheres(dimCount);
for (auto i : numSpheres) {
const auto idx = numSpheres.flatten(i);
if (idx >= materials.size())
break;
// Construct GeometricModel for each instance
cpp::GeometricModel model(sphereGeometry);
model.setParam(
"material", cpp::CopiedData(materials[numSpheres.flatten(i)]));
model.setParam("material", cpp::CopiedData(materials[idx]));
model.commit();
// Construct Group for each instance
+178 -73
View File
@@ -76,7 +76,7 @@ static const std::vector<std::string> g_scenes = {"boxes_lit",
"test_pt_velvet"};
static const std::vector<std::string> g_curveVariant = {
"bspline", "hermite", "catmull-rom", "linear", "cones"};
"bspline", "bezier", "hermite", "catmull-rom", "linear", "cones"};
static const std::vector<std::string> g_renderers = {
"scivis", "pathtracer", "ao", "debug"};
@@ -89,6 +89,7 @@ static const std::vector<std::string> g_debugRendererTypes = {"eyeLight",
"Ns",
"backfacing_Ng",
"backfacing_Ns",
"texCoord",
"dPds",
"dPdt",
"volume"};
@@ -97,7 +98,10 @@ static const std::vector<std::string> g_pixelFilterTypes = {
"point", "box", "gaussian", "mitchell", "blackmanHarris"};
static const std::vector<std::string> g_AOVs = {
"color", "depth", "albedo", "primID", "objID", "instID"};
"color", "depth", "albedo", "normal", "primID", "objID", "instID"};
static const std::vector<std::string> g_denoiserQuality = {
"low", "medium", "high"};
const char *vec_string_getter(void *vec_, int index)
{
@@ -114,13 +118,20 @@ void error_callback(int error, const char *desc)
GLFWOSPRayWindow *GLFWOSPRayWindow::activeWindow = nullptr;
GLFWOSPRayWindow::GLFWOSPRayWindow(const vec2i &windowSize, bool denoiser)
: denoiserAvailable(denoiser)
GLFWOSPRayWindow::GLFWOSPRayWindow(
const vec2i &windowSize, bool denoiserAvail, bool denoiserGPUAvail)
: denoiserAvailable(denoiserAvail)
{
if (activeWindow != nullptr) {
throw std::runtime_error("Cannot create more than one GLFWOSPRayWindow!");
}
if (denoiserAvailable) {
denoiser = cpp::ImageOperation("denoiser");
denoiserEnabled = denoiserGPUAvail;
updateFrameOpsNextFrame = denoiserEnabled;
}
activeWindow = this;
glfwSetErrorCallback(error_callback);
@@ -222,10 +233,10 @@ GLFWOSPRayWindow::GLFWOSPRayWindow(const vec2i &windowSize, bool denoiser)
// set up backplate texture
std::vector<vec4f> backplate;
backplate.push_back(vec4f(0.8f, 0.2f, 0.2f, 1.0f));
backplate.push_back(vec4f(0.2f, 0.8f, 0.2f, 1.0f));
backplate.push_back(vec4f(0.2f, 0.2f, 0.8f, 1.0f));
backplate.push_back(vec4f(0.4f, 0.2f, 0.4f, 1.0f));
backplate.push_back(vec4f(0.05f, 0.05f, 0.05f, 1.0f));
backplate.push_back(vec4f(0.05f, 0.05f, 0.05f, 1.0f));
backplate.push_back(vec4f(0.01f, 0.01f, 0.01f, 1.0f));
backplate.push_back(vec4f(0.01f, 0.01f, 0.01f, 1.0f));
backplateTex.setParam(
"data", cpp::CopiedData(backplate.data(), vec2ul(2, 2)));
@@ -296,6 +307,7 @@ void GLFWOSPRayWindow::reshape(const vec2i &newWindowSize)
framebuffer =
cpp::FrameBuffer(windowSize.x, windowSize.y, OSP_FB_RGBA32F, buffers);
updateTargetFrames(false);
refreshFrameOperations();
// reset OpenGL viewport and orthographic projection
@@ -309,7 +321,7 @@ void GLFWOSPRayWindow::reshape(const vec2i &newWindowSize)
arcballCamera->updateWindowSize(windowSize);
camera.setParam("aspect", windowSize.x / float(windowSize.y));
camera.commit();
addObjectToCommit(camera.handle());
}
void GLFWOSPRayWindow::updateCamera()
@@ -332,6 +344,7 @@ void GLFWOSPRayWindow::updateCamera()
camera.setParam("transform", xfm);
camera.setParam("shutter", range1f(0.5f));
}
addObjectToCommit(camera.handle());
}
void GLFWOSPRayWindow::motion(const vec2f &position)
@@ -366,7 +379,6 @@ void GLFWOSPRayWindow::motion(const vec2f &position)
waitOnOSPRayFrame();
}
updateCamera();
addObjectToCommit(camera.handle());
}
}
@@ -409,6 +421,8 @@ void GLFWOSPRayWindow::display()
fbChannel = OSP_FB_DEPTH;
if (showAlbedo)
fbChannel = OSP_FB_ALBEDO;
if (showNormal)
fbChannel = OSP_FB_NORMAL;
if (showPrimID)
fbChannel = OSP_FB_ID_PRIMITIVE;
if (showGeomID)
@@ -449,24 +463,34 @@ void GLFWOSPRayWindow::display()
id == -1u ? vec3f(0.f) : rkcommon::utility::makeRandomColor(id);
}
}
if (showNormal) {
float *nFb = static_cast<float *>(fb);
float *iFb = reinterpret_cast<float *>(idFbArray.data());
for (int i = 0; i < windowSize.x * windowSize.y * 3; i++)
iFb[i] = std::abs(nFb[i]);
}
glBindTexture(GL_TEXTURE_2D, framebufferTexture);
glTexImage2D(GL_TEXTURE_2D,
0,
showDepth ? GL_DEPTH_COMPONENT
: ((showAlbedo || showPrimID || showGeomID || showInstID)
: ((showAlbedo || showNormal || showPrimID || showGeomID
|| showInstID)
? GL_RGB32F
: GL_RGBA32F),
windowSize.x,
windowSize.y,
0,
showDepth ? GL_DEPTH_COMPONENT
: ((showAlbedo || showPrimID || showGeomID || showInstID)
: ((showAlbedo || showNormal || showPrimID || showGeomID
|| showInstID)
? GL_RGB
: GL_RGBA),
GL_FLOAT,
showDepth ? depthFb
: ((showPrimID || showGeomID || showInstID) ? idFb : fb));
showDepth
? depthFb
: ((showNormal || showPrimID || showGeomID || showInstID) ? idFb
: fb));
framebuffer.unmap(fb);
@@ -499,12 +523,20 @@ void GLFWOSPRayWindow::display()
void GLFWOSPRayWindow::startNewOSPRayFrame()
{
if (updateFrameOpsNextFrame) {
if (updateFrameOpsNextFrame)
refreshFrameOperations();
updateFrameOpsNextFrame = false;
}
lastXfm = arcballCamera->transform();
currentFrame = framebuffer.renderFrame(*renderer, camera, world);
if (updateFrameOpsNextFrame || accumLimit == 0 || frame < accumLimit) {
currentFrame = framebuffer.renderFrame(*renderer, camera, world);
// correctly count rendered frames: to run the PP (e.g. toggling the
// denoiser) we need to start a renderFrame and cannot skip rendering via
// targetFrames in case PT should *not* use blue noise
if (accumLimit == 0 || frame < accumLimit
|| (rendererType == OSPRayRendererType::PATHTRACER && !blueNoise))
frame++;
}
updateFrameOpsNextFrame = false;
if (renderCameraMotionBlur) {
camera.removeParam("motion.transform");
camera.setParam("transform", lastXfm);
@@ -526,8 +558,12 @@ void GLFWOSPRayWindow::addObjectToCommit(OSPObject obj)
void GLFWOSPRayWindow::updateTitleBar()
{
std::stringstream windowTitle;
windowTitle << "OSPRay: " << std::setprecision(4) << " render: " << latestFPS
<< " fps, app: " << displayFPS << " fps";
windowTitle << "OSPRay frame: " << frame
<< (accumLimit && frame >= accumLimit ? " (limit reached), last"
: ", ")
<< " render:" << std::fixed << std::setprecision(2)
<< std::setw(7) << latestFPS << " fps, app:" << std::setw(7)
<< displayFPS << " fps";
if (latestFPS > 0.f && latestFPS < 2.f) {
float progress = currentFrame.progress();
windowTitle << " | ";
@@ -552,7 +588,7 @@ void GLFWOSPRayWindow::buildUI()
ImGuiWindowFlags flags = ImGuiWindowFlags_AlwaysAutoResize;
ImGui::Begin("press 'g' to hide/show UI", nullptr, flags);
static int whichScene = 0;
static int whichScene = 2;
if (ImGui::Combo("scene##whichScene",
&whichScene,
vec_string_getter,
@@ -579,7 +615,7 @@ void GLFWOSPRayWindow::buildUI()
refreshScene(true);
}
static int whichRenderer = 0;
static int whichRenderer = 1;
static int whichDebuggerType = 0;
if (ImGui::Combo("renderer##whichRenderer",
&whichRenderer,
@@ -603,6 +639,7 @@ void GLFWOSPRayWindow::buildUI()
rendererType = OSPRayRendererType::OTHER;
refreshScene();
updateTargetFrames();
}
if (rendererType == OSPRayRendererType::DEBUGGER) {
@@ -616,6 +653,8 @@ void GLFWOSPRayWindow::buildUI()
}
}
if (ImGui::SliderInt("accumulation limit", &accumLimit, 0, 64))
updateTargetFrames();
ImGui::Checkbox("cancel frame on interaction", &cancelFrameOnInteraction);
static int whichAOV = 0;
@@ -625,11 +664,14 @@ void GLFWOSPRayWindow::buildUI()
(void *)&g_AOVs,
g_AOVs.size())) {
const auto &aovStr = g_AOVs[whichAOV];
showDepth = showAlbedo = showPrimID = showGeomID = showInstID = false;
showDepth = showAlbedo = showNormal = showPrimID = showGeomID = showInstID =
false;
if (aovStr == "depth")
showDepth = true;
if (aovStr == "albedo")
showAlbedo = true;
if (aovStr == "normal")
showNormal = true;
if (aovStr == "primID")
showPrimID = true;
if (aovStr == "objID")
@@ -642,6 +684,18 @@ void GLFWOSPRayWindow::buildUI()
if (denoiserAvailable) {
if (ImGui::Checkbox("denoiser", &denoiserEnabled))
updateFrameOpsNextFrame = true;
static int whichQuality = 1; // medium
if (denoiserEnabled
&& ImGui::Combo("quality##whichQuality",
&whichQuality,
vec_string_getter,
(void *)&g_denoiserQuality,
g_denoiserQuality.size())) {
denoiser.setParam("quality",
OSPDenoiserQuality::OSP_DENOISER_QUALITY_LOW + whichQuality);
addObjectToCommit(denoiser.handle());
}
}
ImGui::Separator();
@@ -687,8 +741,19 @@ void GLFWOSPRayWindow::buildUI()
addObjectToCommit(renderer->handle());
}
if (scene == "mip_map_textures") {
static float mipBias = 0.0f;
if (ImGui::SliderFloat("mipMapBias", &mipBias, -5.0f, 10.0f)) {
rendererPT.setParam("mipMapBias", mipBias);
rendererSV.setParam("mipMapBias", mipBias);
rendererAO.setParam("mipMapBias", mipBias);
rendererDBG.setParam("mipMapBias", mipBias);
addObjectToCommit(renderer->handle());
}
}
static float varianceThreshold = 0.0f;
if (ImGui::SliderFloat("varianceThreshold", &varianceThreshold, 0.f, .5f)) {
if (ImGui::SliderFloat("varianceThreshold", &varianceThreshold, 0.f, 5.f)) {
renderer->setParam("varianceThreshold", varianceThreshold);
addObjectToCommit(renderer->handle());
}
@@ -705,8 +770,10 @@ void GLFWOSPRayWindow::buildUI()
addObjectToCommit(renderer->handle());
}
static bool useTestTex = false;
if (ImGui::Checkbox("backplate texture", &useTestTex)) {
static bool useTestTex = true;
static bool init = true;
if (init || ImGui::Checkbox("backplate texture", &useTestTex)) {
init = false;
if (useTestTex) {
rendererPT.setParam("map_backplate", backplateTex);
rendererSV.setParam("map_backplate", backplateTex);
@@ -721,35 +788,49 @@ void GLFWOSPRayWindow::buildUI()
addObjectToCommit(renderer->handle());
}
if (ImGui::Checkbox("renderSunSky", &renderSunSky)) {
if (rendererType == OSPRayRendererType::SCIVIS
|| rendererType == OSPRayRendererType::PATHTRACER) {
if (ImGui::Checkbox("sun-sky illumination", &renderSunSky)) {
if (renderSunSky) {
sunSky.setParam("direction", sunDirection);
sunSky.setParam("horizonExtension", horizonExtension);
sunSky.setParam("turbidity", turbidity);
world.setParam("light", cpp::CopiedData(sunSky));
addObjectToCommit(sunSky.handle());
// turn-off background
bgColorSRGB = bgColor = vec3f(0.f);
renderer->setParam("backgroundColor", bgColor);
useTestTex = false;
rendererPT.removeParam("map_backplate");
rendererSV.removeParam("map_backplate");
rendererAO.removeParam("map_backplate");
rendererDBG.removeParam("map_backplate");
addObjectToCommit(renderer->handle());
} else {
cpp::Light light("ambient");
light.setParam("visible", false);
light.commit();
world.setParam("light", cpp::CopiedData(light));
}
addObjectToCommit(world.handle());
}
if (renderSunSky) {
sunSky.setParam("direction", sunDirection);
world.setParam("light", cpp::CopiedData(sunSky));
addObjectToCommit(sunSky.handle());
} else {
cpp::Light light("ambient");
light.setParam("visible", false);
light.commit();
world.setParam("light", cpp::CopiedData(light));
}
addObjectToCommit(world.handle());
}
if (renderSunSky) {
if (ImGui::DragFloat3("sunDirection", sunDirection, 0.01f, -1.f, 1.f)) {
sunSky.setParam("direction", sunDirection);
addObjectToCommit(sunSky.handle());
addObjectToCommit(world.handle());
}
if (ImGui::DragFloat("turbidity", &turbidity, 0.1f, 1.f, 10.f)) {
sunSky.setParam("turbidity", turbidity);
addObjectToCommit(sunSky.handle());
addObjectToCommit(world.handle());
}
if (ImGui::DragFloat(
"horizonExtension", &horizonExtension, 0.01f, 0.f, 1.f)) {
sunSky.setParam("horizonExtension", horizonExtension);
addObjectToCommit(sunSky.handle());
addObjectToCommit(world.handle());
if (ImGui::DragFloat3("sunDirection", sunDirection, 0.01f, -1.f, 1.f)) {
sunSky.setParam("direction", sunDirection);
addObjectToCommit(sunSky.handle());
addObjectToCommit(world.handle());
}
if (ImGui::DragFloat("turbidity", &turbidity, 0.1f, 1.f, 10.f)) {
sunSky.setParam("turbidity", turbidity);
addObjectToCommit(sunSky.handle());
addObjectToCommit(world.handle());
}
if (ImGui::DragFloat(
"horizonExtension", &horizonExtension, 0.01f, 0.f, 1.f)) {
sunSky.setParam("horizonExtension", horizonExtension);
addObjectToCommit(sunSky.handle());
addObjectToCommit(world.handle());
}
}
}
@@ -760,6 +841,22 @@ void GLFWOSPRayWindow::buildUI()
addObjectToCommit(renderer->handle());
}
static bool limitIndirectLightSamples = true;
if (ImGui::Checkbox("limitIndirectLightSamples", &limitIndirectLightSamples)) {
renderer->setParam("limitIndirectLightSamples", limitIndirectLightSamples);
addObjectToCommit(renderer->handle());
}
if (accumLimit) {
if (ImGui::Checkbox("blue noise", &blueNoise))
updateTargetFrames();
} else {
ImGui::BeginDisabled();
bool f = false;
ImGui::Checkbox("blue noise (needs accumulation limit)", &f);
ImGui::EndDisabled();
}
static int maxDepth = 20;
if (ImGui::SliderInt("maxPathLength", &maxDepth, 1, 64)) {
renderer->setParam("maxPathLength", maxDepth);
@@ -786,7 +883,6 @@ void GLFWOSPRayWindow::buildUI()
if (ImGui::SliderFloat("camera motion blur", &cameraMotionBlur, 0.f, 1.f)) {
updateCamera();
addObjectToCommit(camera.handle());
}
if (cameraMotionBlur > 0.0f) {
@@ -805,33 +901,31 @@ void GLFWOSPRayWindow::buildUI()
ImGui::SetItemDefaultFocus();
}
ImGui::EndCombo();
updateCamera();
}
updateCamera();
addObjectToCommit(camera.handle());
}
if (cameraShutterType != OSP_SHUTTER_GLOBAL
&& ImGui::SliderFloat(
"rollingShutterDuration", &cameraRollingShutter, 0.f, 1.0f)) {
updateCamera();
addObjectToCommit(camera.handle());
}
} else if (rendererType == OSPRayRendererType::SCIVIS) {
static bool shadowsEnabled = false;
if (ImGui::Checkbox("shadows", &shadowsEnabled)) {
static bool init = true;
static bool shadowsEnabled = true;
if (init || ImGui::Checkbox("shadows", &shadowsEnabled)) {
renderer->setParam("shadows", shadowsEnabled);
addObjectToCommit(renderer->handle());
}
static bool visibleLights = false;
if (ImGui::Checkbox("visibleLights", &visibleLights)) {
static bool visibleLights = true;
if (init || ImGui::Checkbox("visibleLights", &visibleLights)) {
renderer->setParam("visibleLights", visibleLights);
addObjectToCommit(renderer->handle());
}
static int aoSamples = 0;
if (ImGui::SliderInt("aoSamples", &aoSamples, 0, 64)) {
static int aoSamples = 1;
if (init || ImGui::SliderInt("aoSamples", &aoSamples, 0, 64)) {
renderer->setParam("aoSamples", aoSamples);
addObjectToCommit(renderer->handle());
}
@@ -841,6 +935,7 @@ void GLFWOSPRayWindow::buildUI()
renderer->setParam("volumeSamplingRate", samplingRate);
addObjectToCommit(renderer->handle());
}
init = false;
} else if (rendererType == OSPRayRendererType::AO) {
static int aoSamples = 1;
if (ImGui::SliderInt("aoSamples", &aoSamples, 0, 64)) {
@@ -875,7 +970,6 @@ void GLFWOSPRayWindow::buildUI()
ImGui::EndCombo();
updateCamera();
addObjectToCommit(camera.handle());
}
if (uiCallback) {
@@ -892,6 +986,7 @@ void GLFWOSPRayWindow::commitOutstandingHandles()
if (!handles.empty()) {
for (auto &h : handles)
ospCommit(h);
frame = 0;
framebuffer.resetAccumulation();
}
}
@@ -911,12 +1006,9 @@ void GLFWOSPRayWindow::refreshScene(bool resetCamera)
testing::release(builder);
switch (rendererType) {
case OSPRayRendererType::PATHTRACER: {
case OSPRayRendererType::PATHTRACER:
renderer = &rendererPT;
if (renderSunSky)
world.setParam("light", cpp::CopiedData(sunSky));
break;
}
case OSPRayRendererType::SCIVIS:
renderer = &rendererSV;
break;
@@ -929,6 +1021,12 @@ void GLFWOSPRayWindow::refreshScene(bool resetCamera)
default:
throw std::runtime_error("invalid renderer chosen!");
}
if (rendererType == OSPRayRendererType::SCIVIS
|| rendererType == OSPRayRendererType::PATHTRACER) {
if (renderSunSky)
world.setParam("light", cpp::CopiedData(sunSky));
} else
renderSunSky = false;
// retains a set background color on renderer change
renderer->setParam("backgroundColor", bgColor);
addObjectToCommit(renderer->handle());
@@ -944,18 +1042,25 @@ void GLFWOSPRayWindow::refreshScene(bool resetCamera)
// init camera
camera.setParam("position", vec3f(0.0f, 0.0f, 1.0f));
updateCamera();
camera.commit();
}
}
void GLFWOSPRayWindow::refreshFrameOperations()
{
if (denoiserEnabled) {
cpp::ImageOperation d("denoiser");
framebuffer.setParam("imageOperation", cpp::CopiedData(d));
framebuffer.setParam("imageOperation", cpp::CopiedData(denoiser));
} else {
framebuffer.removeParam("imageOperation");
}
framebuffer.commit();
}
void GLFWOSPRayWindow::updateTargetFrames(const bool commit)
{
framebuffer.setParam("targetFrames",
rendererType != OSPRayRendererType::PATHTRACER || blueNoise ? accumLimit
: 0);
if (commit)
addObjectToCommit(framebuffer.handle());
}
+15 -6
View File
@@ -27,7 +27,9 @@ enum class OSPRayRendererType
class GLFWOSPRayWindow
{
public:
GLFWOSPRayWindow(const vec2i &windowSize, bool denoiser = false);
GLFWOSPRayWindow(const vec2i &windowSize,
bool denoiserAvail = false,
bool denoiserGPUAvail = false);
~GLFWOSPRayWindow();
@@ -50,6 +52,7 @@ class GLFWOSPRayWindow
void commitOutstandingHandles();
void refreshScene(bool resetCamera = false);
void refreshFrameOperations();
void updateTargetFrames(const bool commit = true);
static GLFWOSPRayWindow *activeWindow;
@@ -60,6 +63,7 @@ class GLFWOSPRayWindow
bool updateFrameOpsNextFrame{false};
bool denoiserEnabled{false};
bool showAlbedo{false};
bool showNormal{false};
bool showDepth{false};
bool showPrimID{false};
bool showGeomID{false};
@@ -94,18 +98,23 @@ class GLFWOSPRayWindow
cpp::FrameBuffer framebuffer;
cpp::Future currentFrame;
cpp::Texture backplateTex{"texture2d"};
cpp::ImageOperation denoiser;
int frame{0};
bool blueNoise{true};
int accumLimit{0};
vec3f bgColor{0.f};
vec3f sunDirection{-0.25f, -1.0f, 0.0f};
vec3f sunDirection{-0.25f, -1.0f, 1.0f};
float turbidity{3.f};
float horizonExtension{0.1f};
float horizonExtension{0.25f};
std::string scene{"boxes_lit"};
std::string scene{"cornell_box"};
std::string curveVariant{"bspline"};
OSPRayRendererType rendererType{OSPRayRendererType::SCIVIS};
std::string rendererTypeStr{"scivis"};
OSPRayRendererType rendererType{OSPRayRendererType::PATHTRACER};
std::string rendererTypeStr{"pathtracer"};
std::string pixelFilterTypeStr{"gaussian"};
+13 -3
View File
@@ -11,10 +11,20 @@ int main(int argc, const char *argv[])
{
initializeOSPRay(argc, argv, false);
bool denoiser = ospLoadModule("denoiser") == OSP_NO_ERROR;
const bool denoiserAvailable = ospLoadModule("denoiser") == OSP_NO_ERROR;
auto glfwOSPRayWindow =
make_unique<GLFWOSPRayWindow>(vec2i(1024, 768), denoiser);
bool denoiserGPUSupport = false;
if (denoiserAvailable) {
const void *sym =
rkcommon::getSymbol("ospray_module_denoiser_gpu_supported");
if (sym) {
auto denoiserGPUSupported = (int (*)())sym;
denoiserGPUSupport = denoiserGPUSupported();
}
}
auto glfwOSPRayWindow = make_unique<GLFWOSPRayWindow>(
vec2i(1024, 768), denoiserAvailable, denoiserGPUSupport);
glfwOSPRayWindow->mainLoop();
glfwOSPRayWindow.reset();
+14 -19
View File
@@ -29,15 +29,6 @@ PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_LIST_DIR}>
)
if (OSPRAY_ENABLE_VOLUMES)
# We need to know if volumes are enabled at compile time so that
# we can enable/disable the VKL-dependent tests for enum values
target_compile_definitions(ospray_gtest_utils
PUBLIC
-DOSPRAY_ENABLE_VOLUMES
)
endif()
add_executable(ospTestSuite
${OSPRAY_RESOURCE}
environment.cpp # potentially compile with SYCL, overriding non-SYCL ospray_gtest_utils
@@ -57,27 +48,31 @@ add_executable(ospTestSuite
ospTestSuite.cpp
)
# We need to know if volumes are enabled at compile time so that
# we can enable/disable the VKL-dependent tests for enum values
# Same for OIDN tests
target_compile_definitions(ospTestSuite
PRIVATE
$<$<BOOL:${OSPRAY_ENABLE_VOLUMES}>:OSPRAY_ENABLE_VOLUMES>
$<$<BOOL:${OSPRAY_MODULE_DENOISER}>:OSPRAY_MODULE_DENOISER>
)
target_include_directories(ospTestSuite
PRIVATE
$<$<BOOL:${OSPRAY_ENABLE_VOLUMES}>:$<TARGET_PROPERTY:openvkl::openvkl,INTERFACE_INCLUDE_DIRECTORIES>>
$<$<BOOL:${OSPRAY_MODULE_DENOISER}>:$<TARGET_PROPERTY:OpenImageDenoise,INTERFACE_INCLUDE_DIRECTORIES>>
)
target_link_libraries(ospTestSuite
PRIVATE
ospray_testing
ospray_gtest_utils
embree
$<$<BOOL:${OSPRAY_ENABLE_VOLUMES}>:openvkl::openvkl>
$<$<BOOL:${OSPRAY_APPS_ENABLE_GLM}>:${GLM_TARGET}>
)
if (OSPRAY_MODULE_GPU)
ospray_add_sycl_target(ospTestSuite)
endif()
if (OSPRAY_MODULE_DENOISER)
# Enable OIDN tests
target_compile_definitions(ospTestSuite
PUBLIC
-DOSPRAY_MODULE_DENOISER
)
endif()
ospray_sign_target(ospTestSuite)
install(TARGETS ospTestSuite
+138 -27
View File
@@ -3,6 +3,7 @@
#include "test_appearance.h"
#include "ArcballCamera.h"
#include "ospray_testing.h"
#include "rkcommon/utility/multidim_index_sequence.h"
namespace OSPRayTestScenes {
@@ -10,7 +11,7 @@ namespace OSPRayTestScenes {
Texture2D::Texture2D()
{
rendererType = "pathtracer";
samplesPerPixel = 64;
samplesPerPixel = 8;
}
void Texture2D::SetUp()
@@ -23,40 +24,37 @@ void Texture2D::SetUp()
auto params = GetParam();
OSPTextureFilter filter = std::get<0>(params);
// create (4*2) x 4 grid
// create (4*2) x 5 grid
constexpr int cols = 8;
constexpr int rows = 4;
constexpr int rows = 5;
std::vector<vec3f> vertex;
std::vector<vec2f> texcoord;
std::vector<vec4ui> index;
rkcommon::index_sequence_2D iidx(vec2i(cols, rows));
// Generate each quad, each needs its own vertex coordinates w/ unique
// texcoords when we're testing w/ texture coordinates on
for (auto i : iidx) {
const int idx_start = vertex.size();
vertex.push_back(vec3f(i.x, i.y * 1.5f, 5.3f));
vertex.push_back(vec3f(i.x + 1.f, i.y * 1.5f, 5.3f));
vertex.push_back(vec3f(i.x + 1.f, (i.y + 1.f) * 1.5f, 5.3f));
vertex.push_back(vec3f(i.x, (i.y + 1.f) * 1.5f, 5.3f));
vertex.push_back(vec3f(i.x, i.y * 1.2f, 5.3f));
vertex.push_back(vec3f(i.x + 1.f, i.y * 1.2f, 5.3f));
vertex.push_back(vec3f(i.x + 1.f, (i.y + 1.f) * 1.2f, 5.3f));
vertex.push_back(vec3f(i.x, (i.y + 1.f) * 1.2f, 5.3f));
texcoord.push_back(vec2f(0.f, 0.f));
texcoord.push_back(vec2f(1.f, 0.f));
texcoord.push_back(vec2f(1.f, 1.f));
texcoord.push_back(vec2f(0.f, 1.f));
index.push_back(
vec4ui(idx_start, idx_start + 1, idx_start + 2, idx_start + 3));
}
cpp::Geometry mesh("mesh");
mesh.setParam("vertex.position", cpp::CopiedData(vertex));
if (std::get<2>(params)) {
if (std::get<3>(params)) {
mesh.setParam("vertex.texcoord", cpp::CopiedData(texcoord));
}
mesh.setParam("index", cpp::CopiedData(index));
mesh.setParam("quadSoup", true);
mesh.commit();
// create textures: columns=#channels, rows=type=[byte, byte, float, short]
std::array<OSPTextureFormat, 4 * 4> format = {OSP_TEXTURE_R8,
// create textures:
// columns=#channels, rows=type=[byte, byte, float, short, half]
std::array<OSPTextureFormat, 4 *rows> format = {OSP_TEXTURE_R8,
OSP_TEXTURE_RA8,
OSP_TEXTURE_RGB8,
OSP_TEXTURE_RGBA8,
@@ -67,16 +65,21 @@ void Texture2D::SetUp()
OSP_TEXTURE_SRGBA,
OSP_TEXTURE_R32F,
OSP_TEXTURE_R32F,
OSP_TEXTURE_RA32F,
OSP_TEXTURE_RGB32F,
OSP_TEXTURE_RGBA32F,
OSP_TEXTURE_R16,
OSP_TEXTURE_RA16,
OSP_TEXTURE_RGB16,
OSP_TEXTURE_RGBA16};
OSP_TEXTURE_RGBA16,
std::array<OSPDataType, 4 * 4> eltype = {OSP_UCHAR,
OSP_TEXTURE_R16F,
OSP_TEXTURE_RA16F,
OSP_TEXTURE_RGB16F,
OSP_TEXTURE_RGBA16F};
std::array<OSPDataType, 4 *rows> eltype = {OSP_UCHAR,
OSP_VEC2UC,
OSP_VEC3UC,
OSP_VEC4UC,
@@ -87,10 +90,15 @@ void Texture2D::SetUp()
OSP_VEC4UC,
OSP_FLOAT,
OSP_FLOAT,
OSP_VEC2F,
OSP_VEC3F,
OSP_VEC4F,
OSP_USHORT,
OSP_VEC2US,
OSP_VEC3US,
OSP_VEC4US,
OSP_USHORT,
OSP_VEC2US,
OSP_VEC3US,
@@ -99,22 +107,28 @@ void Texture2D::SetUp()
std::array<vec4uc, 15> dbyte;
std::array<vec4us, 15> dshort;
std::array<vec4f, 15> dfloat;
std::array<vec4us, 15> dhalf;
rkcommon::index_sequence_2D didx(vec2i(3, 5));
for (auto idx : didx) {
auto i = didx.flatten(idx);
// the center texel should be 127 / 32767 / 0.5, to test normal maps
dbyte[i] = vec4uc(idx.x * 85 + 42, idx.y * 50 + 27, 155, i * 17 + 8);
dbyte[i] = vec4uc(idx.x * 80 + 47, idx.y * 56 + 15, 204, i * 15 + 40);
dshort[i] = vec4us(
idx.x * 22768 + 9999, idx.y * 13000 + 6767, 33000, i * 4400 + 2200);
idx.x * 20480 + 12287, idx.y * 14336 + 4095, 52428, i * 3932 + 9830);
dfloat[i] = vec4f(idx.x * 0.3125f + 0.1875f,
idx.y * 0.21875f + 0.0625f,
0.8f,
i * 0.06f + 0.15f);
}
// float to half conversion
uint32_t *pf = (uint32_t *)dfloat.data();
uint16_t *ph = (uint16_t *)dhalf.data();
for (int i = 0; i < 4 * 15; i++, pf++, ph++)
*ph = (((*pf >> 23) - 112) << 10) | ((*pf >> 13) & 0x3ff);
std::array<void *, 4> addr = {
dbyte.data(), dbyte.data(), dfloat.data(), dshort.data()};
std::array<int, 4> stride = {4, 4, 16, 8};
std::array<void *, rows> addr = {
dbyte.data(), dbyte.data(), dfloat.data(), dshort.data(), dhalf.data()};
std::array<int, rows> stride = {4, 4, 16, 8, 8};
cpp::GeometricModel model(mesh);
std::array<cpp::Material, cols * rows> material;
@@ -163,11 +177,12 @@ void Texture2D::SetUp()
cpp::Light light2("distant");
// two light sets
if (std::get<1>(params)) {
if (std::get<2>(params)) {
// default light
light1.setParam("intensity", 3.f);
// highlighting normal direction
light2.setParam("direction", vec3f(0.7f, 0.2f, 0.f));
light2.setParam("intensity", 5.f);
light2.setParam("color", vec3f(0.f, 0.f, 0.5f));
} else {
// perpendicular bright lights, testing center normal
@@ -179,6 +194,8 @@ void Texture2D::SetUp()
AddLight(light1);
AddLight(light2);
renderer.setParam("mipMapBias", std::get<1>(params));
}
static cpp::Texture createTexture2D(uint32_t width = 32,
@@ -300,13 +317,15 @@ void Texture2DTransform::SetUp()
Texture2DWrapMode::Texture2DWrapMode()
{
rendererType = "scivis";
filter = GetParam();
}
void Texture2DWrapMode::SetUp()
{
Base::SetUp();
auto params = GetParam();
OSPTextureFilter filter = std::get<1>(params);
camera.setParam("position", vec3f(4.f, 4.f, -8.f));
camera.setParam("direction", vec3f(0.f, 0.f, 1.f));
camera.setParam("up", vec3f(0.f, 1.f, 0.f));
@@ -337,6 +356,54 @@ void Texture2DWrapMode::SetUp()
cpp::Light ambient("ambient");
ambient.setParam("intensity", 0.5f);
AddLight(ambient);
renderer.setParam("mipMapBias", std::get<0>(params));
}
Texture2DMipMapping::Texture2DMipMapping()
{
auto params = GetParam();
rendererType = std::get<0>(params);
samplesPerPixel = 4;
}
void Texture2DMipMapping::SetUp()
{
Base::SetUp();
auto params = GetParam();
auto builder = ospray::testing::newBuilder("mip_map_textures");
ospray::testing::setParam(builder, "filter", (uint32_t)std::get<2>(params));
ospray::testing::setParam(builder, "tcScale", std::get<4>(params));
ospray::testing::commit(builder);
world = ospray::testing::buildWorld(builder);
ospray::testing::release(builder);
std::string cameraType = std::get<1>(params);
camera = cpp::Camera(cameraType);
if (cameraType == "perspective")
camera.setParam("aspect", imgSize.x / (float)imgSize.y);
if (cameraType == "orthographic")
camera.setParam("height", 10.0f);
camera.setParam(
"position", vec3f(0.f, 0.f, cameraType == "panoramic" ? -4.f : -6.f));
OSPStereoMode stereoMode = std::get<5>(params);
if (cameraType == "perspective" || cameraType == "panoramic")
camera.setParam("stereoMode", stereoMode);
if (stereoMode == OSP_STEREO_TOP_BOTTOM) {
camera.setParam("imageStart", vec2f(0.25f));
camera.setParam("imageEnd", vec2f(0.75f));
}
renderer.setParam("mipMapBias", std::get<3>(params));
cpp::Light distant("distant");
distant.setParam("direction", vec3f(0.f, 0.f, 1.f));
distant.setParam("intensity", 3.f);
AddLight(distant);
}
RendererMaterialList::RendererMaterialList()
@@ -536,9 +603,18 @@ INSTANTIATE_TEST_SUITE_P(Appearance,
Texture2D,
::testing::Combine(::testing::Values(OSP_TEXTURE_FILTER_LINEAR,
OSP_TEXTURE_FILTER_NEAREST),
::testing::Values(0.0f),
::testing::Bool(),
::testing::Bool()));
INSTANTIATE_TEST_SUITE_P(AppearanceMipMap,
Texture2D,
::testing::Combine(::testing::Values(OSP_TEXTURE_FILTER_LINEAR,
OSP_TEXTURE_FILTER_NEAREST),
::testing::Values(6.0f),
::testing::Bool(),
::testing::Values(false)));
TEST_P(Texture2DTransform, simple)
{
PerformRenderTest();
@@ -554,7 +630,42 @@ TEST_P(Texture2DWrapMode, wrap)
INSTANTIATE_TEST_SUITE_P(Appearance,
Texture2DWrapMode,
::testing::Values(OSP_TEXTURE_FILTER_NEAREST, OSP_TEXTURE_FILTER_LINEAR));
::testing::Combine(::testing::Values(0.0f, 5.0f),
::testing::Values(
OSP_TEXTURE_FILTER_NEAREST, OSP_TEXTURE_FILTER_LINEAR)));
TEST_P(Texture2DMipMapping, mipMapping)
{
PerformRenderTest();
}
INSTANTIATE_TEST_SUITE_P(MipMap,
Texture2DMipMapping,
::testing::Combine(::testing::Values("scivis", "pathtracer", "ao"),
::testing::Values("perspective"),
::testing::Values(
OSP_TEXTURE_FILTER_NEAREST, OSP_TEXTURE_FILTER_LINEAR),
::testing::Values(0.0f, 1.0f),
::testing::Values(1.0f),
::testing::Values(OSP_STEREO_NONE)));
INSTANTIATE_TEST_SUITE_P(MipMapScale,
Texture2DMipMapping,
::testing::Combine(::testing::Values("pathtracer"),
::testing::Values("perspective"),
::testing::Values(OSP_TEXTURE_FILTER_LINEAR),
::testing::Values(1.0f),
::testing::Values(0.3f, 3.1f),
::testing::Values(OSP_STEREO_NONE)));
INSTANTIATE_TEST_SUITE_P(MipMapCamera,
Texture2DMipMapping,
::testing::Combine(::testing::Values("pathtracer"),
::testing::Values("perspective", "orthographic", "panoramic"),
::testing::Values(OSP_TEXTURE_FILTER_LINEAR),
::testing::Values(1.0f),
::testing::Values(1.0f),
::testing::Values(OSP_STEREO_NONE, OSP_STEREO_TOP_BOTTOM)));
TEST_P(PTBackgroundRefraction, backgroundRefraction)
{
+21 -8
View File
@@ -6,11 +6,11 @@
namespace OSPRayTestScenes {
// Test all texture image formats (and filter modes)
class Texture2D
: public Base,
public ::testing::TestWithParam<std::tuple<OSPTextureFilter /*filter*/,
bool /*lightset*/,
bool /*use texcoords*/>>
class Texture2D : public Base,
public ::testing::TestWithParam<std::tuple<OSPTextureFilter,
float /*mipMapBias*/,
bool /*lightset*/,
bool /*use texcoords*/>>
{
public:
Texture2D();
@@ -27,15 +27,28 @@ class Texture2DTransform : public Base,
class Texture2DWrapMode
: public Base,
public ::testing::TestWithParam<OSPTextureFilter /*filter*/>
public ::testing::TestWithParam<
std::tuple<float /*mipMapBias*/, OSPTextureFilter>>
{
OSPTextureFilter filter;
public:
Texture2DWrapMode();
void SetUp() override;
};
class Texture2DMipMapping
: public Base,
public ::testing::TestWithParam<std::tuple<const char * /*renderer*/,
const char * /*camera*/,
OSPTextureFilter,
float /*mipMapBias*/,
float /*scale*/,
OSPStereoMode>>
{
public:
Texture2DMipMapping();
void SetUp() override;
};
class RendererMaterialList : public Base,
public ::testing::TestWithParam<const char *>
{
+12
View File
@@ -163,3 +163,15 @@ TEST(Enums, RTCGeometryType)
ASSERT_EQ(OSP_DISC, RTC_GEOMETRY_TYPE_DISC_POINT);
ASSERT_EQ(OSP_ORIENTED_DISC, RTC_GEOMETRY_TYPE_ORIENTED_DISC_POINT);
}
#ifdef OSPRAY_MODULE_DENOISER
#include "OpenImageDenoise/oidn.h"
TEST(Enums, OIDNQuality)
{
ASSERT_LE(sizeof(OSPDenoiserQuality), sizeof(OIDNQuality));
ASSERT_EQ(OSP_DENOISER_QUALITY_LOW, OIDN_QUALITY_FAST);
ASSERT_EQ(OSP_DENOISER_QUALITY_MEDIUM, OIDN_QUALITY_BALANCED);
ASSERT_EQ(OSP_DENOISER_QUALITY_HIGH, OIDN_QUALITY_HIGH);
}
#endif
+3
View File
@@ -182,6 +182,9 @@ void FromOsprayTesting::SetUp()
camera.setParam("position", arcballCamera.eyePos());
camera.setParam("direction", arcballCamera.lookDir());
camera.setParam("up", arcballCamera.upDir());
if (rendererType == "pathtracer")
renderer.setParam("limitIndirectLightSamples", false);
}
void FromOsprayTestingMaxDepth::SetUp()
+5 -1
View File
@@ -39,6 +39,7 @@ void SpherePrecision::SetUp()
renderer.setParam("aoIntensity", 1.f);
} else if (rendererType == "pathtracer") {
renderer.setParam("maxPathLength", 2);
renderer.setParam("limitIndirectLightSamples", false);
}
cpp::Geometry sphere("sphere");
@@ -215,7 +216,8 @@ INSTANTIATE_TEST_SUITE_P(TestScenesGeometry,
"catmull-rom",
"linear_deprecated",
"linear",
"cones"),
"cones",
"bezier"),
::testing::Values("scivis", "pathtracer", "ao")));
INSTANTIATE_TEST_SUITE_P(TestScenesClipping,
@@ -250,6 +252,7 @@ INSTANTIATE_TEST_SUITE_P(TestScenesMaxDepth,
::testing::Values("ao"),
::testing::Values(16)));
/*
TEST_P(FromOsprayTestingVariance, testScenes)
{
PerformRenderTest();
@@ -259,6 +262,7 @@ TEST_P(FromOsprayTestingVariance, testScenes)
INSTANTIATE_TEST_SUITE_P(TestScenesVariance,
FromOsprayTestingVariance,
::testing::Values(std::make_tuple("cornell_box", "pathtracer", 4)));
*/
TEST_P(FromOsprayTestingLightSamples, testScenes)
{
+27 -8
View File
@@ -16,7 +16,8 @@ class ImageOpBase : public Base
void SetUp() override;
protected:
std::string imageOp;
std::string imageOpType;
cpp::ImageOperation imageOp;
};
void ImageOpBase::SetUp()
@@ -25,7 +26,7 @@ void ImageOpBase::SetUp()
instances.clear();
auto builder = ospray::testing::newBuilder("cornell_box");
auto builder = ospray::testing::newBuilder("random_discs");
ospray::testing::setParam(builder, "rendererType", rendererType);
ospray::testing::commit(builder);
@@ -34,13 +35,21 @@ void ImageOpBase::SetUp()
camera.setParam("position", vec3f(0.f, 0.f, -2.5f));
cpp::ImageOperation imgOp(imageOp);
framebuffer.setParam("imageOperation", cpp::CopiedData(imgOp));
imageOp = cpp::ImageOperation(imageOpType);
frames = 1;
framebuffer = cpp::FrameBuffer(imgSize.x,
imgSize.y,
frameBufferFormat,
OSP_FB_COLOR | OSP_FB_ALBEDO | OSP_FB_NORMAL);
framebuffer.setParam("imageOperation", cpp::CopiedData(imageOp));
framebuffer.commit();
}
#ifdef OSPRAY_MODULE_DENOISER
class DenoiserOp : public ImageOpBase, public ::testing::Test
class DenoiserOp : public ImageOpBase,
public ::testing::TestWithParam<
std::tuple<bool /*denoiseAlpha*/, OSPDenoiserQuality>>
{
public:
DenoiserOp()
@@ -48,11 +57,15 @@ class DenoiserOp : public ImageOpBase, public ::testing::Test
ospLoadModule("denoiser");
rendererType = "pathtracer";
imageOp = "denoiser";
imageOpType = "denoiser";
}
void SetUp() override
{
ImageOpBase::SetUp();
auto params = GetParam();
imageOp.setParam("denoiseAlpha", std::get<0>(params));
imageOp.setParam("quality", std::get<1>(params));
imageOp.commit();
}
};
#endif
@@ -66,7 +79,7 @@ class ImageOp
ImageOp()
{
auto params = GetParam();
imageOp = std::get<0>(params);
imageOpType = std::get<0>(params);
rendererType = std::get<1>(params);
}
void SetUp() override
@@ -78,10 +91,16 @@ class ImageOp
// Test Instantiations //////////////////////////////////////////////////////
#ifdef OSPRAY_MODULE_DENOISER
TEST_F(DenoiserOp, DenoiserOp)
TEST_P(DenoiserOp, DenoiserOp)
{
PerformRenderTest();
}
INSTANTIATE_TEST_SUITE_P(DenoiserOp,
DenoiserOp,
::testing::Combine(::testing::Bool(),
::testing::Values(OSP_DENOISER_QUALITY_LOW,
OSP_DENOISER_QUALITY_MEDIUM,
OSP_DENOISER_QUALITY_HIGH)));
#endif
TEST_P(ImageOp, ImageOp)
+1 -1
View File
@@ -180,7 +180,7 @@ void MotionBlurBoxes::SetUp()
n.x += 1.0f;
mnordata.push_back(cpp::CopiedData(nor));
for (vec3f &p : pos)
p = xfmPoint(quatf::rotate(vec3f(0.4, 0, 1), -0.1), p);
p = xfmPoint(quatf::rotate(vec3f(.4f, 0.f, 1.f), -.1f), p);
mposdata.push_back(cpp::CopiedData(pos));
for (vec3f &n : nor)
n.x -= 0.5f;
@@ -12,7 +12,7 @@
# should build the ospTutorial app from that install and NOT use your
# local build.
cmake_minimum_required(VERSION 3.1)
cmake_minimum_required(VERSION 3.5)
project(ospTutorialFindospray LANGUAGES C)
+1 -1
View File
@@ -15,7 +15,7 @@ if(OSPRAY_STRICT_BUILD)
set(OSPRAY_CXX_FLAGS "-Wno-header-hygiene ${OSPRAY_CXX_FLAGS}")
set(OSPRAY_CXX_FLAGS "-Wno-covered-switch-default ${OSPRAY_CXX_FLAGS}")
set(OSPRAY_CXX_FLAGS "-Wno-date-time ${OSPRAY_CXX_FLAGS}")
set(OSPRAY_CXX_FLAGS "-Wno-unsafe-buffer-usage ${OSPRAY_CXX_FLAGS}") #we use pointer arithmetics on buffers
set(OSPRAY_CXX_FLAGS "-Wno-unsafe-buffer-usage ${OSPRAY_CXX_FLAGS}") #we use pointer arithmetic on buffers
set(OSPRAY_CXX_FLAGS "-Wno-reserved-identifier ${OSPRAY_CXX_FLAGS}") #used in autogenerated ISPC headers
# Should try to fix and remove...
+296
View File
@@ -0,0 +1,296 @@
## Copyright 2024 Intel Corporation
## SPDX-License-Identifier: Apache-2.0
###############################################################################
## Generic ISPC macros/options ################################################
###############################################################################
set(ISPC_INCLUDE_DIR "")
macro (include_directories_ispc)
list(APPEND ISPC_INCLUDE_DIR ${ARGN})
endmacro ()
set(ISPC_DEFINITIONS "")
macro (add_definitions_ispc)
list(APPEND ISPC_DEFINITIONS ${ARGN})
endmacro ()
###############################################################################
## CPU specific macros/options ################################################
###############################################################################
## Find ISPC ##
find_program(ISPC_EXECUTABLE ispc HINTS ${ISPC_DIR_HINT} DOC "Path to the ISPC executable.")
if (NOT ISPC_EXECUTABLE)
message(FATAL_ERROR "Could not find ISPC. Exiting.")
else()
# Execute "ispc --version" and parse the version
execute_process(COMMAND ${ISPC_EXECUTABLE} "--version"
OUTPUT_VARIABLE ISPC_INFO)
string(REGEX MATCH "(.*), ([0-9]*\.[0-9]*\.[0-9]*[a-z]*) (.*)" _ ${ISPC_INFO})
set(ISPC_VERSION ${CMAKE_MATCH_2})
message(STATUS "Found ISPC v${ISPC_VERSION}: ${ISPC_EXECUTABLE}")
# Execute "ispc --help" and parse supported archs
execute_process(COMMAND ${ISPC_EXECUTABLE} "--help"
OUTPUT_VARIABLE ISPC_HELP)
string(REGEX MATCH "--arch={((([a-z,0-9,-])+, |([a-z,0-9,-])+)+)}" _ ${ISPC_HELP})
set(ISPC_ARCHS ${CMAKE_MATCH_1})
if ("${ISPC_ARCHS}" STREQUAL "")
message(WARNING "Can't determine ISPC supported architectures.")
else()
message(STATUS "ISPC supports: ${ISPC_ARCHS}")
string(REPLACE ", " ";" ISPC_ARCHS_LIST ${ISPC_ARCHS})
endif()
endif()
## ISPC config options ##
set(ISPC_ADDRESSING 32 CACHE STRING "32 vs 64 bit addressing in ispc")
set_property(CACHE ISPC_ADDRESSING PROPERTY STRINGS 32 64)
mark_as_advanced(ISPC_ADDRESSING)
macro(define_ispc_supported_arch ARCH_NAME ARCH_FILTER)
set(ISPC_ARCHS_${ARCH_NAME}_LIST ${ISPC_ARCHS_LIST})
list(FILTER ISPC_ARCHS_${ARCH_NAME}_LIST INCLUDE REGEX ${ARCH_FILTER})
list(LENGTH ISPC_ARCHS_${ARCH_NAME}_LIST ARCH_LENGTH)
if (${ARCH_LENGTH} GREATER 0)
set(ISPC_${ARCH_NAME}_ENABLED TRUE)
endif()
endmacro()
define_ispc_supported_arch(X86 "x86|x86-64")
define_ispc_supported_arch(ARM "arm|aarch64")
define_ispc_supported_arch(XE "xe64")
macro(define_ispc_isa_options ISA_NAME)
set(ISPC_TARGET_${ISA_NAME} ${ARGV1} CACHE STRING "ispc target used for ${ISA_NAME} ISA")
set_property(CACHE ISPC_TARGET_${ISA_NAME} PROPERTY STRINGS ${ARGN} NONE)
#mark_as_advanced(ISPC_TARGET_${ISA_NAME})
endmacro()
if (ISPC_X86_ENABLED)
define_ispc_isa_options(SSE4 sse4-i32x4 sse4-i32x8 sse4-i16x8 sse4-i8x16)
define_ispc_isa_options(AVX avx1-i32x8 avx1-i32x4 avx1-i32x16 avx1-i64x4)
define_ispc_isa_options(AVX2 avx2-i32x8 avx2-i32x4 avx2-i32x16 avx2-i64x4)
define_ispc_isa_options(AVX512KNL avx512knl-x16)
define_ispc_isa_options(AVX512SKX avx512skx-x16 avx512skx-x8)
define_ispc_isa_options(AVX512SPR avx512spr-x16 avx512spr-x8)
endif()
macro(append_ispc_target_list ISA_NAME)
set(_TARGET_NAME ISPC_TARGET_${ISA_NAME})
if (NOT ${_TARGET_NAME} STREQUAL "NONE")
list(APPEND ISPC_TARGET_LIST ${${_TARGET_NAME}})
endif()
unset(_TARGET_NAME)
endmacro()
unset(ISPC_TARGET_LIST)
if (ISPC_X86_ENABLED)
append_ispc_target_list(SSE4)
append_ispc_target_list(AVX)
append_ispc_target_list(AVX2)
append_ispc_target_list(AVX512KNL)
append_ispc_target_list(AVX512SKX)
if (NOT APPLE)
append_ispc_target_list(AVX512SPR)
endif()
endif()
## Macros ##
macro (ispc_read_dependencies ISPC_DEPENDENCIES_FILE)
set(ISPC_DEPENDENCIES "")
if (EXISTS ${ISPC_DEPENDENCIES_FILE})
file(READ ${ISPC_DEPENDENCIES_FILE} contents)
string(REPLACE " " ";" contents "${contents}")
string(REPLACE ";" "\\\\;" contents "${contents}")
string(REPLACE "\n" ";" contents "${contents}")
foreach(dep ${contents})
if (EXISTS ${dep})
set(ISPC_DEPENDENCIES ${ISPC_DEPENDENCIES} ${dep})
endif (EXISTS ${dep})
endforeach(dep ${contents})
endif ()
endmacro()
macro (ispc_compile)
cmake_parse_arguments(ISPC_COMPILE "" "TARGET" "" ${ARGN})
set(ISPC_ADDITIONAL_ARGS "")
if (OSPRAY_STRICT_BUILD)
list(APPEND ISPC_ADDITIONAL_ARGS --wno-perf)
else()
list(APPEND ISPC_ADDITIONAL_ARGS --woff)
endif()
# Check if CPU target is passed externally
if (NOT ISPC_TARGET_CPU)
set(ISPC_TARGETS ${ISPC_TARGET_LIST})
else()
set(ISPC_TARGETS ${ISPC_TARGET_CPU})
endif()
set(ISPC_TARGET_EXT ${CMAKE_CXX_OUTPUT_EXTENSION})
string(REPLACE ";" "," ISPC_TARGET_ARGS "${ISPC_TARGETS}")
if (CMAKE_SIZEOF_VOID_P EQUAL 8)
if (${CMAKE_SYSTEM_PROCESSOR} MATCHES "arm64|aarch64")
set(ISPC_ARCHITECTURE "aarch64")
else()
set(ISPC_ARCHITECTURE "x86-64")
endif()
else()
set(ISPC_ARCHITECTURE "x86")
endif()
file(RELATIVE_PATH ISPC_TARGET_DIR_RELATIVE ${CMAKE_BINARY_DIR} ${CMAKE_CURRENT_BINARY_DIR})
set(ISPC_TARGET_DIR ${CMAKE_BINARY_DIR}/${ISPC_TARGET_DIR_RELATIVE})
include_directories(${ISPC_TARGET_DIR})
if(ISPC_INCLUDE_DIR)
string(REPLACE ";" ";-I;" ISPC_INCLUDE_DIR_PARMS "${ISPC_INCLUDE_DIR}")
set(ISPC_INCLUDE_DIR_PARMS "-I" ${ISPC_INCLUDE_DIR_PARMS})
endif()
if (NOT CMAKE_BUILD_TYPE)
set (CMAKE_BUILD_TYPE "Release")
endif()
#CAUTION: -O0/1 -g with ispc seg faults
set(ISPC_FLAGS_DEBUG "-g" CACHE STRING "ISPC Debug flags")
mark_as_advanced(ISPC_FLAGS_DEBUG)
set(ISPC_FLAGS_RELEASE "-O3" CACHE STRING "ISPC Release flags")
mark_as_advanced(ISPC_FLAGS_RELEASE)
set(ISPC_FLAGS_RELWITHDEBINFO "-O2 -g" CACHE STRING "ISPC Release with Debug symbols flags")
mark_as_advanced(ISPC_FLAGS_RELWITHDEBINFO)
if ("${CMAKE_BUILD_TYPE}" STREQUAL "Release")
set(ISPC_OPT_FLAGS ${ISPC_FLAGS_RELEASE})
elseif ("${CMAKE_BUILD_TYPE}" STREQUAL "Debug")
set(ISPC_OPT_FLAGS ${ISPC_FLAGS_DEBUG})
elseif ("${CMAKE_BUILD_TYPE}" STREQUAL "RelWithDebInfo")
set(ISPC_OPT_FLAGS ${ISPC_FLAGS_RELWITHDEBINFO})
else ()
message(FATAL_ERROR "CMAKE_BUILD_TYPE (${CMAKE_BUILD_TYPE}) allows only the following values: Debug;Release;RelWithDebInfo")
endif()
# turn space separated list into ';' separated list
string(REPLACE " " ";" ISPC_OPT_FLAGS "${ISPC_OPT_FLAGS}")
if (NOT WIN32)
list(APPEND ISPC_ADDITIONAL_ARGS --pic)
endif()
if (NOT "${CMAKE_BUILD_TYPE}" STREQUAL "Debug")
list(APPEND ISPC_ADDITIONAL_ARGS --opt=disable-assertions)
endif()
# Also set the target-local include directories and defines if
# we were given a target name
set(ISPC_INCLUDE_DIRS_EXPR "")
set(ISPC_COMPILE_DEFINITIONS_EXPR "")
if (NOT "${ISPC_COMPILE_TARGET}" STREQUAL "")
set(ISPC_INCLUDE_DIRS_EXPR
"$<TARGET_PROPERTY:${ISPC_COMPILE_TARGET},INCLUDE_DIRECTORIES>")
set(ISPC_COMPILE_DEFINITIONS_EXPR
"$<TARGET_PROPERTY:${ISPC_COMPILE_TARGET},COMPILE_DEFINITIONS>")
endif()
set(ISPC_OBJECTS "")
foreach(src ${ISPC_COMPILE_UNPARSED_ARGUMENTS})
get_filename_component(fname ${src} NAME_WE)
# The src_relpath will usually be the same as getting the DIRECTORY
# component of the src file name, but we go through the full path
# computation path to handle cases where the src name is an absolute
# file path in some other location, where we need to compute a path to
get_filename_component(src_dir ${src} ABSOLUTE)
file(RELATIVE_PATH src_relpath ${CMAKE_CURRENT_LIST_DIR} ${src_dir})
get_filename_component(src_relpath ${src_relpath} DIRECTORY)
# Remove any relative paths up from the relative path
string(REPLACE "../" "_/" src_relpath "${src_relpath}")
set(outdir "${ISPC_TARGET_DIR}/${src_relpath}")
set(outdir_relative "${ISPC_TARGET_DIR_RELATIVE}/${src_relpath}")
set(input ${CMAKE_CURRENT_SOURCE_DIR}/${src})
set(ISPC_DEPENDENCIES_FILE ${outdir}/${fname}.dev.idep)
ispc_read_dependencies(${ISPC_DEPENDENCIES_FILE})
set(results "${outdir}/${fname}.dev${ISPC_TARGET_EXT}")
# if we have multiple targets add additional object files
list(LENGTH ISPC_TARGETS NUM_TARGETS)
if (NUM_TARGETS GREATER 1)
foreach(target ${ISPC_TARGETS})
string(REGEX REPLACE "-(i(8|16|32|64))?x(4|8|16|32|64)" "" target ${target})
string(REPLACE "avx1" "avx" target ${target})
list(APPEND results "${outdir}/${fname}.dev_${target}${ISPC_TARGET_EXT}")
endforeach()
endif()
# use relative path for generated header file, because the path is
# included as comment and the header will be distributed
set(headerfile "${outdir}/${fname}_ispc.h")
file(RELATIVE_PATH headerfile ${CMAKE_CURRENT_BINARY_DIR} ${headerfile})
add_custom_command(
OUTPUT ${results} ${outdir}/${fname}_ispc.h
COMMAND ${CMAKE_COMMAND} -E make_directory ${outdir}
COMMAND ${ISPC_EXECUTABLE}
${ISPC_DEFINITIONS}
-I ${CMAKE_CURRENT_SOURCE_DIR}
"$<$<BOOL:${ISPC_INCLUDE_DIRS_EXPR}>:-I$<JOIN:${ISPC_INCLUDE_DIRS_EXPR},;-I>>"
${ISPC_INCLUDE_DIR_PARMS}
"$<$<BOOL:${ISPC_COMPILE_DEFINITIONS_EXPR}>:-D$<JOIN:${ISPC_COMPILE_DEFINITIONS_EXPR},;-D>>"
--arch=${ISPC_ARCHITECTURE}
--addressing=${ISPC_ADDRESSING}
${ISPC_OPT_FLAGS}
--target=${ISPC_TARGET_ARGS}
--opt=fast-math
${ISPC_ADDITIONAL_ARGS}
-h ${headerfile}
-MMM ${ISPC_DEPENDENCIES_FILE}
-o ${outdir}/${fname}.dev${ISPC_TARGET_EXT}
${input}
DEPENDS ${input} ${ISPC_DEPENDENCIES}
COMMENT "Building ISPC object ${outdir_relative}/${fname}.dev${ISPC_TARGET_EXT}"
COMMAND_EXPAND_LISTS
VERBATIM
)
list(APPEND ISPC_OBJECTS ${results})
# avoid race conditions if multiple targets compile the same ispc source file
string(REPLACE "/" "_" dep_target "compile__${src}")
if (NOT TARGET ${dep_target})
add_custom_target(${dep_target} DEPENDS ${results})
endif()
list(APPEND ISPC_DEPENDENCY_TARGETS ${dep_target})
endforeach()
endmacro()
###############################################################################
## Generic kernel compilation #################################################
###############################################################################
# Kept for backwards compatibility with existing CPU projects
function(ispc_target_add_sources name)
## Split-out C/C++ from ISPC files ##
set(ISPC_SOURCES "")
get_property(TARGET_SOURCES TARGET ${name} PROPERTY SOURCES)
foreach(src ${ARGN})
get_filename_component(ext ${src} EXT)
if (ext STREQUAL ".ispc")
list(APPEND ISPC_SOURCES ${src})
else()
list(APPEND TARGET_SOURCES ${src})
endif()
endforeach()
if (ISPC_SOURCES)
ispc_compile(${ISPC_SOURCES})
list(APPEND TARGET_SOURCES ${ISPC_OBJECTS})
add_dependencies(${name} ${ISPC_DEPENDENCY_TARGETS})
endif()
set_target_properties(${name} PROPERTIES SOURCES "${TARGET_SOURCES}")
endfunction()
+5 -8
View File
@@ -12,10 +12,12 @@ set(OSPRAY_CMAKECONFIG_DIR
"${CMAKE_INSTALL_LIBDIR}/cmake/ospray-${OSPRAY_VERSION}")
set(ISPC_VERSION_REQUIRED 1.23.0)
set(RKCOMMON_VERSION_REQUIRED 1.13.0)
set(EMBREE_VERSION_REQUIRED 4.3.1)
set(RKCOMMON_VERSION_REQUIRED 1.14.0)
set(EMBREE_VERSION_REQUIRED 4.3.3)
set(OPENVKL_VERSION_REQUIRED 2.0.1)
set(OIDN_VERSION_REQUIRED 2.2.0)
set(OIDN_VERSION_REQUIRED 2.3.0)
set(OSPRAY_IMGUI_GIT_TAG cb16be3a3fc1f9cd146ae24d52b615f8a05fa93d) # v1.90.9
set(OSPRAY_STB_GIT_TAG 013ac3beddff3dbffafd5177e7972067cd2b5083) # v2.30 / v1.16
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR})
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR})
@@ -82,11 +84,6 @@ get_target_property(RKCOMMON_INCLUDE_DIRS rkcommon::rkcommon
ospray_find_embree(${EMBREE_VERSION_REQUIRED} FALSE)
ospray_verify_embree_features()
# ISPC
set_property(GLOBAL PROPERTY FIND_LIBRARY_USE_LIB64_PATHS ON)
find_package(ispcrt ${ISPC_VERSION_REQUIRED} REQUIRED)
set(ISPC_FAST_MATH ON)
# Open VKL
if (OSPRAY_ENABLE_VOLUMES)
ospray_find_openvkl(${OPENVKL_VERSION_REQUIRED} FALSE)
-2
View File
@@ -56,8 +56,6 @@ macro(ospray_add_dependent_lib_plugins TARGET_NAME PLUGINS_PATTERN VER_PATTERN)
endif()
endmacro()
ospray_add_dependent_lib(ispcrt::ispcrt)
ospray_add_dependent_lib_plugins(ispcrt::ispcrt "ispcrt_device_*" "")
ospray_add_dependent_lib(rkcommon::rkcommon)
if (RKCOMMON_TASKING_TBB)
ospray_add_dependent_lib(TBB::tbb)
+1 -1
View File
@@ -2,7 +2,7 @@
## SPDX-License-Identifier: Apache-2.0
set(OSPRAY_VERSION_MAJOR 3)
set(OSPRAY_VERSION_MINOR 1)
set(OSPRAY_VERSION_MINOR 2)
set(OSPRAY_VERSION_PATCH 0)
set(OSPRAY_SOVERSION 3)
set(OSPRAY_VERSION_GITHASH 0)
+6 -1
View File
@@ -79,7 +79,12 @@ set(CPACK_PACKAGE_FILE_NAME "ospray-${OSPRAY_VERSION}")
#set(CPACK_PACKAGE_RELOCATABLE TRUE)
# do not disable, stripping symbols is important for security reasons
set(CPACK_STRIP_FILES TRUE)
# except on Windows, where stripping is usually not supported/required; but on
# some systems it is done via llvm-strip, which only slightly changes the
# binary, enough to invalidate code signatures
if (NOT WIN32)
set(CPACK_STRIP_FILES TRUE)
endif()
set(CPACK_PACKAGE_VERSION_MAJOR ${OSPRAY_VERSION_MAJOR})
set(CPACK_PACKAGE_VERSION_MINOR ${OSPRAY_VERSION_MINOR})
+230 -116
View File
@@ -100,33 +100,38 @@ to set parameters on the device. The semantics of setting parameters is
exactly the same as `ospSetParam`, which is documented below in the
[parameters] section. The following parameters can be set on all devices:
------ ------------ ----------------------------------------------------------
Type Name Description
------ ------------ ----------------------------------------------------------
int numThreads number of threads which OSPRay should use
------ ------------------------ ----------------------------------------------
Type Name Description
------ ------------------------ ----------------------------------------------
int numThreads number of threads which OSPRay should use
uint logLevel logging level; valid values (in order of severity) are
`OSP_LOG_NONE`, `OSP_LOG_ERROR`, `OSP_LOG_WARNING`,
`OSP_LOG_INFO`, and `OSP_LOG_DEBUG`
bool disableMipMapGeneration disable the default generation of MIP maps for
textures (e.g., to save the additional memory
needed)
string logOutput convenience for setting where status messages go; valid
values are `cerr` and `cout`
uint logLevel logging level; valid values (in order of
severity) are `OSP_LOG_NONE`, `OSP_LOG_ERROR`,
`OSP_LOG_WARNING`, `OSP_LOG_INFO`, and
`OSP_LOG_DEBUG`
string errorOutput convenience for setting where error messages go; valid
values are `cerr` and `cout`
string logOutput convenience for setting where status messages
go; valid values are `cerr` and `cout`
bool debug set debug mode; equivalent to `logLevel=debug` and
`numThreads=1`
string errorOutput convenience for setting where error messages
go; valid values are `cerr` and `cout`
bool warnAsError send `warning` and `error` messages through the error
callback, otherwise send `warning` messages through
the message callback; must have sufficient `logLevel` to
enable warnings
bool debug set debug mode; equivalent to `logLevel=debug`
and `numThreads=1`
bool setAffinity bind software threads to hardware threads if set to 1;
0 disables binding omitting the parameter will let OSPRay
choose
------ ------------ ----------------------------------------------------------
bool warnAsError send `warning` and `error` messages through
the error callback, otherwise send `warning`
messages through the message callback; must
have sufficient `logLevel` to enable warnings
bool setAffinity bind software threads to hardware threads if
set to 1; 0 disables binding omitting the
parameter will let OSPRay choose
------ ------------------------ ----------------------------------------------
: Parameters shared by all devices.
Once parameters are set on the created device, the device must be
@@ -453,6 +458,8 @@ below.
OSP_FRAMEBUFFER framebuffer object reference
OSP_FUTURE future object reference
OSP_LIGHT light object reference
OSP_MATERIAL material object reference
@@ -463,16 +470,26 @@ below.
OSP_WORLD world object reference
OSP_GROUP group object reference
OSP_INSTANCE instance object reference
OSP_GEOMETRY geometry object reference
OSP_GEOMETRIC_MODEL geometric model object reference
OSP_VOLUME volume object reference
OSP_VOLUMETRIC_MODEL volumetric model object reference
OSP_TRANSFER_FUNCTION transfer function object reference
OSP_IMAGE_OPERATION image operation object reference
OSP_STRING C-style zero-terminated character string
OSP_BOOL 8\ bit boolean
OSP_CHAR, OSP_VEC[234]C 8\ bit signed character scalar and [234]-element vector
OSP_UCHAR, OSP_VEC[234]UC 8\ bit unsigned character scalar and [234]-element vector
@@ -846,7 +863,7 @@ the `cell.type` parameter must be omitted).
uint8[] cell.type [data] array of cell types (VTK
compatible), only set if `indexPrefixed
= false` false. Supported types are:
= false`. Supported types are:
`OSP_TETRAHEDRON`
@@ -1109,22 +1126,60 @@ A mesh consisting of either triangles or quads is created by calling
`ospNewGeometry` with type string "`mesh`". Once created, a mesh
recognizes the following parameters:
-------------------- ----------------------- ---------------------------------
Type Name Description
-------------------- ----------------------- -------------------------------------------------
vec3f[] vertex.position [data] array of vertex positions, overridden by `motion.*` arrays
vec3f[] normal [data] array of face-varying normals, overridden by `motion.*` arrays
vec3f[] vertex.normal [data] array of vertex-varying normals, overridden by `motion.*` arrays
vec4f[] / vec3f[] color [data] array of face-varying colors (linear RGBA/RGB)
vec4f[] / vec3f[] vertex.color [data] array of vertex-varying colors (linear RGBA/RGB)
vec2f[] texcoord [data] array of face-varying texture coordinates
vec2f[] vertex.texcoord [data] array of vertex-varying texture coordinates
vec3ui[] / vec4ui[] index [data] array of (either triangle or quad) indices (into the vertex array(s))
bool quadSoup when no explicit `index` is given, indicates whether to assume a 'soup' of quads instead of triangles, default false
vec3f[][] motion.vertex.position [data] array of vertex position arrays (uniformly distributed keys for deformation motion blur)
vec3f[][] motion.normal [data] array of face-varying normal arrays (uniformly distributed keys for deformation motion blur)
vec3f[][] motion.vertex.normal [data] array of vertex-varying normal arrays (uniformly distributed keys for deformation motion blur)
box1f time time associated with first and last key in `motion.*` arrays (for deformation motion blur), default [0, 1]
-------------------- ----------------------- -------------------------------------------------
-------------------- ----------------------- ---------------------------------
vec3f[] vertex.position [data] array of vertex positions,
overridden by `motion.*` arrays
vec3f[] normal [data] array of face-varying
normals, overridden by `motion.*`
arrays
vec3f[] vertex.normal [data] array of vertex-varying
normals, overridden by `motion.*`
arrays
vec4f[] / vec3f[] color [data] array of face-varying
colors (linear RGBA/RGB)
vec4f[] / vec3f[] vertex.color [data] array of vertex-varying
colors (linear RGBA/RGB)
vec2f[] texcoord [data] array of face-varying
texture coordinates
vec2f[] vertex.texcoord [data] array of vertex-varying
texture coordinates
vec3ui[] / vec4ui[] index [data] array of (either triangle
or quad) indices (into the vertex
array(s))
bool quadSoup when no explicit `index` is
given, indicates whether to
assume a 'soup' of quads instead
of triangles, default false
vec3f[][] motion.vertex.position [data] array of vertex position
arrays (uniformly distributed
keys for deformation motion blur)
vec3f[][] motion.normal [data] array of face-varying
normal arrays (uniformly
distributed keys for deformation
motion blur)
vec3f[][] motion.vertex.normal [data] array of vertex-varying
normal arrays (uniformly
distributed keys for deformation
motion blur)
box1f time time associated with first and
last key in `motion.*` arrays
(for deformation motion blur),
default [0, 1]
-------------------- ----------------------- ---------------------------------
: Parameters defining a mesh geometry.
The data type of index arrays differentiates between the underlying
@@ -1143,6 +1198,17 @@ i.e., each four subsequent vertices form one quad. If the size of the
`vertex.position` array is not a multiple of three for triangles or four
for quads, the remainder vertices are ignored.
Face-varying attributes (`normal`, `motion.normal`, `color`, `texcoord`)
map unique values to each vertex of a primitive/face (triangle or quad),
thus attributes can be different for the same vertex that is shared by
multiple primitives. Essentially, face-varying attributes are a
'attribute soup' and behave similar to the implicit index, the size of
the array must be at least three times the number of triangles or four
times the number of quads, respectively. Face-varying attributes take
precedence over the respective vertex attributes (`vertex.normal`,
`motion.vertex.normal`, `vertex.color`, `vertex.texcoord`) when both
arrays of the same attribute are present.
### Subdivision
A mesh consisting of subdivision surfaces, created by specifying a
@@ -1509,7 +1575,7 @@ specific light source).
assuming the light is oriented towards to the
surface, unit is W/m^2^
OSP_INTENSITY_QUANTITY_SCALE a linear scaling factor for light sources with a
OSP_INTENSITY_QUANTITY_SCALE a linear scaling factor for light sources with a
built-in quantity (e.g., `HDRI`, or `sunSky`, or
when using `intensityDistribution`).
---------------------------------- ----------------------------------------------------
@@ -1609,7 +1675,7 @@ tracer]).
The spotlight is a light emitting into a cone of directions. It is
created by passing the type string "`spot`" to `ospNewLight`. The
spotlight
spotlight
supports only `OSP_INTENSITY_QUANTITY_SCALE` when
`intensityDistribution` is set, or otherwise
`OSP_INTENSITY_QUANTITY_POWER`,
@@ -1689,7 +1755,7 @@ shadows.
The cylinder light is a cylinderical, procedural area light source
emitting uniformly outwardly into the space beyond the boundary. It is
created by passing the type string "`cylinder`" to `ospNewLight`. The
created by passing the type string "`cylinder`" to `ospNewLight`. The
cylinder light supports `OSP_INTENSITY_QUANTITY_POWER`,
`OSP_INTENSITY_QUANTITY_INTENSITY` and `OSP_INTENSITY_QUANTITY_RADIANCE`
(default) as `intensityQuantity` parameter. In addition to the [general
@@ -1706,7 +1772,7 @@ the following special parameters:
Note that only renderers that use stochastic sampling (like the path
tracer) will compute soft shadows from the cylinder light. Other renderers
will just sample the closest point on the cylinder light, which results in
will just sample the closest point on the cylinder light, which results in
hard shadows.
### HDRI Light
@@ -1714,8 +1780,8 @@ hard shadows.
The HDRI light is a textured light source surrounding the scene and
illuminating it from infinity. It is created by passing the type string
"`hdri`" to `ospNewLight`. The values of the HDRI correspond to radiance
and therefore the HDRI light only accepts `OSP_INTENSITY_QUANTITY_SCALE`
as `intensityQuantity` parameter value.
and therefore the HDRI light only accepts `OSP_INTENSITY_QUANTITY_SCALE`
as `intensityQuantity` parameter value.
In addition to the [general parameters](#lights) the HDRI light
supports the following special parameters:
@@ -2211,9 +2277,9 @@ thus individual flakes are not visible.
The [path tracer] supports the Luminous material which emits light
uniformly in all directions and which can thus be used to turn any
geometric object into a light source. It is created by passing the type
string "`luminous`" to `ospNewMaterial`. The amount of constant radiance
that is emitted is determined by combining the general parameters of
geometric object into a light source. It is created by passing the type
string "`luminous`" to `ospNewMaterial`. The amount of constant radiance
that is emitted is determined by combining the general parameters of
lights: [`color` and `intensity`](#lights) (which essentially means that
parameter `intensityQuantity` is not needed because it is always
`OSP_INTENSITY_QUANTITY_RADIANCE`).
@@ -2222,7 +2288,7 @@ parameter `intensityQuantity` is not needed because it is always
------ ------------ -------- ---------------------------------------
vec3f color white color of the emitted light (linear RGB)
float intensity 1 intensity of the light (a factor)
float transparency 1 material transparency
float transparency 0 material transparency
------ ------------ -------- ---------------------------------------
: Parameters accepted by the Luminous material.
@@ -2266,14 +2332,19 @@ The supported texture formats for `texture2d` are:
OSP_TEXTURE_RGBA8 8\ bit [0–255] linear components red, green, blue, alpha
OSP_TEXTURE_SRGBA 8\ bit sRGB gamma encoded color components, and linear alpha
OSP_TEXTURE_RGBA32F 32\ bit float components red, green, blue, alpha
OSP_TEXTURE_RGBA16F 16\ bit float components red, green, blue, alpha
OSP_TEXTURE_RGB8 8\ bit [0–255] linear components red, green, blue
OSP_TEXTURE_SRGB 8\ bit sRGB gamma encoded components red, green, blue
OSP_TEXTURE_RGB32F 32\ bit float components red, green, blue
OSP_TEXTURE_RGB16F 16\ bit float components red, green, blue
OSP_TEXTURE_R8 8\ bit [0–255] linear single component red
OSP_TEXTURE_RA8 8\ bit [0–255] linear two components red, alpha
OSP_TEXTURE_L8 8\ bit [0–255] gamma encoded luminance (replicated into red, green, blue)
OSP_TEXTURE_LA8 8\ bit [0–255] gamma encoded luminance, and linear alpha
OSP_TEXTURE_RA32F 32\ bit float two component red, alpha
OSP_TEXTURE_R32F 32\ bit float single component red
OSP_TEXTURE_RA16F 16\ bit float two component red, alpha
OSP_TEXTURE_R16F 16\ bit float single component red
OSP_TEXTURE_RGBA16 16\ bit [0–65535] linear components red, green, blue, alpha
OSP_TEXTURE_RGB16 16\ bit [0–65535] linear components red, green, blue
OSP_TEXTURE_RA16 16\ bit [0–65535] linear two components red, alpha
@@ -2728,7 +2799,8 @@ General parameters of all renderers are
-------------- ------------------ ----------------------- -----------------------------------------
Type Name Default Description
-------------- ------------------ ----------------------- -----------------------------------------
int pixelSamples 1 samples per pixel
int pixelSamples 1 samples per pixel, best results when a
power of 2
int maxPathLength 20 maximum ray recursion depth
@@ -2740,8 +2812,8 @@ General parameters of all renderers are
float / backgroundColor black, background color and alpha (linear
vec3f / vec4f transparent A/RGB/RGBA), if no `map_backplate` is set
OSPTexture map_backplate optional [texture] image used as background
(use texture type `texture2d`)
OSPTexture map_backplate optional [texture] image used as
background (use texture type `texture2d`)
OSPTexture map_maxDepth optional screen-sized float [texture]
with maximum far distance per pixel
@@ -2755,6 +2827,10 @@ General parameters of all renderers are
filter used by the renderer for
antialiasing. Possible pixel filters
are listed below.
float mipMapBias 0 bias for texture MIP-mapping, balancing
between sharpness/aliasing and
blurriness due to prefiltering
-------------- ------------------ ----------------------- -----------------------------------------
: Parameters understood by all renderers.
@@ -2767,7 +2843,8 @@ refinement of image regions that have an estimated variance below the
Per default the background of the rendered image will be transparent
black, i.e., the alpha channel holds the opacity of the rendered
objects. This eases transparency-aware blending of the image with an
arbitrary background image by the application. The parameter
arbitrary background image by the application (via $ospray.rgb +
appBackground.rgb⋅(1-ospray.alpha)$). The parameter
`backgroundColor` or `map_backplate` can be used to already blend with a
constant background color or backplate texture, respectively, (and
alpha) during rendering.
@@ -2781,7 +2858,7 @@ distance of primary rays, thus objects of other renderers can hide
objects rendered by OSPRay.
OSPRay supports antialiasing in image space by using pixel filters,
which are centered around the center of a pixel. The size $w×w$ of the
which are aligned around the center of a pixel. The size $w×w$ of the
filter depends on the selected filter type. The types of supported pixel
filters are defined by the `OSPPixelFilterType` enum and can be set
using the `pixelFilter` parameter.
@@ -2806,6 +2883,14 @@ using the `pixelFilter` parameter.
-------------------------------- ---------------------------------------------
: Pixel filter types supported by OSPRay for antialiasing in image space.
OSPRay also antialiases textures with prefiltering and MIP-mapping,
which can be adjusted with parameter `mipMapBias`. For final frame
rendering with a high number of `pixelSamples` or accumulated frames
`mipMapBias` can be lowered (e.g., set to -0.5 or -2) to result in sharper
textures which are essentially anisotropically filtered. Conversely, for
preview rendering with just a single sample per pixel a higher
`mipMapBias` of 1 or 2 can reduce texture aliasing and increase
rendering speed.
### SciVis Renderer
@@ -2874,27 +2959,34 @@ realistic materials. This renderer is created by passing the type string
parameters](#renderer) understood by all renderers the path tracer
supports the following special parameters:
---------- -------------------- -------- ------------------------------------
Type Name Default Description
---------- -------------------- -------- ------------------------------------
int lightSamples all number of random light samples
per path vertex, per default
all light sources are sampled
------ -------------------------- -------- ----------------------------------
Type Name Default Description
------ -------------------------- -------- ----------------------------------
int lightSamples all number of random light samples
per path vertex, best results
when a power of 2; per default
all light sources are sampled
int roulettePathLength 5 ray recursion depth at which to
start Russian roulette termination
bool limitIndirectLightSamples true after the first non-specular
(i.e., diffuse and glossy) path
vertex take (at most) a single
light sample (instead of
`lightSamples` many)
int maxScatteringEvents 20 maximum number of non-specular
(i.e., diffuse and glossy) bounces
int roulettePathLength 5 ray recursion depth at which to
start Russian roulette termination
float maxContribution ∞ samples are clamped to this value
before they are accumulated into
the framebuffer
int maxScatteringEvents 20 maximum number of non-specular
(i.e., diffuse and glossy) bounces
bool backgroundRefraction false allow for alpha blending even if
background is seen through
refractive objects like glass
---------- -------------------- -------- ------------------------------------
float maxContribution ∞ samples are clamped to this value
before they are accumulated into
the framebuffer
bool backgroundRefraction false allow for alpha blending even if
background is seen through
refractive objects like glass
------ -------------------------- -------- ----------------------------------
: Special parameters understood by the path tracer.
The path tracer requires that [materials] are assigned to [geometries],
@@ -2941,7 +3033,7 @@ values of `OSPFrameBufferChannel` listed in the table below.
OSP_FB_ACCUM accumulation buffer for progressive refinement
OSP_FB_VARIANCE for estimation of the current noise level if OSP_FB_ACCUM is also present, see [rendering]
OSP_FB_NORMAL accumulated world-space normal of the first non-specular hit, as vec3f
OSP_FB_ALBEDO accumulated material albedo (color without illumination) at the first hit, as vec3f
OSP_FB_ALBEDO accumulated material albedo (color without illumination) at the first non-specular hit, as vec3f
OSP_FB_ID_PRIMITIVE primitive index of the first hit, as uint32
OSP_FB_ID_OBJECT geometric/volumetric model `id`, if specified, or index in [group] of first hit, as uint32
OSP_FB_ID_INSTANCE user defined [instance] `id`, if specified, or instance index of first hit, as uint32
@@ -3006,12 +3098,24 @@ The framebuffer takes a list of pixel operations to be applied to the image
in sequence as an `OSPData`. The pixel operations will be run in the order
they are in the array.
-------------------- --------------- -----------------------------------------
Type Name Description
-------------------- --------------- ---------------------------------------
-------------------- --------------- -----------------------------------------
OSPImageOperation[] imageOperation ordered sequence of image operations
-------------------- --------------- ---------------------------------------
int targetFrames anticipated number of frames that will be
accumulated for progressive refinement,
used renderers to generate a blue noise
sampling pattern; should be a power of 2,
is always 1 without `OSP_FB_ACCUM`;
default 0 (disabled)
-------------------- --------------- -----------------------------------------
: Parameters accepted by the framebuffer.
If the total number of frames to be accumulated is known, then
`targetFrames` should be set, because then renderers can generate more
pleasing blue noise patterns. Accumulation stops when `targetFrames` is
reached.
### Image Operation
@@ -3030,43 +3134,31 @@ Color Encoding System (ACES). The tone mapper is created by passing the type
string "`tonemapper`" to `ospNewImageOperation`. The tone mapping curve can be
customized using the parameters listed in the table below.
------ ---------- --------- -----------------------------------------
Type Name Default Description
------ ---------- --------- -----------------------------------------
float exposure 1.0 amount of light per unit area
------ ---------- --------- --------- -----------------------------------------
Type Name Default Filmic Description
------ ---------- --------- --------- -----------------------------------------
float exposure 1.0 1.0 amount of light per unit area
float contrast 1.6773 contrast (toe of the curve); typically is
in [1–2]
float contrast 1.6773 1.1759 contrast (toe of the curve); typically is
in [1–2]
float shoulder 0.9714 highlight compression (shoulder of the
curve); typically is in [0.9–1]
float shoulder 0.9714 0.9746 highlight compression (shoulder of the
curve); typically is in [0.9–1]
float midIn 0.18 mid-level anchor input; default is 18%
gray
float midIn 0.18 0.18 mid-level anchor input; default is 18%
gray
float midOut 0.18 mid-level anchor output; default is 18%
gray
float midOut 0.18 0.18 mid-level anchor output; default is 18%
gray
float hdrMax 11.0785 maximum HDR input that is not clipped
float hdrMax 11.0785 6.3704 maximum HDR input that is not clipped
bool acesColor true apply the ACES color transforms
------ ---------- --------- -----------------------------------------
: Parameters accepted by the tone mapper.
To use the popular "Uncharted 2" filmic tone mapping curve instead, set the
parameters to the values listed in the table below.
Name Value
--------- --------
contrast 1.1759
shoulder 0.9746
midIn 0.18
midOut 0.18
hdrMax 6.3704
acesColor false
--------- --------
: Filmic tone mapping curve parameters. Note that the curve includes an
exposure bias to match 18% middle gray.
bool acesColor true false apply the ACES color transforms
------ ---------- --------- --------- -----------------------------------------
: Parameters accepted by the tone mapper. The column "Filmic" lists
alternative values for the popular "Uncharted 2" tone mapping curve
(note that that curve includes an exposure bias to match 18% middle
gray).
#### Denoiser
@@ -3079,6 +3171,25 @@ using a GPU when available. The device selection be overridden by the
environment variable `OIDN_DEFAULT_DEVICE`, possible values are `cpu`,
`sycl`, `cuda`, `hip`, or a physical device ID
----- ------------- ----------------------------------------------------------
Type Name Description
----- ------------- ----------------------------------------------------------
uint quality `OSPDenoiserQuality` for denoiser quality, default is
`OSP_DENOISER_QUALITY_MEDIUM`: balanced
quality/performance for interactive/real-time rendering;
also allowed are:
`OSP_DENOISER_QUALITY_LOW`: high performance, for
interactive/real-time preview rendering
`OSP_DENOISER_QUALITY_HIGH`: high quality, for final frame
rendering
bool denoiseAlpha whether to denoise the alpha channel as well, default
false
----- ------------- ----------------------------------------------------------
: Parameters accepted by the denoiser.
Rendering
---------
@@ -3091,7 +3202,8 @@ combining a framebuffer, renderer, camera, and world.
What to render and how to render it depends on the renderer's
parameters. If the framebuffer supports accumulation (i.e., it was
created with `OSP_FB_ACCUM`) then successive calls to `ospRenderFrame`
will progressively refine the rendered image.
will progressively refine the rendered image (until `targetFrames` is
reached).
To start an render task, use
@@ -3248,18 +3360,16 @@ or via explicit device creation by the application:
-------- ------------- --------------------------------
void\ * syclContext SYCL context
void\ * syclDevice SYCL device
void\ * zeContext Level Zero context
void\ * zeDevice Level Zero device
-------- ------------- --------------------------------
: Parameters specific to the `gpu` device.
Applications can either set their SYCL context and device or their Level
Zero context and device, to share device memory with OSPRay or to
control which device should be used (e.g., in case multiple GPUs are
present). If neither parameter is set, the `gpu` device will
automatically create a context internally and select a GPU (that
selection can be influenced via environment variable
`ONEAPI_DEVICE_SELECTOR`).
Applications can set their SYCL context and device to share device
memory with OSPRay or to control which device should be used
(e.g., in case multiple GPUs are present). If neither parameter is set,
the `gpu` device will automatically create a context internally
and select a GPU (that selection can be influenced via environment
variable `ONEAPI_DEVICE_SELECTOR`, see [Intel oneAPI DPC++ Compiler
documentation](https://intel.github.io/llvm-docs/EnvironmentVariables.html#oneapi-device-selector)).
Compile times for just in time compilation (JIT compilation) can be
large. To resolve this issue we recommend enabling persistent JIT
@@ -3270,7 +3380,11 @@ JIT cache should get stored).
To reduce GPU memory allocation overhead when rendering scenes with many
objects (geometries, instances, etc.), memory pooling should be enabled
by setting the environment variable `ISPCRT_MEM_POOL=1`.
by setting the environment variable
`SYCL_PI_LEVEL_ZERO_USM_ALLOCATOR="1;0;shared:1M,0,2M"`.
See [Intel oneAPI DPC++ Compiler
documentation](https://intel.github.io/llvm-docs/EnvironmentVariables.html#debugging-variables-for-level-zero-plugin)
for more details.
### Known Issues {-}
@@ -3407,7 +3521,7 @@ devices set the environment variable `OSPRAY_MPI_DISTRIBUTED_GPU`, e.g.,
export OSPRAY_MPI_DISTRIBUTED_GPU=1
```
or
or
```sh
mpiexec -genv OSPRAY_MPI_DISTRIBUTED_GPU 1 \
@@ -3432,7 +3546,7 @@ for GPU rendering, and manually creating and using an instance of the
`mpiDistributed` device, for example:
ospLoadModule("mpi_distributed_cpu");
OSPDevice mpiDevice = ospNewDevice("mpiDistributed");
ospDeviceCommit(mpiDevice);
ospSetCurrentDevice(mpiDevice);
+6 -4
View File
@@ -39,14 +39,16 @@ Packages
Packages for x86_64 are provided, OSPRay can be built for ARM64/NEON
using the superbuild (see [Building and Finding OSPRay](#building-and-finding-ospray)).
For Linux we provide OSPRay precompiled for 64\ bit (including the GPU module) as a TGZ archive.
For Linux we provide OSPRay precompiled for 64\ bit (including the GPU module) as a TGZ archive.
[ospray-<OSPRAY_VERSION>.x86_64.linux.tar.gz](https://github.com/ospray/OSPRay/releases/download/v<OSPRAY_VERSION>/ospray-<OSPRAY_VERSION>.x86_64.linux.tar.gz)
For Mac OS\ X we provide OSPRay as a ZIP archive:
[ospray-<OSPRAY_VERSION>.x86_64.macosx.zip](https://github.com/ospray/OSPRay/releases/download/v<OSPRAY_VERSION>/ospray-<OSPRAY_VERSION>.x86_64.macosx.zip)
For Mac OS\ X we provide OSPRay as a ZIP archives for x86_64 and ARM64
architectures:
[ospray-<OSPRAY_VERSION>.x86_64.macosx.zip](https://github.com/ospray/OSPRay/releases/download/v<OSPRAY_VERSION>/ospray-<OSPRAY_VERSION>.x86_64.macosx.zip)
[ospray-<OSPRAY_VERSION>.arm64.macosx.zip](https://github.com/ospray/OSPRay/releases/download/v<OSPRAY_VERSION>/ospray-<OSPRAY_VERSION>.arm64.macosx.zip)
For Windows we provide OSPRay binaries precompiled for 64\ bit
(including the GPU module) as an MSI installer as well as a ZIP archive.
(including the GPU module) as an MSI installer as well as a ZIP archive.
[ospray-<OSPRAY_VERSION>.x86_64.windows.msi](https://github.com/ospray/OSPRay/releases/download/v<OSPRAY_VERSION>/ospray-<OSPRAY_VERSION>.x86_64.windows.msi)
[ospray-<OSPRAY_VERSION>.x86_64.windows.zip](https://github.com/ospray/OSPRay/releases/download/v<OSPRAY_VERSION>/ospray-<OSPRAY_VERSION>.x86_64.windows.zip)
+2 -2
View File
@@ -4,8 +4,8 @@ OSPRay Overview
Intel® OSPRay is an **o**pen source, **s**calable, and **p**ortable
**ray** tracing engine for high-performance, high-fidelity visualization
on Intel Architecture CPUs, Intel Xe GPUs, and ARM64 CPUs. OSPRay is part
of the [Intel oneAPI Rendering
Toolkit](https://software.intel.com/en-us/rendering-framework) and is
of the [Intel Rendering Toolkit (Render
Kit)](https://software.intel.com/en-us/rendering-framework) and is
released under the permissive [Apache 2.0
license](http://www.apache.org/licenses/LICENSE-2.0).
+4 -14
View File
@@ -25,8 +25,8 @@ before you can build OSPRay you need the following prerequisites:
Please obtain a release of ISPC from the [ISPC downloads
page](https://ispc.github.io/downloads.html).
If ISPC is not found by CMake its location can be hinted with the
variable `ispcrt_DIR`.
- OSPRay builds on top of the [Intel oneAPI Rendering Toolkit common
variable `ISPC_EXECUTABLE`.
- OSPRay builds on top of the [Intel Rendering Toolkit (Render Kit) common
library (rkcommon)](https://www.github.com/ospray/rkcommon). The
library provides abstractions for tasking, aligned memory
allocation, vector math types, among others. For users who also need
@@ -37,7 +37,7 @@ before you can build OSPRay you need the following prerequisites:
be built from source as part of the [superbuild](#cmake-superbuild).
Alternatively you can set CMake variable `RKCOMMON_TASKING_SYSTEM`
to `OpenMP` or `Internal`.
- OSPRay also heavily uses Intel [Embree], installing version 4.3.1
- OSPRay also heavily uses Intel [Embree], installing version 4.3.3
or newer is required. If Embree is not found by CMake its location
can be hinted with the variable `embree_DIR`.
- OSPRay supports volume rendering (enabled by default via
@@ -47,7 +47,7 @@ before you can build OSPRay you need the following prerequisites:
the variable `openvkl_DIR`, or disable `OSPRAY_ENABLE_VOLUMES`.
- OSPRay also provides an optional module implementing the `denoiser`
image operation, which is enabled by `OSPRAY_MODULE_DENOISER`. This
module requires Intel [Open Image Denoise] in version 2.2.0 or
module requires Intel [Open Image Denoise] in version 2.3.0 or
newer. You may need to hint the location of the library with the
CMake variable `OpenImageDenoise_DIR`.
- For the optional MPI modules (enabled by `OSPRAY_MODULE_MPI`), which
@@ -92,13 +92,3 @@ To build OSPRay's GPU module you need
or the latest [Intel oneAPI DPC++/C++
Compiler](https://www.intel.com/content/www/us/en/developer/articles/tool/oneapi-standalone-components.html#dpcpp-cpp)
- a recent [CMake](http://www.cmake.org), version 3.25.3 or higher
- the [oneAPI Level Zero Loader
v1.12.0](https://github.com/oneapi-src/level-zero/releases/tag/v1.12.0)
development packages
- On Linux Ubuntu 22.04 there are prebuilt packages available for
this: `level-zero-devel` and `level-zero`
- Other Linux distributions require building these packages from source
- On Windows, you can use the single package
`level-zero_<version>_win-sdk`; note you will need to set the
environment variable `LEVEL_ZERO_ROOT` to the location of the
SDK
+35 -38
View File
@@ -20,12 +20,11 @@ endif()
# Setup module include directories and source files
# -------------------------------------------------------
set(OSPRAY_CPP_SOURCES
set(OSPRAY_HOST_SOURCES
${OSPRAY_RESOURCE}
ModuleInit.cpp
ispc_tasksys.cpp
ispc_tasksys.h
ISPCDevice.h
ISPCDevice.cpp
@@ -81,9 +80,6 @@ set(OSPRAY_CPP_SOURCES
lights/registration.cpp
math/spectrum.h
math/halton.cpp
math/sobol.cpp
math/MathConstants.cpp
math/Distribution2D.cpp
render/LoadBalancer.cpp
@@ -121,7 +117,7 @@ set(OSPRAY_CPP_SOURCES
texture/registration.cpp
)
set(OSPRAY_ISPC_SOURCES
set(OSPRAY_KERNEL_SOURCES
ISPCDevice.ispc
common/World.ispc
@@ -205,10 +201,19 @@ set(OSPRAY_ISPC_SOURCES
texture/TextureDispatch.ispc
texture/Texture2D.ispc
texture/TextureParam.ispc
)
set(OSPRAY_BCKND_ISPC_SOURCES
common/DeviceRTImpl_ispc.cpp
)
set(OSPRAY_BCKND_SYCL_SOURCES
common/DeviceRTImpl_sycl.cpp
)
if (OSPRAY_ENABLE_VOLUMES)
set(OSPRAY_VOLUMES_CPP_SOURCES
list(APPEND OSPRAY_HOST_SOURCES
geometry/Isosurfaces.cpp
texture/TextureVolume.cpp
@@ -221,7 +226,7 @@ if (OSPRAY_ENABLE_VOLUMES)
volume/transferFunction/registration.cpp
)
set(OSPRAY_VOLUMES_ISPC_SOURCES
list(APPEND OSPRAY_KERNEL_SOURCES
geometry/Isosurfaces.ispc
render/ao/volumes.ispc
@@ -337,16 +342,19 @@ if (OSPRAY_MODULE_CPU)
)
endif()
add_library(ospray_module_cpu SHARED)
add_library(ospray_module_cpu SHARED
${OSPRAY_HOST_SOURCES}
${OSPRAY_ISPC_DEF}
${OSPRAY_BCKND_ISPC_SOURCES}
math/halton.c math/sobol.c # constants exported for ISPC only
geometry/Subdivision.cpp
)
ispc_target_add_sources(ospray_module_cpu
${OSPRAY_CPP_SOURCES}
${OSPRAY_VOLUMES_CPP_SOURCES}
${OSPRAY_ISPC_SOURCES}
${OSPRAY_VOLUMES_ISPC_SOURCES}
${OSPRAY_ISPC_DEF}
geometry/Subdivision.cpp
geometry/Subdivision.ispc)
${OSPRAY_KERNEL_SOURCES}
geometry/Subdivision.ispc
texture/MipMapGeneration.ispc
)
ospray_install_library(ospray_module_cpu lib)
@@ -354,7 +362,6 @@ if (OSPRAY_MODULE_CPU)
PUBLIC
ospray
rkcommon::rkcommon
$<BUILD_INTERFACE:ispcrt::ispcrt>
$<BUILD_INTERFACE:embree>
)
@@ -367,7 +374,6 @@ if (OSPRAY_MODULE_CPU)
$<BUILD_INTERFACE:${CMAKE_CURRENT_BINARY_DIR}>
$<BUILD_INTERFACE:${PROJECT_BINARY_DIR}>
# NOTE(jda) - the following includes are missing despite PUBLIC linking
$<BUILD_INTERFACE:${ISPCRT_INCLUDE_DIR}>
$<BUILD_INTERFACE:${EMBREE_INCLUDE_DIRS}>
#######################################################################
$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}/ospray/SDK>
@@ -379,6 +385,7 @@ if (OSPRAY_MODULE_CPU)
TILE_SIZE=${OSPRAY_TILE_SIZE}
MAX_TILE_SIZE=${OSPRAY_MAX_STACK_TILE_SIZE}
SYCL_EXTERNAL=
OSPRAY_GLOBAL=
)
if (OSPRAY_ENABLE_VOLUMES)
@@ -388,11 +395,6 @@ if (OSPRAY_MODULE_CPU)
$<BUILD_INTERFACE:openvkl::openvkl_module_cpu_device>
)
target_include_directories(ospray_module_cpu
PUBLIC
$<BUILD_INTERFACE:${OPENVKL_INCLUDE_DIRS}>
)
target_compile_definitions(ospray_module_cpu
PUBLIC
OSPRAY_ENABLE_VOLUMES
@@ -408,17 +410,13 @@ if (OSPRAY_MODULE_GPU)
cmake_minimum_required(VERSION 3.20.5)
endif()
include(${ISPCRT_DIR}/interop.cmake)
# Have CMake's build infrastructure treat the ISPC files as C++ for SYCL
set_source_files_properties(${OSPRAY_ISPC_SOURCES} ${OSPRAY_VOLUMES_ISPC_SOURCES}
set_source_files_properties(${OSPRAY_KERNEL_SOURCES} ${OSPRAY_VOLUMES_KERNEL_SOURCES}
PROPERTIES
LANGUAGE CXX)
add_library(ospray_module_gpu_kernels OBJECT
${OSPRAY_ISPC_SOURCES}
${OSPRAY_VOLUMES_ISPC_SOURCES}
${OSPRAY_KERNEL_SOURCES}
)
ospray_add_sycl_target(ospray_module_gpu_kernels)
@@ -427,7 +425,6 @@ if (OSPRAY_MODULE_GPU)
PUBLIC
ospray
rkcommon::rkcommon
$<BUILD_INTERFACE:ispcrt::ispcrt>
$<BUILD_INTERFACE:embree>
)
@@ -440,7 +437,6 @@ if (OSPRAY_MODULE_GPU)
$<BUILD_INTERFACE:${CMAKE_CURRENT_BINARY_DIR}>
$<BUILD_INTERFACE:${PROJECT_BINARY_DIR}>
# NOTE(jda) - the following includes are missing despite PUBLIC linking
$<BUILD_INTERFACE:${ISPCRT_INCLUDE_DIR}>
$<BUILD_INTERFACE:${EMBREE_INCLUDE_DIRS}>
#######################################################################
$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}/ospray/SDK>
@@ -467,8 +463,10 @@ if (OSPRAY_MODULE_GPU)
target_compile_definitions(ospray_module_gpu_kernels
PUBLIC
OSPRAY_TARGET_SYCL
__SYCL_USE_NON_VARIADIC_SPIRV_OCL_PRINTF__ # WA to allow printf of float, see https://github.com/intel/llvm/issues/12880
OSPRAY_BEGIN_ISPC_NAMESPACE=namespace\ ispc{
OSPRAY_END_ISPC_NAMESPACE=}
OSPRAY_GLOBAL=static
_ALLOW_KEYWORD_MACROS # avoid error when redefining reserved keywords like "export"
uniform=
varying=
@@ -494,11 +492,6 @@ if (OSPRAY_MODULE_GPU)
$<BUILD_INTERFACE:openvkl::openvkl_module_gpu_device>
)
target_include_directories(ospray_module_gpu_kernels
PUBLIC
$<BUILD_INTERFACE:${OPENVKL_INCLUDE_DIRS}>
)
target_compile_definitions(ospray_module_gpu_kernels
PUBLIC
OSPRAY_ENABLE_VOLUMES
@@ -509,8 +502,11 @@ if (OSPRAY_MODULE_GPU)
install(TARGETS ospray_module_gpu_kernels EXPORT ospray_Exports)
add_library(ospray_module_gpu SHARED
${OSPRAY_CPP_SOURCES}
${OSPRAY_VOLUMES_CPP_SOURCES}
${OSPRAY_HOST_SOURCES}
${OSPRAY_BCKND_SYCL_SOURCES}
)
ispc_target_add_sources(ospray_module_gpu
texture/MipMapGeneration.ispc
)
target_link_libraries(ospray_module_gpu
@@ -540,6 +536,7 @@ foreach(dir . ${SUBDIRS})
COMPONENT devel
FILES_MATCHING
PATTERN *_ispc.h
PATTERN CMakeFiles EXCLUDE
)
endforeach()
+76 -139
View File
@@ -1,14 +1,11 @@
// Copyright 2009 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#ifdef OSPRAY_TARGET_SYCL
#include <sycl/ext/oneapi/backend/level_zero.hpp>
#endif
// ospray
#include "ISPCDevice.h"
#include "camera/Camera.h"
#include "common/Data.h"
#include "common/DeviceRTImpl.h"
#include "common/Group.h"
#include "common/Instance.h"
#include "common/Library.h"
@@ -16,16 +13,12 @@
#include "fb/ImageOp.h"
#include "fb/LocalFB.h"
#include "geometry/GeometricModel.h"
#include "ispc_tasksys.h"
#include "lights/Light.h"
#include "render/LoadBalancer.h"
#include "render/Material.h"
#ifdef OSPRAY_TARGET_SYCL
#include "render/RenderTaskSycl.h"
#else
#include "render/RenderTask.h"
#endif
#include "render/Renderer.h"
#include "render/RenderingFuture.h"
#include "texture/MipMapCache.h"
#include "texture/Texture.h"
#include "texture/Texture2D.h"
#ifdef OSPRAY_ENABLE_VOLUMES
@@ -37,8 +30,6 @@
#include <algorithm>
#include <functional>
#include <map>
#include "rkcommon/tasking/tasking_system_init.h"
#include "rkcommon/utility/CodeTimer.h"
#ifndef OSPRAY_TARGET_SYCL
#include "ISPCDevice_ispc.h"
@@ -171,6 +162,11 @@ ISPCDevice::ISPCDevice()
#endif
}
ISPCDevice::ISPCDevice(std::unique_ptr<devicert::Device> device) : ISPCDevice()
{
drtDevice = std::move(device);
}
ISPCDevice::~ISPCDevice()
{
try {
@@ -190,10 +186,12 @@ ISPCDevice::~ISPCDevice()
static void embreeErrorFunc(void *, const RTCError code, const char *str)
{
postStatusMsg() << "#osp: Embree internal error " << code << " : " << str;
const std::string msg = std::string("Embree internal error ")
+ rtcGetErrorString(code) + " : " + str;
postStatusMsg() << "#osp: Embree internal error " << msg;
OSPError e =
(code > RTC_ERROR_UNSUPPORTED_CPU) ? OSP_UNKNOWN_ERROR : (OSPError)code;
handleError(e, "Embree internal error '" + std::string(str) + "'");
handleError(e, msg);
}
#ifdef OSPRAY_ENABLE_VOLUMES
@@ -210,121 +208,64 @@ void ISPCDevice::commit()
{
Device::commit();
if (!userContext) {
#ifdef OSPRAY_TARGET_SYCL
sycl::context *appSyclCtx =
static_cast<sycl::context *>(getParam<void *>("syclContext", nullptr));
sycl::device *appSyclDevice =
static_cast<sycl::device *>(getParam<void *>("syclDevice", nullptr));
if ((appSyclCtx && !appSyclDevice) || (!appSyclCtx && appSyclDevice)) {
handleError(OSP_INVALID_OPERATION,
"OSPRay ISPCDevice invalid configuration: if providing a syclContext and syclDevice both must be provided");
return;
}
ze_context_handle_t appZeCtx = static_cast<ze_context_handle_t>(
getParam<void *>("zeContext", nullptr));
ze_device_handle_t appZeDevice =
static_cast<ze_device_handle_t>(getParam<void *>("zeDevice", nullptr));
if ((appZeCtx && !appZeDevice) || (!appZeCtx && appZeDevice)) {
handleError(OSP_INVALID_OPERATION,
"OSPRay ISPCDevice invalid configuration: if providing a zeContext and zeDevice both must be provided");
return;
}
if (appSyclCtx && appZeCtx) {
handleError(OSP_INVALID_OPERATION,
"OSPRay ISPCDevice invalid configuration: For SYCL or Level Zero context interopability only a SYCL or Level Zero context & device can be provided, not both.");
return;
}
// If we got a SYCL context just get the native handles and set the "app" L0
// context/device to them, since we can take the same code path from there
if (appSyclCtx) {
appZeCtx =
sycl::get_native<sycl::backend::ext_oneapi_level_zero>(*appSyclCtx);
appZeDevice = sycl::get_native<sycl::backend::ext_oneapi_level_zero>(
*appSyclDevice);
}
const bool newContext = appZeCtx || !ispcrtContext;
if (appZeCtx) {
userContext = true;
ispcrtContext = ispcrt::Context(
ISPCRT_DEVICE_TYPE_GPU, (ISPCRTGenericHandle)appZeCtx);
ispcrtDevice =
ispcrt::Device(ispcrtContext, (ISPCRTGenericHandle)appZeDevice);
} else if (!ispcrtContext) {
// internally, from Multidevice GPU
ispcrt::Context *ispcrtContextPtr = static_cast<ispcrt::Context *>(
getParam<void *>("ispcrtContext", nullptr));
ispcrt::Device *ispcrtDevicePtr = static_cast<ispcrt::Device *>(
getParam<void *>("ispcrtDevice", nullptr));
if (ispcrtContextPtr != nullptr && ispcrtDevicePtr != nullptr) {
ispcrtContext = *ispcrtContextPtr;
ispcrtDevice = *ispcrtDevicePtr;
} else {
ispcrtContext = ispcrt::Context(ISPCRT_DEVICE_TYPE_GPU);
ispcrtDevice = ispcrt::Device(ispcrtContext);
}
}
if (newContext) {
syclPlatform = appSyclCtx ? appSyclCtx->get_platform()
: sycl::ext::oneapi::level_zero::make_platform(
reinterpret_cast<pi_native_handle>(
ispcrtDevice.nativePlatformHandle()));
syclDevice = sycl::ext::oneapi::level_zero::make_device(syclPlatform,
reinterpret_cast<pi_native_handle>(
ispcrtDevice.nativeDeviceHandle()));
syclContext = sycl::ext::oneapi::level_zero::make_context(
std::vector<sycl::device>{syclDevice},
reinterpret_cast<pi_native_handle>(
ispcrtDevice.nativeContextHandle()),
true);
syclQueue = sycl::queue(syclContext,
syclDevice,
{sycl::property::queue::enable_profiling(),
sycl::property::queue::in_order()});
if (embreeDevice) {
rtcReleaseDevice(embreeDevice);
embreeDevice = nullptr;
}
#ifdef OSPRAY_ENABLE_VOLUMES
if (vklDevice) {
vklReleaseDevice(vklDevice);
vklDevice = nullptr;
}
#endif
}
#else
userContext = true; // on CPU there is no other choice
ispcrtContext = ispcrt::Context(ISPCRT_DEVICE_TYPE_CPU);
ispcrtDevice = ispcrt::Device(ispcrtContext);
#endif
ispcrtQueue = ispcrt::TaskQueue(ispcrtDevice);
// Check if SYCL context and device have been provided externally
void *appSyclCtxNew = getParam<void *>("syclContext", nullptr);
void *appSyclDeviceNew = getParam<void *>("syclDevice", nullptr);
if ((appSyclCtxNew && !appSyclDeviceNew)
|| (!appSyclCtxNew && appSyclDeviceNew)) {
handleError(OSP_INVALID_OPERATION,
"OSPRay ISPCDevice invalid configuration: if providing a syclContext and syclDevice both must be provided");
return;
}
setIspcrtTaskingCallbacks();
// Release all devices if user-provided parameters has changed
if ((appSyclCtxNew != appSyclCtx) || (appSyclDeviceNew != appSyclDevice)) {
// Release DRT device
drtDevice.reset();
// Release Embree device
if (embreeDevice) {
rtcReleaseDevice(embreeDevice);
embreeDevice = nullptr;
}
#ifdef OSPRAY_ENABLE_VOLUMES
// Release VKL device
if (vklDevice) {
vklReleaseDevice(vklDevice);
vklDevice = nullptr;
}
#endif
}
// Save user-provided parameters
appSyclCtx = appSyclCtxNew;
appSyclDevice = appSyclDeviceNew;
// We will create run-time device once only
if (!drtDevice) {
// Create DRT device
if (appSyclCtx && appSyclDevice)
drtDevice =
devicert::make_device_unique(appSyclDevice, appSyclCtx, debugMode);
else
drtDevice = devicert::make_device_unique(debugMode);
}
if (!embreeDevice) {
#ifdef OSPRAY_TARGET_SYCL
embreeDevice =
rtcNewSYCLDevice(syclContext, generateEmbreeDeviceCfg(*this).c_str());
rtcSetDeviceSYCLDevice(embreeDevice, syclDevice);
embreeDevice = rtcNewSYCLDevice(
*static_cast<sycl::context *>(drtDevice->getSyclContextPtr()),
generateEmbreeDeviceCfg(*this).c_str());
rtcSetDeviceSYCLDevice(embreeDevice,
*static_cast<sycl::device *>(drtDevice->getSyclDevicePtr()));
#else
embreeDevice = rtcNewDevice(generateEmbreeDeviceCfg(*this).c_str());
#endif
rtcSetDeviceErrorFunction(embreeDevice, embreeErrorFunc, nullptr);
RTCError erc = rtcGetDeviceError(embreeDevice);
if (erc != RTC_ERROR_NONE) {
// why did the error function not get called !?
postStatusMsg() << "#osp:init: embree internal error number " << erc;
postStatusMsg() << "#osp:init: embree internal error: "
<< rtcGetDeviceLastErrorMessage(embreeDevice);
throw std::runtime_error("failed to initialize Embree");
}
}
@@ -336,7 +277,7 @@ void ISPCDevice::commit()
#ifdef OSPRAY_TARGET_SYCL
vklDevice = vklNewDevice("gpu");
vklDeviceSetVoidPtr(
vklDevice, "syclContext", static_cast<void *>(&syclContext));
vklDevice, "syclContext", drtDevice->getSyclContextPtr());
#else
int cpu_width = ispc::ISPCDevice_programCount();
switch (cpu_width) {
@@ -370,6 +311,10 @@ void ISPCDevice::commit()
}
#endif
// Create MIP map cache if needed
if (!disableMipMapGeneration)
mipMapCache = rkcommon::make_unique<MipMapCache>();
#ifndef OSPRAY_TARGET_SYCL
// Output device info string
const char *isaNames[] = {
@@ -377,10 +322,6 @@ void ISPCDevice::commit()
postStatusMsg(OSP_LOG_INFO)
<< "Using ISPC device with " << isaNames[ispc::ISPCDevice_isa()]
<< " instruction set";
#else
postStatusMsg(OSP_LOG_INFO)
<< "Using SYCL GPU device on "
<< syclDevice.get_info<sycl::info::device::name>() << " device";
#endif
}
@@ -586,7 +527,7 @@ OSPFrameBuffer ISPCDevice::frameBufferCreate(
OSPImageOperation ISPCDevice::newImageOp(const char *type)
{
ospray::ImageOp *ret = ImageOp::createImageOp(type, *this);
ospray::ImageOp *ret = ImageOp::createImageOp(type, getDRTDevice());
return (OSPImageOperation)ret;
}
@@ -634,32 +575,28 @@ OSPFuture ISPCDevice::renderFrame(OSPFrameBuffer _fb,
Camera *camera = (Camera *)_camera;
World *world = (World *)_world;
#ifndef OSPRAY_TARGET_SYCL
fb->setCompletedEvent(OSP_NONE_FINISHED);
// Increase reference counters so the passed objects will not be released
// during frame rendering
fb->refInc();
renderer->refInc();
camera->refInc();
world->refInc();
return (OSPFuture) new RenderTask(fb, [=]() {
utility::CodeTimer timer;
timer.start();
loadBalancer->renderFrame(fb, renderer, camera, world);
timer.stop();
// Schedule frame rendering
std::pair<devicert::AsyncEvent, devicert::AsyncEvent> events =
loadBalancer->renderFrame(fb, renderer, camera, world);
// Schedule reference counters decrease to be done after the rendering
devicert::AsyncEvent event = getDRTDevice().launchHostTask([=]() {
fb->refDec();
renderer->refDec();
camera->refDec();
world->refDec();
return timer.seconds();
});
#else
std::pair<AsyncEvent, AsyncEvent> events =
loadBalancer->renderFrame(fb, renderer, camera, world, false);
return (OSPFuture) new RenderTask(events.first, events.second);
#endif
// Return rendering future object
return (OSPFuture) new RenderingFuture(
fb, events.first, events.second, event);
}
int ISPCDevice::isReady(OSPFuture _task, OSPSyncEvent event)
+19 -47
View File
@@ -5,8 +5,8 @@
// ospray
#include "Device.h"
// ispcrt
#include "ispcrt.hpp"
// device run-time
#include "DeviceRT.h"
// embree
#include "common/Embree.h"
#ifdef OSPRAY_ENABLE_VOLUMES
@@ -28,20 +28,14 @@ int ISPCDevice_isa();
namespace ospray {
struct LocalTiledLoadBalancer;
#ifdef OSPRAY_TARGET_SYCL
using AsyncEvent = sycl::event;
#else
struct AsyncEvent
{
};
#endif
struct MipMapCache;
namespace api {
struct OSPRAY_SDK_INTERFACE ISPCDevice : public Device
{
ISPCDevice();
ISPCDevice(std::unique_ptr<devicert::Device> device);
virtual ~ISPCDevice() override;
/////////////////////////////////////////////////////////////////////////
@@ -161,38 +155,14 @@ struct OSPRAY_SDK_INTERFACE ISPCDevice : public Device
}
#endif
ispcrt::Device &getIspcrtDevice()
inline devicert::Device &getDRTDevice()
{
return ispcrtDevice;
}
ispcrt::Context &getIspcrtContext()
{
return ispcrtContext;
}
ispcrt::TaskQueue &getIspcrtQueue()
{
return ispcrtQueue;
}
void *getPostProcessingCommandQueuePtr() override
{
#ifdef OSPRAY_TARGET_SYCL
return &syclQueue;
#else
return nullptr;
#endif
return *drtDevice;
}
#ifdef OSPRAY_TARGET_SYCL
sycl::queue &getSyclQueue()
{
return syclQueue;
}
/* Compute the rounded dispatch global size for the given work group size.
* SYCL requires that globalSize % workgroupSize == 0, ths function will
* SYCL requires that globalSize % workgroupSize == 0, this function will
* round up globalSize and return nd_range(roundedSize, workgroupSize).
* The kernel being launched must discard tasks that are out of bounds
* bounds due to this rounding
@@ -201,24 +171,26 @@ struct OSPRAY_SDK_INTERFACE ISPCDevice : public Device
const size_t globalSize, const size_t workgroupSize) const;
#endif
inline MipMapCache &getMipMapCache()
{
return *mipMapCache;
}
private:
ispcrt::Context ispcrtContext;
ispcrt::Device ispcrtDevice;
ispcrt::TaskQueue ispcrtQueue;
std::unique_ptr<devicert::Device> drtDevice;
RTCDevice embreeDevice = nullptr;
#ifdef OSPRAY_ENABLE_VOLUMES
VKLDevice vklDevice = nullptr;
#endif
#ifdef OSPRAY_TARGET_SYCL
sycl::platform syclPlatform;
sycl::device syclDevice;
sycl::context syclContext;
sycl::queue syclQueue;
#endif
// External SYCL context and device
void *appSyclCtx{nullptr};
void *appSyclDevice{nullptr};
bool userContext{false}; // app can set context only once
// Device-wide MIP map cache is needed because the same texture data objects
// (and thus generated MIP maps) can be shared among many textures
std::unique_ptr<MipMapCache> mipMapCache;
};
} // namespace api
+5 -2
View File
@@ -7,8 +7,7 @@
namespace ospray {
Camera::Camera(api::ISPCDevice &device, const FeatureFlagsOther featureFlags)
: AddStructShared(device.getIspcrtContext(), device),
featureFlags(featureFlags)
: AddStructShared(device.getDRTDevice(), device), featureFlags(featureFlags)
{
managedObjectType = OSP_CAMERA;
}
@@ -105,6 +104,10 @@ void Camera::commit()
getSh()->rollingShutterHorizontal = (shutterType == OSP_SHUTTER_ROLLING_RIGHT
|| shutterType == OSP_SHUTTER_ROLLING_LEFT);
getSh()->rollingShutterDuration = rollingShutterDuration;
getSh()->needTimeSample = shutterType == OSP_SHUTTER_GLOBAL
? shutter.size()
: rollingShutterDuration;
getSh()->needLensSample = false;
if (motionTransform.motionBlur)
featureFlags |= FFO_CAMERA_MOTION_BLUR;
+2
View File
@@ -6,6 +6,7 @@
#pragma once
#include "common/Ray.ih"
#include "common/RayCone.ih"
#include "rkcommon/math/box.ih"
// c++ shared
#include "CameraShared.h"
@@ -21,6 +22,7 @@ struct CameraSample
vec2f screen; // normalized screen sample, in [0..1]
vec2f lens;
float time;
vec2f pixel_center;
};
inline vec2f Camera_subRegion(const Camera *uniform self, const vec2f &screen)
+1
View File
@@ -9,6 +9,7 @@ OSPRAY_BEGIN_ISPC_NAMESPACE
SYCL_EXTERNAL void Camera_dispatch_initRay(const Camera *uniform self,
varying Ray &ray,
varying RayCone &,
const varying CameraSample &sample,
const uniform FeatureFlagsHandler &ffh);
+6 -5
View File
@@ -12,6 +12,7 @@ OSPRAY_BEGIN_ISPC_NAMESPACE
SYCL_EXTERNAL void Camera_dispatch_initRay(const Camera *uniform self,
varying Ray &ray,
varying RayCone &rayCone,
const varying CameraSample &sample,
const uniform FeatureFlagsHandler &ffh)
{
@@ -19,18 +20,18 @@ SYCL_EXTERNAL void Camera_dispatch_initRay(const Camera *uniform self,
if ((self->type == CAMERA_TYPE_PERSPECTIVE)
&& (ffo & FFO_CAMERA_PERSPECTIVE)) {
if (self->motionBlur && (ffo & FFO_CAMERA_MOTION_BLUR))
PerspectiveCamera_initRayMB(self, ray, sample, ffh);
PerspectiveCamera_initRayMB(self, ray, rayCone, sample, ffh);
else
PerspectiveCamera_initRay(self, ray, sample, ffh);
PerspectiveCamera_initRay(self, ray, rayCone, sample, ffh);
} else if ((self->type == CAMERA_TYPE_ORTHOGRAPHIC)
&& (ffo & FFO_CAMERA_ORTHOGRAPHIC)) {
OrthographicCamera_initRay(self, ray, sample, ffh);
OrthographicCamera_initRay(self, ray, rayCone, sample, ffh);
} else if ((self->type == CAMERA_TYPE_PANORAMIC)
&& (ffo & FFO_CAMERA_PANORAMIC)) {
PanoramicCamera_initRay(self, ray, sample, ffh);
PanoramicCamera_initRay(self, ray, rayCone, sample, ffh);
} else {
#ifndef OSPRAY_TARGET_SYCL
self->initRay(self, ray, sample);
self->initRay(self, ray, rayCone, sample);
#endif
}
}
+9 -3
View File
@@ -13,11 +13,14 @@ typedef void *Camera_initRay;
struct Camera;
struct CameraSample;
struct Ray;
struct RayCone;
// Fct pointer type for 'virtual' method that sets a pixel,
// generated ray.dir must be normalized to ensure ray.t is world-space distance
// generated rayCone is in normalized camera coordinates for y (height)
typedef void (*Camera_initRay)(const Camera *uniform,
varying Ray &ray,
varying RayCone &rayCone,
const varying CameraSample &sample);
#endif
@@ -34,12 +37,13 @@ struct Camera
CameraType type;
Camera_initRay initRay; // the 'virtual' initRay() method
bool motionBlur; // for the camera itself only, not in general
float nearClip;
box2f subImage; // viewable tile / subrange to compute, in [0..1]^2 x [0..1]^2
range1f shutter; // camera shutter open start and end time, in [0..1]
bool globalShutter;
bool motionBlur; // for the camera itself only, not in general
bool needLensSample;
bool needTimeSample;
bool rollingShutterHorizontal;
float rollingShutterDuration;
RTCScene scene; // only to call rtcGetGeometryTransformFromScene
@@ -48,11 +52,13 @@ struct Camera
Camera()
: type(CAMERA_TYPE_UNKNOWN),
initRay(nullptr),
motionBlur(false),
nearClip(1e-6f),
subImage(0.f),
shutter(0.f),
globalShutter(false),
motionBlur(false),
needLensSample(false),
needTimeSample(false),
rollingShutterHorizontal(false),
rollingShutterDuration(0.f),
scene(nullptr)
+2 -2
View File
@@ -10,8 +10,7 @@
namespace ospray {
OrthographicCamera::OrthographicCamera(api::ISPCDevice &device)
: AddStructShared(
device.getIspcrtContext(), device, FFO_CAMERA_ORTHOGRAPHIC)
: AddStructShared(device.getDRTDevice(), device, FFO_CAMERA_ORTHOGRAPHIC)
{
#ifndef OSPRAY_TARGET_SYCL
getSh()->super.initRay = reinterpret_cast<ispc::Camera_initRay>(
@@ -47,6 +46,7 @@ void OrthographicCamera::commit()
getSh()->org =
pos - 0.5f * getSh()->du_size - 0.5f * getSh()->dv_up; // shift
}
getSh()->height = height;
}
box3f OrthographicCamera::projectBox(const box3f &b) const
+1
View File
@@ -7,6 +7,7 @@ OSPRAY_BEGIN_ISPC_NAMESPACE
SYCL_EXTERNAL void OrthographicCamera_initRay(const Camera *uniform,
varying Ray &,
varying RayCone &,
const varying CameraSample &,
const uniform FeatureFlagsHandler &);
+4 -1
View File
@@ -4,7 +4,6 @@
#include "Camera.ih"
#include "common/Embree.h"
#include "common/FeatureFlags.ih"
#include "common/FeatureFlagsEnum.h"
// c++ shared
#include "OrthographicCameraShared.h"
@@ -14,6 +13,7 @@ OSPRAY_BEGIN_ISPC_NAMESPACE
SYCL_EXTERNAL void OrthographicCamera_initRay(const Camera *uniform _self,
varying Ray &ray,
varying RayCone &rayCone,
const varying CameraSample &sample,
const uniform FeatureFlagsHandler &ffh)
{
@@ -48,6 +48,9 @@ SYCL_EXTERNAL void OrthographicCamera_initRay(const Camera *uniform _self,
}
setRay(ray, org, dir, self->super.nearClip, inf, time);
const uniform vec2f subImageSize = box_size(self->super.subImage);
rayCone.width = self->height * abs(subImageSize.y);
rayCone.dwdt = 0.f;
}
// Exports (called from C++) //////////////////////////////////////////////////
@@ -17,13 +17,13 @@ struct OrthographicCamera
// below are essentially unions: 1. if no motionBlur; 2. if motionBlur
vec3f org; // lower left position of the camera image plane;
// origin of camera
vec3f du_size; // delta of ray origin between two pixels in x;
// sensor size (in x and y)
vec3f dv_up; // delta of ray origin between two pixels in y;
// up direction of camera
vec3f du_size; // sensor size (in x and y)
vec3f dv_up; // up vector with magnitude equal to the imagePlane size in y
float height; // size of the imagePlane in y
#ifdef __cplusplus
OrthographicCamera() : dir(0.f), org(0.f), du_size(0.f), dv_up(0.f)
OrthographicCamera()
: dir(0.f), org(0.f), du_size(0.f), dv_up(0.f), height(1.f)
{
super.type = CAMERA_TYPE_ORTHOGRAPHIC;
}
+1 -1
View File
@@ -14,7 +14,7 @@ void *PanoramicCamera_initRay_addr();
namespace ospray {
PanoramicCamera::PanoramicCamera(api::ISPCDevice &device)
: AddStructShared(device.getIspcrtContext(), device, FFO_CAMERA_PANORAMIC)
: AddStructShared(device.getDRTDevice(), device, FFO_CAMERA_PANORAMIC)
{
#ifndef OSPRAY_TARGET_SYCL
getSh()->super.initRay = reinterpret_cast<ispc::Camera_initRay>(
+1
View File
@@ -7,6 +7,7 @@ OSPRAY_BEGIN_ISPC_NAMESPACE
SYCL_EXTERNAL void PanoramicCamera_initRay(const Camera *uniform,
varying Ray &,
varying RayCone &,
const varying CameraSample &,
const uniform FeatureFlagsHandler &);
+13 -2
View File
@@ -4,7 +4,6 @@
#include "Camera.ih"
#include "common/Embree.h"
#include "common/FeatureFlags.ih"
#include "common/FeatureFlagsEnum.h"
#include "math/sampling.ih"
#include "ospray/OSPEnums.h"
// c++ shared
@@ -16,12 +15,16 @@ OSPRAY_BEGIN_ISPC_NAMESPACE
SYCL_EXTERNAL void PanoramicCamera_initRay(const Camera *uniform _self,
varying Ray &ray,
varying RayCone &rayCone,
const varying CameraSample &sample,
const uniform FeatureFlagsHandler &ffh)
{
const PanoramicCamera *uniform self = (const PanoramicCamera *uniform)_self;
vec2f screen = sample.screen;
float pixel_center = self->stereoMode == OSP_STEREO_SIDE_BY_SIDE
? sample.pixel_center.x
: sample.pixel_center.y;
varying float *uniform split =
self->stereoMode == OSP_STEREO_SIDE_BY_SIDE ? &screen.x : &screen.y;
@@ -36,7 +39,7 @@ SYCL_EXTERNAL void PanoramicCamera_initRay(const Camera *uniform _self,
case OSP_STEREO_SIDE_BY_SIDE:
case OSP_STEREO_TOP_BOTTOM:
*split *= 2.f;
if (*split < 1.f) {
if (pixel_center < 0.5f) {
offset = -self->ipd_offset;
} else {
offset = self->ipd_offset;
@@ -80,6 +83,14 @@ SYCL_EXTERNAL void PanoramicCamera_initRay(const Camera *uniform _self,
}
setRay(ray, org, dir, self->super.nearClip, inf, time);
rayCone.width = 0.f;
rayCone.dwdt = pi * sinTheta;
const uniform vec2f subImageSize = box_size(self->super.subImage);
rayCone.dwdt *= abs(subImageSize.y);
if (self->stereoMode == OSP_STEREO_TOP_BOTTOM)
rayCone.dwdt *= 2.f;
}
// Exports (called from C++) //////////////////////////////////////////////////
+2 -1
View File
@@ -10,7 +10,7 @@
namespace ospray {
PerspectiveCamera::PerspectiveCamera(api::ISPCDevice &device)
: AddStructShared(device.getIspcrtContext(), device, FFO_CAMERA_PERSPECTIVE)
: AddStructShared(device.getDRTDevice(), device, FFO_CAMERA_PERSPECTIVE)
{
#ifndef OSPRAY_TARGET_SYCL
getSh()->super.initRay = reinterpret_cast<ispc::Camera_initRay>(
@@ -56,6 +56,7 @@ void PerspectiveCamera::commit()
getSh()->scaledAperture = apertureRadius
? apertureRadius / (imgPlaneSize.x * focusDistance)
: 0.0f;
getSh()->super.needLensSample = getSh()->scaledAperture;
getSh()->aspect = aspect;
getSh()->stereoMode = stereoMode;
getSh()->dir_00 = normalize(dir);
+2
View File
@@ -7,11 +7,13 @@ OSPRAY_BEGIN_ISPC_NAMESPACE
SYCL_EXTERNAL void PerspectiveCamera_initRay(const Camera *uniform,
varying Ray &,
varying RayCone &,
const varying CameraSample &,
const uniform FeatureFlagsHandler &);
SYCL_EXTERNAL void PerspectiveCamera_initRayMB(const Camera *uniform,
varying Ray &,
varying RayCone &,
const varying CameraSample &,
const uniform FeatureFlagsHandler &);
+20 -3
View File
@@ -4,7 +4,6 @@
#include "Camera.ih"
#include "common/Embree.h"
#include "common/FeatureFlags.ih"
#include "common/FeatureFlagsEnum.h"
#include "math/sampling.ih"
#include "ospray/OSPEnums.h"
// c++ shared
@@ -16,6 +15,7 @@ OSPRAY_BEGIN_ISPC_NAMESPACE
SYCL_EXTERNAL void PerspectiveCamera_initRay(const Camera *uniform _self,
varying Ray &ray,
varying RayCone &rayCone,
const varying CameraSample &sample,
const uniform FeatureFlagsHandler &)
{
@@ -27,9 +27,11 @@ SYCL_EXTERNAL void PerspectiveCamera_initRay(const Camera *uniform _self,
const uniform bool sbs = self->stereoMode == OSP_STEREO_SIDE_BY_SIDE;
varying float *uniform split = sbs ? &screen.x : &screen.y;
float pixel_center = sbs ? sample.pixel_center.x : sample.pixel_center.y;
if (sbs || self->stereoMode == OSP_STEREO_TOP_BOTTOM) {
*split *= 2.f;
if (*split < 1.f) {
if (pixel_center < 0.5f) {
org = org - self->ipd_offset;
} else {
org = org + self->ipd_offset;
@@ -40,7 +42,7 @@ SYCL_EXTERNAL void PerspectiveCamera_initRay(const Camera *uniform _self,
screen = Camera_subRegion(_self, screen);
vec3f dir = self->dir_00 + screen.x * self->du_size + screen.y * self->dv_up;
const float coneShortening = rsqrt(dot(dir, dir));
if (self->scaledAperture > 0.f) {
const vec3f llp = uniformSampleDisk(self->scaledAperture, sample.lens);
// transform local lens point to focal plane (dir_XX are prescaled)
@@ -52,10 +54,18 @@ SYCL_EXTERNAL void PerspectiveCamera_initRay(const Camera *uniform _self,
const float time = Camera_shutterTime(_self, screen, sample.time);
setRay(ray, org, normalize(dir), self->super.nearClip, inf, time);
rayCone.width = 0.f;
const uniform vec2f subImageSize = box_size(self->super.subImage);
rayCone.dwdt = self->imgPlaneSize.y * abs(subImageSize.y)
* coneShortening; // coneShortening is 1 for pixel at the center
if (self->stereoMode == OSP_STEREO_TOP_BOTTOM)
rayCone.dwdt *= 2.f;
}
SYCL_EXTERNAL void PerspectiveCamera_initRayMB(const Camera *uniform _self,
varying Ray &ray,
varying RayCone &rayCone,
const varying CameraSample &sample,
const uniform FeatureFlagsHandler &)
{
@@ -127,8 +137,15 @@ SYCL_EXTERNAL void PerspectiveCamera_initRayMB(const Camera *uniform _self,
org = org + lp;
dir = dir - lp;
}
const float coneShortening = rsqrt(dot(dir, dir));
setRay(ray, org, normalize(dir), self->super.nearClip, inf, time);
rayCone.width = 0.f;
const uniform vec2f subImageSize = box_size(self->super.subImage);
rayCone.dwdt = self->imgPlaneSize.y * abs(subImageSize.y)
* coneShortening; // cone shortening is 1 for pixel at the center
if (self->stereoMode == OSP_STEREO_TOP_BOTTOM)
rayCone.dwdt *= 2.f;
}
// Exports (called from C++) //////////////////////////////////////////////////
+1 -2
View File
@@ -20,8 +20,7 @@ struct PerspectiveCamera
// below are essentially unions: 1. if no motionBlur; 2. if motionBlur
vec3f du_size; // delta of ray direction between two pixels in x, scaled to
// focusDistance; sensor size (in x and y) and architectural
vec3f dv_up; // delta of ray direction between two pixels in y, scaled to
// focusDistance; up direction of camera
vec3f dv_up; // up vector with magnitude equal to the imagePlane size in y
vec3f ipd_offset; // shift of camera position for left/right eye (only when
// SIDE_BY_SIDE or TOP_BOTTOM); (0.5*ipd, focusDistance, 0)
+12 -28
View File
@@ -3,7 +3,6 @@
// ospray
#include "Data.h"
#include "common/ISPCRTBuffers.h"
#include "ospray/ospray.h"
#include "rkcommon/utility/getEnvVar.h"
#include "rkcommon/utility/multidim_index_sequence.h"
@@ -48,9 +47,8 @@ Data::Data(api::ISPCDevice &device, OSPDataType type, const vec3ul &numItems)
byteStride(0)
{
// TODO: is this pad out by 16 still needed?
view = make_buffer_shared_unique<char>(device.getIspcrtContext(),
size() * sizeOf(type) + 16,
ispcrt::SharedMemoryUsageHint::HostWriteDeviceRead);
view = devicert::make_buffer_shared_unique<char>(
device.getDRTDevice(), size() * sizeOf(type) + 16);
addr = view->data();
init();
@@ -92,25 +90,22 @@ void Data::init()
// Check if the shared data the app gave is actually in USM, if not we still
// need to make a copy of it internally so it's accessible on the GPU
if (shared) {
ispcrt::Context &ispcrtContext = getISPCDevice().getIspcrtContext();
ispcrt::Device &ispcrtDevice = getISPCDevice().getIspcrtDevice();
devicert::Device &device = getISPCDevice().getDRTDevice();
const size_t sizeBytes = byteStride.z * numItems.z;
auto memType = ispcrtDevice.getMemoryAllocType(addr);
auto memType = device.getPointerType(addr);
switch (memType) {
case ISPCRT_ALLOC_TYPE_HOST:
case devicert::Alloc::Host:
default:
// std::cerr << "HOST..COPYING" << std::endl;
shared = false;
view = make_buffer_shared_unique<char>(ispcrtContext,
sizeBytes, // TODO: is a padding of +16 still needed?
ispcrt::SharedMemoryUsageHint::HostWriteDeviceRead);
view = devicert::make_buffer_shared_unique<char>(device, sizeBytes);
addr = view->data();
std::memcpy(addr, appSharedPtr, sizeBytes);
break;
case ISPCRT_ALLOC_TYPE_SHARED:
case devicert::Alloc::Shared:
// std::cerr << "SHARED..USE IN PLACE" << std::endl;
break;
case ISPCRT_ALLOC_TYPE_DEVICE:
case devicert::Alloc::Device:
static bool useDeviceMemory =
(rkcommon::utility::getEnvVar<int>("OSPRAY_ALLOW_DEVICE_MEMORY")
.value_or(0)
@@ -121,23 +116,12 @@ void Data::init()
} else {
// std::cerr << "DEVICE..COPYING" << std::endl;
shared = false;
// make a handle for the app's memory
ISPCRTNewMemoryViewFlags memFlags = {
ISPCRT_ALLOC_TYPE_DEVICE, ISPCRT_SM_APPLICATION_MANAGED_DEVICE};
ISPCRTMemoryView handleOnAppsMemory = ispcrtNewMemoryView(
ispcrtDevice.handle(), appSharedPtr, sizeBytes, &memFlags);
// make ospray's shared buffer
view = make_buffer_shared_unique<char>(ispcrtContext,
sizeBytes,
ispcrt::SharedMemoryUsageHint::HostWriteDeviceRead);
view = devicert::make_buffer_shared_unique<char>(device, sizeBytes);
// copy to it
ispcrt::TaskQueue &ispcrtTaskQueue = getISPCDevice().getIspcrtQueue();
ispcrtCopyMemoryView(ispcrtTaskQueue.handle(),
view->handle(),
handleOnAppsMemory,
sizeBytes);
ispcrtTaskQueue.sync();
ispcrtRelease(handleOnAppsMemory);
device.memcpy(view->sharedPtr(), appSharedPtr, sizeBytes);
addr = view->data();
}
break;
+1 -2
View File
@@ -7,7 +7,6 @@
#include <memory>
#include "ISPCDeviceObject.h"
#include "StructShared.h"
#include "ispcrt.hpp"
// including "Data_ispc.h" breaks app code using SDK headers
#ifndef __ISPC_STRUCT_Data1D__
@@ -71,7 +70,7 @@ struct OSPRAY_SDK_INTERFACE Data : public ISPCDeviceObject
protected:
// The actual buffer storing the data
std::unique_ptr<BufferShared<char>> view;
BufferSharedUq<char> view;
char *addr{nullptr};
// We need to track the appSharedPtr separately for the GPU backend, if we
// were passed a shared ptr to memory that was not in USM we made a copy that
+117
View File
@@ -0,0 +1,117 @@
// Copyright 2024 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "common/FeatureFlags.ih"
#define ROUND_RANGE(global, group) ((global - 1) / group + 1) * group
#ifdef ISPC
#define DEFINE_RENDERER_KERNEL_LAUNCHER(kernel_name) \
task static void kernel_name##Task(Renderer *uniform renderer, \
FrameBuffer *uniform fb, \
Camera *uniform camera, \
World *uniform world, \
const uint32 *uniform taskIDs, \
const uniform FeatureFlagsHandler &ffh) \
{ \
const uniform vec3ui itemIndex = make_vec3ui(0, 0, taskIndex2); \
kernel_name(itemIndex, renderer, fb, camera, world, taskIDs, ffh); \
} \
\
export void kernel_name##Launcher(void *uniform, \
void *uniform, \
const uniform vec3ui &itemDims, \
Renderer *uniform renderer, \
FrameBuffer *uniform fb, \
Camera *uniform camera, \
World *uniform world, \
const uint32 *uniform taskIDs, \
const uniform FeatureFlags &ff) \
{ \
uniform FeatureFlagsHandler ffh; \
launch[1, 1, itemDims.z] kernel_name##Task( \
renderer, fb, camera, world, taskIDs, ffh); \
}
#define DEFINE_FRAMEOP_KERNEL_LAUNCHER(kernel_name) \
task static void kernel_name##Task( \
const uniform vec2ui &itemDims, const FrameBufferView *uniform fbv) \
{ \
const vec2ui itemIndex = \
make_vec2ui(taskIndex0 * programCount + programIndex, taskIndex1); \
if (itemIndex.x < itemDims.x) \
kernel_name(itemIndex, fbv); \
} \
\
export void kernel_name##Launcher(void *uniform, \
void *uniform, \
const uniform vec2ui &itemDims, \
const FrameBufferView *uniform fbv) \
{ \
launch[ROUND_RANGE(itemDims.x, programCount), \
itemDims.y] kernel_name##Task(itemDims, fbv); \
}
#else
#define DEFINE_RENDERER_KERNEL_LAUNCHER(kernel_name) \
extern "C" void kernel_name##Launcher(void *queue, \
void *event, \
const vec3ui &itemDims, \
Renderer *renderer, \
FrameBuffer *fb, \
Camera *camera, \
World *world, \
const uint32_t *taskIDs, \
const FeatureFlags &ff) \
{ \
sycl::queue *syclQueue = static_cast<sycl::queue *>(queue); \
sycl::event *syclEvent = static_cast<sycl::event *>(event); \
/* Submit kernel to device */ \
sycl::nd_range<3> dispatchRange( \
{itemDims.x, itemDims.y, itemDims.z}, {itemDims.x, itemDims.y, 1}); \
*syclEvent = syclQueue->submit([&](sycl::handler &cgh) { \
cgh.set_specialization_constant<ispc::specFeatureFlags>(ff); \
cgh.parallel_for(dispatchRange, \
[=](sycl::nd_item<3> itemIndex, sycl::kernel_handler kh) { \
ispc::FeatureFlagsHandler ffh(kh); \
kernel_name(vec3ui(itemIndex.get_global_id(0), \
itemIndex.get_global_id(1), \
itemIndex.get_global_id(2)), \
renderer, \
fb, \
camera, \
world, \
taskIDs, \
ffh); \
}); \
}); \
}
#define DEFINE_FRAMEOP_KERNEL_LAUNCHER(kernel_name) \
extern "C" void kernel_name##Launcher(void *queue, \
void *event, \
const vec2ui &itemDims, \
const FrameBufferView *fbv) \
{ \
sycl::queue *syclQueue = static_cast<sycl::queue *>(queue); \
sycl::event *syclEvent = static_cast<sycl::event *>(event); \
/* Submit kernel to device */ \
const vec2ui workgroupSize = vec2ui(16, 1); \
const vec2ui roundedSize = ROUND_RANGE(itemDims, workgroupSize); \
sycl::nd_range<2> dispatchRange( \
{roundedSize.x, roundedSize.y}, {workgroupSize.x, workgroupSize.y}); \
*syclEvent = syclQueue->submit([&](sycl::handler &cgh) { \
cgh.parallel_for(dispatchRange, [=](sycl::nd_item<2> itemIndex) { \
if (itemIndex.get_global_id(0) < itemDims.x) \
kernel_name( \
vec2ui(itemIndex.get_global_id(0), itemIndex.get_global_id(1)), \
fbv); \
}); \
}); \
}
#endif
+30
View File
@@ -0,0 +1,30 @@
// Copyright 2024 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#pragma once
#ifdef OSPRAY_TARGET_SYCL
#include "DeviceRTImpl_sycl.h"
#else
#include "DeviceRTImpl_ispc.h"
#endif
namespace ospray {
namespace devicert {
template <typename... Args>
inline std::unique_ptr<Device> make_device_unique(Args &&...args)
{
return std::unique_ptr<Device>(new DeviceImpl(std::forward<Args>(args)...));
}
template <typename T, typename... Args>
inline std::unique_ptr<BufferDeviceShadowed<T>>
make_buffer_device_shadowed_unique(Args &&...args)
{
return std::unique_ptr<BufferDeviceShadowed<T>>(
new BufferDeviceShadowedImpl<T>(std::forward<Args>(args)...));
}
} // namespace devicert
} // namespace ospray
+386
View File
@@ -0,0 +1,386 @@
// Copyright 2024 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#include "DeviceRTImpl_ispc.h"
#include "common/FeatureFlagsEnum.h"
#include "rkcommon/memory/malloc.h"
#include <cstring> // for memcpy
namespace ospray {
namespace devicert {
/////////////////////////////////////////////////////////////////////
// AsyncEvent implementation
void AsyncEventImpl::jobScheduled()
{
std::lock_guard<std::mutex> lock(mtx);
ready = false;
}
void AsyncEventImpl::jobStarted()
{
std::lock_guard<std::mutex> lock(mtx);
timer.start();
}
void AsyncEventImpl::jobFinished()
{
{
std::lock_guard<std::mutex> lock(mtx);
timer.stop();
ready = true;
}
cv.notify_one();
}
void AsyncEventImpl::wait() const
{
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, [this] { return ready; });
}
bool AsyncEventImpl::finished() const
{
std::lock_guard<std::mutex> lock(mtx);
return ready;
}
float AsyncEventImpl::getDuration() const
{
std::lock_guard<std::mutex> lock(mtx);
return timer.seconds();
}
void *AsyncEventImpl::getSyclEventPtr()
{
return nullptr;
}
/////////////////////////////////////////////////////////////////////
// Device implementation
// Base command class
struct DeviceImpl::Command
{
Command() = default;
Command(std::shared_ptr<AsyncEventImpl> event) : event(event) {}
virtual ~Command() = default;
virtual bool execute() = 0;
friend struct DeviceImpl;
protected:
std::shared_ptr<AsyncEventImpl> event;
};
// Shutdown device thread command
struct DeviceImpl::CommandShutdown : public Command
{
bool execute() override
{
// Just return false for loop exit
return false;
}
};
// MemCpy command
struct DeviceImpl::CommandMemCpy : public Command
{
CommandMemCpy(void *dest,
const void *src,
std::size_t size,
std::shared_ptr<AsyncEventImpl> event)
: Command(event), dest(dest), src(src), size(size)
{}
bool execute() override
{
// Do memory copying
event->jobStarted();
std::memcpy(dest, src, size);
event->jobFinished();
// Continue commands processing
return true;
}
private:
void *const dest;
const void *const src;
const std::size_t size;
};
// Launch render kernel command
struct DeviceImpl::CommandLaunchRenderKernel : public Command
{
CommandLaunchRenderKernel(const vec3ui &itemDims,
RendererKernel kernel,
ispc::Renderer *renderer,
ispc::FrameBuffer *fb,
ispc::Camera *camera,
ispc::World *world,
const uint32_t *taskIDs,
const FeatureFlags &ff,
std::shared_ptr<AsyncEventImpl> event)
: Command(event),
itemDims(itemDims),
rendererKernel(kernel),
renderer(renderer),
fb(fb),
camera(camera),
world(world),
taskIDs(taskIDs),
ff(ff)
{}
bool execute() override
{
// Run kernel
event->jobStarted();
rendererKernel(
nullptr, nullptr, itemDims, renderer, fb, camera, world, taskIDs, ff);
event->jobFinished();
// Continue commands processing
return true;
}
private:
// Domain and kernel pointer
const vec3ui itemDims;
RendererKernel rendererKernel;
// Kernel parameters
ispc::Renderer *renderer;
ispc::FrameBuffer *fb;
ispc::Camera *camera;
ispc::World *world;
const uint32_t *taskIDs;
const FeatureFlags ff;
};
// Launch FrameOp kernel command
struct DeviceImpl::CommandLaunchFrameOpKernel : public Command
{
CommandLaunchFrameOpKernel(const vec2ui &itemDims,
FrameOpKernel kernel,
const ispc::FrameBufferView *fbv,
std::shared_ptr<AsyncEventImpl> event)
: Command(event), itemDims(itemDims), frameOpKernel(kernel), fbv(fbv)
{}
bool execute() override
{
// Run kernel
event->jobStarted();
frameOpKernel(nullptr, nullptr, itemDims, fbv);
event->jobFinished();
// Continue commands processing
return true;
}
private:
// Domain and kernel pointer
const vec2ui itemDims;
FrameOpKernel frameOpKernel;
// Kernel parameters
const ispc::FrameBufferView *fbv;
};
// Run host task command
struct DeviceImpl::CommandRunHostTask : public Command
{
CommandRunHostTask(
const std::function<void()> task, std::shared_ptr<AsyncEventImpl> event)
: Command(event), hostTask(task)
{}
bool execute() override
{
// Run task
event->jobStarted();
hostTask();
event->jobFinished();
// Continue commands processing
return true;
}
private:
const std::function<void()> hostTask;
};
DeviceImpl::DeviceImpl(bool debug)
: Device(debug), workerThread([this]() {
// Main worker thread loop
CommandPtr cmd;
do {
// Lock the mutex
std::unique_lock<std::mutex> lock(queueMtx);
// Atomically release the mutex and wait. At this point, the mutex
// is released, allowing main thread to acquire it
queueCV.wait(lock, [this] { return !commandQueue.empty(); });
// When notified by the main thread and the condition is true, the
// mutex is re-acquired by the wait function before returning so we
// can safely retrieve command from the queue
cmd = std::move(commandQueue.front());
commandQueue.pop();
// Process the command
} while (cmd->execute());
})
{}
DeviceImpl::DeviceImpl(uint32_t, bool debug) : DeviceImpl(debug) {}
DeviceImpl::DeviceImpl(void *, void *, bool debug) : DeviceImpl(debug) {}
DeviceImpl::~DeviceImpl()
{
// Signal the worker thread to terminate by adding shutdown command
scheduleCommand(std::unique_ptr<Command>(new CommandShutdown()));
// And finish worker thread
workerThread.join();
}
void DeviceImpl::scheduleCommand(CommandPtr cmd)
{
{
std::lock_guard<std::mutex> lock(queueMtx);
if (cmd->event)
cmd->event->jobScheduled();
commandQueue.push(std::move(cmd));
}
queueCV.notify_one();
}
void *DeviceImpl::deviceMalloc(std::size_t size)
{
return rkcommon::memory::alignedMalloc(size);
}
void *DeviceImpl::sharedMalloc(std::size_t size)
{
return rkcommon::memory::alignedMalloc(size);
}
void *DeviceImpl::hostMalloc(std::size_t size)
{
return rkcommon::memory::alignedMalloc(size);
}
void DeviceImpl::free(void *ptr)
{
rkcommon::memory::alignedFree(ptr);
}
Alloc DeviceImpl::getPointerType(void *) const
{
return Alloc::Host;
}
void DeviceImpl::wait()
{
// Get the last event if exists
std::shared_ptr<AsyncEventImpl> lastEvent;
{
std::lock_guard<std::mutex> lock(queueMtx);
if (commandQueue.empty())
return;
lastEvent = commandQueue.back()->event;
}
// And wait for its completion
lastEvent->wait();
}
AsyncEvent DeviceImpl::createAsyncEvent()
{
std::shared_ptr<AsyncEventImpl> eventImpl =
std::make_shared<AsyncEventImpl>();
return AsyncEvent(eventImpl);
}
AsyncEvent DeviceImpl::memcpy(void *dest, const void *src, std::size_t size)
{
// Create a command with event
auto eventImpl = std::make_shared<AsyncEventImpl>();
CommandPtr cmd =
std::unique_ptr<Command>(new CommandMemCpy(dest, src, size, eventImpl));
// Put the command into the queue and signal the worker thread
scheduleCommand(std::move(cmd));
return AsyncEvent(eventImpl);
}
AsyncEvent DeviceImpl::launchRendererKernel(const vec3ui &itemDims,
RendererKernel kernel,
ispc::Renderer *renderer,
ispc::FrameBuffer *fb,
ispc::Camera *camera,
ispc::World *world,
const uint32_t *taskIDs,
const FeatureFlags &ff)
{
// Create a command with event
auto eventImpl = std::make_shared<AsyncEventImpl>();
CommandPtr cmd = std::unique_ptr<Command>(new CommandLaunchRenderKernel(
itemDims, kernel, renderer, fb, camera, world, taskIDs, ff, eventImpl));
// Put the command into the queue and signal the worker thread
scheduleCommand(std::move(cmd));
return AsyncEvent(eventImpl);
}
AsyncEvent DeviceImpl::launchFrameOpKernel(const vec2ui &itemDims,
FrameOpKernel kernel,
const ispc::FrameBufferView *fbv)
{
// Create a command with event
auto eventImpl = std::make_shared<AsyncEventImpl>();
CommandPtr cmd = std::unique_ptr<Command>(
new CommandLaunchFrameOpKernel(itemDims, kernel, fbv, eventImpl));
// Put the command into the queue and signal the worker thread
scheduleCommand(std::move(cmd));
return AsyncEvent(eventImpl);
}
AsyncEvent DeviceImpl::launchHostTask(const std::function<void()> &task)
{
// Create a command with event
auto eventImpl = std::make_shared<AsyncEventImpl>();
CommandPtr cmd =
std::unique_ptr<Command>(new CommandRunHostTask(task, eventImpl));
// Put the command into the queue and signal the worker thread
scheduleCommand(std::move(cmd));
return AsyncEvent(eventImpl);
}
void *DeviceImpl::getSyclDevicePtr()
{
// SYCL not used
return nullptr;
}
void *DeviceImpl::getSyclContextPtr()
{
// SYCL not used
return nullptr;
}
void *DeviceImpl::getSyclQueuePtr()
{
// SYCL not used
return nullptr;
}
} // namespace devicert
} // namespace ospray
+168
View File
@@ -0,0 +1,168 @@
// Copyright 2024 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "common/DeviceRT.h"
#include "rkcommon/utility/CodeTimer.h"
#include <condition_variable>
#include <mutex>
#include <queue>
#include <thread>
namespace ospray {
namespace devicert {
/////////////////////////////////////////////////////////////////////
// AsyncEvent interface
struct OSPRAY_SDK_INTERFACE AsyncEventImpl : public AsyncEventIfc
{
// Signalling job state
void jobScheduled();
void jobStarted();
void jobFinished();
// Wait for the event
void wait() const override;
// Return true if finished
bool finished() const override;
// Get event duration
float getDuration() const override;
// Get SYCL event pointer
void *getSyclEventPtr() override;
private:
// Event state
bool ready{true};
// Measure job time
rkcommon::utility::CodeTimer timer;
// Synchronization to wait on event
mutable std::mutex mtx;
mutable std::condition_variable cv;
};
/////////////////////////////////////////////////////////////////////
// Device interface
struct OSPRAY_SDK_INTERFACE DeviceImpl : public Device
{
// Construction & destruction
DeviceImpl(bool debug);
DeviceImpl(uint32_t deviceId, bool debug);
DeviceImpl(void *devicePtr, void *contextPtr, bool debug);
~DeviceImpl() override;
// Allocate device memory
void *deviceMalloc(std::size_t size) override;
// Allocate shared memory
void *sharedMalloc(std::size_t size) override;
// Allocate host memory
void *hostMalloc(std::size_t size) override;
// Release shared or device memory
void free(void *ptr) override;
// Get pointer allocation type
Alloc getPointerType(void *ptr) const override;
// Wait for device to finish its pending work
void wait() override;
// Create asynchronous event object
AsyncEvent createAsyncEvent() override;
// Copy memory from/to device
AsyncEvent memcpy(void *dest, const void *src, std::size_t size) override;
// Launch a kernel on a device
AsyncEvent launchRendererKernel(const vec3ui &itemDims,
RendererKernel kernel,
ispc::Renderer *renderer,
ispc::FrameBuffer *fb,
ispc::Camera *camera,
ispc::World *world,
const uint32_t *taskIDs,
const FeatureFlags &ff) override;
AsyncEvent launchFrameOpKernel(const vec2ui &itemDims,
FrameOpKernel kernel,
const ispc::FrameBufferView *fbv) override;
// Launch a given task on a host using device queue ordering
AsyncEvent launchHostTask(const std::function<void()> &task) override;
// For code (e.g. OIDN API) that is able to use SYCL without including it
void *getSyclDevicePtr() override;
void *getSyclContextPtr() override;
void *getSyclQueuePtr() override;
private:
// Inner command classes
class Command;
class CommandShutdown;
class CommandMemCpy;
class CommandLaunchRenderKernel;
class CommandLaunchFrameOpKernel;
class CommandRunHostTask;
using CommandPtr = std::unique_ptr<Command>;
// Device command queue
std::queue<CommandPtr> commandQueue;
std::mutex queueMtx;
std::condition_variable queueCV;
// Device worker thread
std::thread workerThread;
// Schedule command for execution
void scheduleCommand(CommandPtr cmd);
};
/////////////////////////////////////////////////////////////////////
// Buffer in device memory with system memory shadow
template <typename T>
struct BufferDeviceShadowedImpl : public BufferDeviceShadowed<T>
{
// Inherit constructors
BufferDeviceShadowedImpl(Device &device, std::size_t count);
BufferDeviceShadowedImpl(Device &device, const std::vector<T> &v);
BufferDeviceShadowedImpl(Device &device, T *data, std::size_t count);
protected:
// Copy between device and shadow buffers
AsyncEvent memcpy(T *, const T *, std::size_t) override
{
return AsyncEvent();
}
};
template <typename T>
BufferDeviceShadowedImpl<T>::BufferDeviceShadowedImpl(
Device &device, std::size_t count)
: BufferDeviceShadowed<T>(device, nullptr, count)
{}
template <typename T>
BufferDeviceShadowedImpl<T>::BufferDeviceShadowedImpl(
Device &device, const std::vector<T> &v)
: BufferDeviceShadowed<T>(device, nullptr, v)
{}
template <typename T>
BufferDeviceShadowedImpl<T>::BufferDeviceShadowedImpl(
Device &device, T *data, std::size_t count)
: BufferDeviceShadowed<T>(device, nullptr, data, count)
{}
} // namespace devicert
} // namespace ospray
+217
View File
@@ -0,0 +1,217 @@
// Copyright 2024 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#include "DeviceRTImpl_sycl.h"
namespace ospray {
namespace devicert {
/////////////////////////////////////////////////////////////////////
// AsyncEvent implementation
void AsyncEventImpl::wait() const
{
event.wait();
}
bool AsyncEventImpl::finished() const
{
return (event.get_info<sycl::info::event::command_execution_status>()
== sycl::info::event_command_status::complete);
}
float AsyncEventImpl::getDuration() const
{
try {
const auto t0 =
event.get_profiling_info<sycl::info::event_profiling::command_start>();
const auto t1 =
event.get_profiling_info<sycl::info::event_profiling::command_end>();
return (t1 - t0) * 1.0e-9f;
} catch (...) {
// In case no profiling data is available
return 0.f;
}
}
void *AsyncEventImpl::getSyclEventPtr()
{
return &event;
}
/////////////////////////////////////////////////////////////////////
// Device implementation
DeviceImpl::DeviceImpl(bool debug)
: Device(debug),
device(sycl::gpu_selector_v),
context(device),
queue(context,
device,
{sycl::property::queue::enable_profiling(),
sycl::property::queue::in_order()})
{
postStatusMsg(OSP_LOG_INFO)
<< "Using SYCL GPU device on "
<< device.get_info<sycl::info::device::name>() << " device (default)";
}
namespace {
sycl::device getDeviceByIndex(uint32_t id)
{
auto gpuDevices = sycl::device::get_devices(sycl::info::device_type::gpu);
return gpuDevices[id % gpuDevices.size()];
}
} // namespace
DeviceImpl::DeviceImpl(uint32_t deviceId, bool debug)
: Device(debug),
device(getDeviceByIndex(deviceId)),
context(device),
queue(context,
device,
{sycl::property::queue::enable_profiling(),
sycl::property::queue::in_order()})
{
postStatusMsg(OSP_LOG_INFO) << "Using SYCL GPU device on "
<< device.get_info<sycl::info::device::name>()
<< " device (number: " << deviceId << ")";
}
DeviceImpl::DeviceImpl(void *devicePtr, void *contextPtr, bool debug)
: Device(debug),
device(*static_cast<sycl::device *>(devicePtr)),
context(*static_cast<sycl::context *>(contextPtr)),
queue(context,
device,
{sycl::property::queue::enable_profiling(),
sycl::property::queue::in_order()})
{
postStatusMsg(OSP_LOG_INFO) << "Using SYCL GPU device on "
<< device.get_info<sycl::info::device::name>()
<< " device (provided externally)";
}
void *DeviceImpl::deviceMalloc(std::size_t size)
{
return sycl::malloc_device(size, queue);
}
void *DeviceImpl::sharedMalloc(std::size_t size)
{
return sycl::malloc_shared(
size, queue, sycl::ext::oneapi::property::usm::device_read_only());
}
void *DeviceImpl::hostMalloc(std::size_t size)
{
return sycl::malloc_host(size, queue);
}
void DeviceImpl::free(void *ptr)
{
sycl::free(ptr, queue);
}
Alloc DeviceImpl::getPointerType(void *ptr) const
{
sycl::usm::alloc type = sycl::get_pointer_type(ptr, queue.get_context());
switch (type) {
case sycl::usm::alloc::host:
return Alloc::Host;
case sycl::usm::alloc::device:
return Alloc::Device;
case sycl::usm::alloc::shared:
return Alloc::Shared;
case sycl::usm::alloc::unknown:
return Alloc::Unknown;
}
return Alloc::Unknown;
}
void DeviceImpl::wait()
{
queue.wait();
}
AsyncEvent DeviceImpl::createAsyncEvent()
{
std::shared_ptr<AsyncEventImpl> eventImpl =
std::make_shared<AsyncEventImpl>();
return AsyncEvent(eventImpl);
}
AsyncEvent DeviceImpl::memcpy(void *dest, const void *src, std::size_t size)
{
// Create async event and do memory copying
std::shared_ptr<AsyncEventImpl> eventImpl =
std::make_shared<AsyncEventImpl>();
eventImpl->event = queue.memcpy(dest, src, size);
return AsyncEvent(eventImpl);
}
AsyncEvent DeviceImpl::launchRendererKernel(const vec3ui &itemDims,
RendererKernel kernel,
ispc::Renderer *renderer,
ispc::FrameBuffer *fb,
ispc::Camera *camera,
ispc::World *world,
const uint32_t *taskIDs,
const FeatureFlags &ff)
{
// Create async event and launch a kernel
std::shared_ptr<AsyncEventImpl> eventImpl =
std::make_shared<AsyncEventImpl>();
kernel(&queue,
&eventImpl->event,
itemDims,
renderer,
fb,
camera,
world,
taskIDs,
ff);
return AsyncEvent(eventImpl);
}
AsyncEvent DeviceImpl::launchFrameOpKernel(const vec2ui &itemDims,
FrameOpKernel kernel,
const ispc::FrameBufferView *fbv)
{
// Create async event and launch a kernel
std::shared_ptr<AsyncEventImpl> eventImpl =
std::make_shared<AsyncEventImpl>();
kernel(&queue, &eventImpl->event, itemDims, fbv);
return AsyncEvent(eventImpl);
}
AsyncEvent DeviceImpl::launchHostTask(const std::function<void()> &task)
{
// Create async event and launch a task
std::shared_ptr<AsyncEventImpl> eventImpl =
std::make_shared<AsyncEventImpl>();
eventImpl->event = queue.submit(
[&](sycl::handler &cgh) { cgh.host_task([=]() { task(); }); });
return AsyncEvent(eventImpl);
}
void *DeviceImpl::getSyclDevicePtr()
{
// Return SYCL device pointer
return &device;
}
void *DeviceImpl::getSyclContextPtr()
{
// Return SYCL context pointer
return &context;
}
void *DeviceImpl::getSyclQueuePtr()
{
// Return SYCL command queue pointer
return &queue;
}
} // namespace devicert
} // namespace ospray
+156
View File
@@ -0,0 +1,156 @@
// Copyright 2024 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "common/DeviceRT.h"
#include <sycl/sycl.hpp>
namespace ospray {
namespace devicert {
/////////////////////////////////////////////////////////////////////
// AsyncEvent interface
struct OSPRAY_SDK_INTERFACE AsyncEventImpl : public AsyncEventIfc
{
// Wait for the event
void wait() const override;
// Return true if finished
bool finished() const override;
// Get event duration
float getDuration() const override;
// Allow DeviceImpl to access event
friend struct DeviceImpl;
// Get SYCL event pointer
void *getSyclEventPtr() override;
private:
mutable sycl::event event;
};
/////////////////////////////////////////////////////////////////////
// Device interface
struct OSPRAY_SDK_INTERFACE DeviceImpl : public Device
{
// Construction & destruction
DeviceImpl(bool debug);
DeviceImpl(uint32_t deviceId, bool debug);
DeviceImpl(void *devicePtr, void *contextPtr, bool debug);
// Allocate device memory
void *deviceMalloc(std::size_t size) override;
// Allocate shared memory
void *sharedMalloc(std::size_t size) override;
// Allocate host memory
void *hostMalloc(std::size_t size) override;
// Release shared or device memory
void free(void *ptr) override;
// Get pointer allocation type
Alloc getPointerType(void *ptr) const override;
// Wait for device to finish its pending work
void wait() override;
// Create asynchronous event object
AsyncEvent createAsyncEvent() override;
// Copy memory from/to device
AsyncEvent memcpy(void *dest, const void *src, std::size_t size) override;
// Launch a kernel on a device
AsyncEvent launchRendererKernel(const vec3ui &itemDims,
RendererKernel kernel,
ispc::Renderer *renderer,
ispc::FrameBuffer *fb,
ispc::Camera *camera,
ispc::World *world,
const uint32_t *taskIDs,
const FeatureFlags &ff) override;
AsyncEvent launchFrameOpKernel(const vec2ui &itemDims,
FrameOpKernel kernel,
const ispc::FrameBufferView *fbv) override;
// Launch a given task on a host using device queue ordering
AsyncEvent launchHostTask(const std::function<void()> &task) override;
// For code (e.g. OIDN API) that is able to use SYCL without including it
void *getSyclDevicePtr() override;
void *getSyclContextPtr() override;
void *getSyclQueuePtr() override;
private:
sycl::device device;
sycl::context context;
sycl::queue queue;
};
/////////////////////////////////////////////////////////////////////
// Buffer in device memory with system memory shadow
template <typename T>
struct BufferDeviceShadowedImpl : public BufferDeviceShadowed<T>
{
// Bring these members into scope of derived class
using BufferDeviceShadowed<T>::device;
using BufferDeviceShadowed<T>::devPtr;
// Inherit constructors
BufferDeviceShadowedImpl(Device &device, std::size_t count);
BufferDeviceShadowedImpl(Device &device, const std::vector<T> &v);
BufferDeviceShadowedImpl(Device &device, T *data, std::size_t count);
~BufferDeviceShadowedImpl() override;
protected:
// Copy between device and shadow buffers
AsyncEvent memcpy(T *dest, const T *src, std::size_t count) override;
};
template <typename T>
BufferDeviceShadowedImpl<T>::BufferDeviceShadowedImpl(
Device &device, std::size_t count)
: BufferDeviceShadowed<T>(
device, static_cast<T *>(device.deviceMalloc(count * sizeof(T))), count)
{}
template <typename T>
BufferDeviceShadowedImpl<T>::BufferDeviceShadowedImpl(
Device &device, const std::vector<T> &v)
: BufferDeviceShadowed<T>(
device, static_cast<T *>(device.deviceMalloc(v.size() * sizeof(T))), v)
{}
template <typename T>
BufferDeviceShadowedImpl<T>::BufferDeviceShadowedImpl(
Device &device, T *data, std::size_t count)
: BufferDeviceShadowed<T>(device,
static_cast<T *>(device.deviceMalloc(count * sizeof(T))),
data,
count)
{}
template <typename T>
BufferDeviceShadowedImpl<T>::~BufferDeviceShadowedImpl()
{
device.free(devPtr);
}
template <typename T>
AsyncEvent BufferDeviceShadowedImpl<T>::memcpy(
T *dest, const T *src, std::size_t count)
{
return device.memcpy(dest, src, count * sizeof(T));
}
} // namespace devicert
} // namespace ospray
+8 -6
View File
@@ -38,21 +38,23 @@ struct DifferentialGeometry
const Renderer *uniform renderer; // pointer to renderer being used
unsigned int objID; // user definable model id (0xffff none)
unsigned int instID; // user definable instance id (0xffff none)
float pixelFootprint; // 1:1 mapping between pixels and texels
};
// assumed precision of intersection routines
#define ulpEpsilon 0x1.0fp-21f
inline float calcEpsilon(const vec3f &P, float t)
{
return reduce_max(make_vec4f(abs(P), t)) * ulpEpsilon;
}
inline float calcEpsilon(const vec3f &P, const vec3f &dir, float t)
{
// convert ray-space t to object-/world-space using max(dir) instead of
// costly length; the error is at most sqrt(3)~1.7, quite acceptable for eps
return reduce_max(make_vec4f(abs(P), reduce_max(abs(dir)) * t)) * ulpEpsilon;
return calcEpsilon(P, reduce_max(abs(dir)) * t);
}
inline float calcEpsilon(const vec3f &P, float dist)
{
const vec3f dummy_dir = make_vec3f(1.0f);
return calcEpsilon(P, dummy_dir, dist);
}
OSPRAY_END_ISPC_NAMESPACE
+8
View File
@@ -36,27 +36,35 @@ enum FeatureFlagsGeometry
FFG_CONE_LINEAR_CURVE = RTC_FEATURE_FLAG_CONE_LINEAR_CURVE,
FFG_ROUND_LINEAR_CURVE = RTC_FEATURE_FLAG_ROUND_LINEAR_CURVE,
FFG_FLAT_LINEAR_CURVE = RTC_FEATURE_FLAG_FLAT_LINEAR_CURVE,
FFG_LINEAR_CURVE = RTC_FEATURE_FLAG_LINEAR_CURVES,
FFG_ROUND_BEZIER_CURVE = RTC_FEATURE_FLAG_ROUND_BEZIER_CURVE,
FFG_FLAT_BEZIER_CURVE = RTC_FEATURE_FLAG_FLAT_BEZIER_CURVE,
FFG_NORMAL_ORIENTED_BEZIER_CURVE =
RTC_FEATURE_FLAG_NORMAL_ORIENTED_BEZIER_CURVE,
FFG_BEZIER_CURVE = RTC_FEATURE_FLAG_BEZIER_CURVES,
FFG_ROUND_BSPLINE_CURVE = RTC_FEATURE_FLAG_ROUND_BSPLINE_CURVE,
FFG_FLAT_BSPLINE_CURVE = RTC_FEATURE_FLAG_FLAT_BSPLINE_CURVE,
FFG_NORMAL_ORIENTED_BSPLINE_CURVE =
RTC_FEATURE_FLAG_NORMAL_ORIENTED_BSPLINE_CURVE,
FFG_BSPLINE_CURVE = RTC_FEATURE_FLAG_BSPLINE_CURVES,
FFG_ROUND_HERMITE_CURVE = RTC_FEATURE_FLAG_ROUND_HERMITE_CURVE,
FFG_FLAT_HERMITE_CURVE = RTC_FEATURE_FLAG_FLAT_HERMITE_CURVE,
FFG_NORMAL_ORIENTED_HERMITE_CURVE =
RTC_FEATURE_FLAG_NORMAL_ORIENTED_HERMITE_CURVE,
FFG_HERMITE_CURVE = RTC_FEATURE_FLAG_HERMITE_CURVES,
FFG_ROUND_CATMULL_ROM_CURVE = RTC_FEATURE_FLAG_ROUND_CATMULL_ROM_CURVE,
FFG_FLAT_CATMULL_ROM_CURVE = RTC_FEATURE_FLAG_FLAT_CATMULL_ROM_CURVE,
FFG_NORMAL_ORIENTED_CATMULL_ROM_CURVE =
RTC_FEATURE_FLAG_NORMAL_ORIENTED_CATMULL_ROM_CURVE,
FFG_CATMULL_ROM_CURVE = 0 | RTC_FEATURE_FLAG_ROUND_CATMULL_ROM_CURVE
| RTC_FEATURE_FLAG_FLAT_CATMULL_ROM_CURVE
| RTC_FEATURE_FLAG_NORMAL_ORIENTED_CATMULL_ROM_CURVE,
FFG_SPHERE = RTC_FEATURE_FLAG_SPHERE_POINT,
FFG_DISC_POINT = RTC_FEATURE_FLAG_DISC_POINT,
FFG_ORIENTED_DISC_POINT = RTC_FEATURE_FLAG_ORIENTED_DISC_POINT,
+13 -10
View File
@@ -41,7 +41,7 @@ static void freeAndNullifyEmbreeScene(RTCScene &scene)
// Group definitions ////////////////////////////////////////////////////////
Group::Group(api::ISPCDevice &device)
: AddStructShared(device.getIspcrtContext(), device)
: AddStructShared(device.getDRTDevice(), device)
{
managedObjectType = OSP_GROUP;
}
@@ -133,9 +133,10 @@ void Group::commit()
sceneFlags,
buildQuality);
geometricModelsArray = make_buffer_shared_unique<ispc::GeometricModel *>(
getISPCDevice().getIspcrtContext(),
createArrayOfSh<ispc::GeometricModel>(*geometricModels));
geometricModelsArray =
devicert::make_buffer_shared_unique<ispc::GeometricModel *>(
getISPCDevice().getDRTDevice(),
createArrayOfSh<ispc::GeometricModel>(*geometricModels));
getSh()->geometricModels = geometricModelsArray->sharedPtr();
rtcCommitScene(sceneGeometries);
@@ -150,9 +151,10 @@ void Group::commit()
sceneFlags,
buildQuality);
volumetricModelsArray = make_buffer_shared_unique<ispc::VolumetricModel *>(
getISPCDevice().getIspcrtContext(),
createArrayOfSh<ispc::VolumetricModel>(*volumetricModels));
volumetricModelsArray =
devicert::make_buffer_shared_unique<ispc::VolumetricModel *>(
getISPCDevice().getDRTDevice(),
createArrayOfSh<ispc::VolumetricModel>(*volumetricModels));
getSh()->volumetricModels = volumetricModelsArray->sharedPtr();
rtcCommitScene(sceneVolumes);
@@ -168,9 +170,10 @@ void Group::commit()
| RTC_SCENE_FLAG_ROBUST,
buildQuality);
clipModelsArray = make_buffer_shared_unique<ispc::GeometricModel *>(
getISPCDevice().getIspcrtContext(),
createArrayOfSh<ispc::GeometricModel>(*clipModels));
clipModelsArray =
devicert::make_buffer_shared_unique<ispc::GeometricModel *>(
getISPCDevice().getDRTDevice(),
createArrayOfSh<ispc::GeometricModel>(*clipModels));
getSh()->clipModels = clipModelsArray->sharedPtr();
numInvertedClippers = 0;
+3 -3
View File
@@ -54,11 +54,11 @@ struct OSPRAY_SDK_INTERFACE Group
private:
FeatureFlags featureFlags;
std::unique_ptr<BufferShared<ispc::GeometricModel *>> geometricModelsArray;
BufferSharedUq<ispc::GeometricModel *> geometricModelsArray;
#ifdef OSPRAY_ENABLE_VOLUMES
std::unique_ptr<BufferShared<ispc::VolumetricModel *>> volumetricModelsArray;
BufferSharedUq<ispc::VolumetricModel *> volumetricModelsArray;
#endif
std::unique_ptr<BufferShared<ispc::GeometricModel *>> clipModelsArray;
BufferSharedUq<ispc::GeometricModel *> clipModelsArray;
};
OSPTYPEFOR_SPECIALIZATION(Group *, OSP_GROUP);
-243
View File
@@ -1,243 +0,0 @@
// Copyright 2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <cstring>
#include <memory>
#include <vector>
#include "ispcrt.hpp"
namespace ospray {
/////////////////////////////////////////////////////////////////////
// BufferDevice
template <typename T>
struct BufferDevice : public ispcrt::Array<T, ispcrt::AllocType::Device>
{
using ispcrt::Array<T, ispcrt::AllocType::Device>::devicePtr;
BufferDevice(ispcrt::Device &device, T *hostPtr = nullptr);
BufferDevice(ispcrt::Device &device, size_t size);
};
template <typename T>
BufferDevice<T>::BufferDevice(ispcrt::Device &device, T *hostPtr)
: ispcrt::Array<T, ispcrt::AllocType::Device>(device, hostPtr)
{}
template <typename T>
BufferDevice<T>::BufferDevice(ispcrt::Device &device, size_t size)
: ispcrt::Array<T, ispcrt::AllocType::Device>(device, nullptr, size)
{}
template <typename T, typename... Args>
inline std::unique_ptr<BufferDevice<T>> make_buffer_device_unique(
Args &&...args)
{
return std::unique_ptr<BufferDevice<T>>(
new BufferDevice<T>(std::forward<Args>(args)...));
}
/////////////////////////////////////////////////////////////////////
// BufferDeviceShadowed
template <typename T>
struct BufferDeviceShadowed : public std::vector<T>,
public ispcrt::Array<T, ispcrt::AllocType::Device>
{
using ispcrt::Array<T, ispcrt::AllocType::Device>::devicePtr;
using std::vector<T>::size;
BufferDeviceShadowed(ispcrt::Device &device, size_t size);
BufferDeviceShadowed(ispcrt::Device &device, std::vector<T> &v);
BufferDeviceShadowed(ispcrt::Device &device, T *data, size_t size);
};
template <typename T>
BufferDeviceShadowed<T>::BufferDeviceShadowed(
ispcrt::Device &device, size_t size)
: std::vector<T>(size),
ispcrt::Array<T, ispcrt::AllocType::Device>(
device, std::vector<T>::data(), size)
{}
template <typename T>
BufferDeviceShadowed<T>::BufferDeviceShadowed(
ispcrt::Device &device, std::vector<T> &v)
: std::vector<T>(v),
ispcrt::Array<T, ispcrt::AllocType::Device>(
device, std::vector<T>::data(), v.size())
{}
template <typename T>
BufferDeviceShadowed<T>::BufferDeviceShadowed(
ispcrt::Device &device, T *data, size_t size)
: std::vector<T>(data, data + size),
ispcrt::Array<T, ispcrt::AllocType::Device>(
device, std::vector<T>::data(), size)
{}
template <typename T, typename... Args>
inline std::unique_ptr<BufferDeviceShadowed<T>>
make_buffer_device_shadowed_unique(Args &&...args)
{
return std::unique_ptr<BufferDeviceShadowed<T>>(
new BufferDeviceShadowed<T>(std::forward<Args>(args)...));
}
/////////////////////////////////////////////////////////////////////
// BufferShared C version
inline ISPCRTMemoryView BufferSharedCreate(ISPCRTContext context,
size_t size,
ISPCRTSharedMemoryAllocationHint allocHint =
ISPCRT_SM_HOST_DEVICE_READ_WRITE)
{
ISPCRTNewMemoryViewFlags flags;
flags.allocType = ISPCRT_ALLOC_TYPE_SHARED;
flags.smHint = allocHint;
return ispcrtNewMemoryViewForContext(context, nullptr, size, &flags);
}
inline void BufferSharedDelete(ISPCRTMemoryView view)
{
ispcrtRelease(view);
}
/////////////////////////////////////////////////////////////////////
// BufferShared C++ version
template <typename T>
struct BufferShared : public ispcrt::Array<T, ispcrt::AllocType::Shared>
{
using ispcrt::Array<T, ispcrt::AllocType::Shared>::size;
BufferShared(ispcrt::Context &context,
ispcrt::SharedMemoryUsageHint allocHint =
ispcrt::SharedMemoryUsageHint::HostDeviceReadWrite);
BufferShared(ispcrt::Context &context,
size_t size,
ispcrt::SharedMemoryUsageHint allocHint =
ispcrt::SharedMemoryUsageHint::HostDeviceReadWrite);
BufferShared(ispcrt::Context &context,
const std::vector<T> &v,
ispcrt::SharedMemoryUsageHint allocHint =
ispcrt::SharedMemoryUsageHint::HostDeviceReadWrite);
BufferShared(ispcrt::Context &context,
const T *data,
size_t size,
ispcrt::SharedMemoryUsageHint allocHint =
ispcrt::SharedMemoryUsageHint::HostDeviceReadWrite);
T *data();
const T *data() const;
T *begin();
T *end();
const T *cbegin() const;
const T *cend() const;
T &operator[](const size_t i);
const T &operator[](const size_t i) const;
T *sharedPtr() const;
};
template <typename T>
BufferShared<T>::BufferShared(
ispcrt::Context &context, ispcrt::SharedMemoryUsageHint allocHint)
: ispcrt::Array<T, ispcrt::AllocType::Shared>(context, allocHint)
{}
template <typename T>
BufferShared<T>::BufferShared(ispcrt::Context &context,
size_t size,
ispcrt::SharedMemoryUsageHint allocHint)
: ispcrt::Array<T, ispcrt::AllocType::Shared>(context, size, allocHint)
{}
template <typename T>
BufferShared<T>::BufferShared(ispcrt::Context &context,
const std::vector<T> &v,
ispcrt::SharedMemoryUsageHint allocHint)
: ispcrt::Array<T, ispcrt::AllocType::Shared>(context, v.size(), allocHint)
{
std::memcpy(sharedPtr(), v.data(), sizeof(T) * v.size());
}
template <typename T>
BufferShared<T>::BufferShared(ispcrt::Context &context,
const T *data,
size_t size,
ispcrt::SharedMemoryUsageHint allocHint)
: ispcrt::Array<T, ispcrt::AllocType::Shared>(context, size, allocHint)
{
std::memcpy(sharedPtr(), data, sizeof(T) * size);
}
template <typename T>
T *BufferShared<T>::data()
{
return sharedPtr();
}
template <typename T>
const T *BufferShared<T>::data() const
{
return sharedPtr();
}
template <typename T>
T *BufferShared<T>::begin()
{
return data();
}
template <typename T>
T *BufferShared<T>::end()
{
return begin() + size();
}
template <typename T>
const T *BufferShared<T>::cbegin() const
{
return data();
}
template <typename T>
const T *BufferShared<T>::cend() const
{
return cbegin() + size();
}
template <typename T>
T &BufferShared<T>::operator[](const size_t i)
{
return *(data() + i);
}
template <typename T>
const T &BufferShared<T>::operator[](const size_t i) const
{
return *(data() + i);
}
// The below method is WA for Level Zero bug, when running on GPU sharedPtr()
// crashes on 0-sized ispcrt::Array
template <typename T>
T *BufferShared<T>::sharedPtr() const
{
return size() ? ispcrt::Array<T, ispcrt::AllocType::Shared>::sharedPtr()
: nullptr;
}
template <typename T, typename... Args>
inline std::unique_ptr<BufferShared<T>> make_buffer_shared_unique(
Args &&...args)
{
return std::unique_ptr<BufferShared<T>>(
new BufferShared<T>(std::forward<Args>(args)...));
}
} // namespace ospray
+1 -1
View File
@@ -7,7 +7,7 @@
namespace ospray {
Instance::Instance(api::ISPCDevice &device, Group *_group)
: AddStructShared(device.getIspcrtContext(), device), groupAPI(_group)
: AddStructShared(device.getDRTDevice(), device), groupAPI(_group)
{
managedObjectType = OSP_INSTANCE;
}
+1 -2
View File
@@ -63,7 +63,7 @@ inline void Instance_postIntersect(const Instance *uniform self,
const uniform FeatureFlagsGeometry ffg = getFeatureFlagsGeometry(ffh);
if ((flags & DG_MOTIONBLUR) == DG_MOTIONBLUR && self->motionBlur
&& (ffg & FFG_MOTION_BLUR)) {
uniform float utime;
uniform float utime = 0.f;
uniform int cnt = 0;
foreach_unique (t in ray.time) {
utime = t;
@@ -80,7 +80,6 @@ inline void Instance_postIntersect(const Instance *uniform self,
// scale dg.epsilon by max (epsilon is scalar and thus assumed to be
// isotropic anyway and hence cannot better handle non-uniform scaling)
dg.epsilon *= max(abs(xfm.l.vx.x), max(abs(xfm.l.vy.y), abs(xfm.l.vz.z)));
if (flags & DG_TANGENTS) {
dg.dPds = xfmVector(xfm, dg.dPds);
dg.dPdt = xfmVector(xfm, dg.dPdt);
+196 -49
View File
@@ -3,6 +3,12 @@
#pragma once
#include "rkcommon/math/vec.ih"
#define STRING(x) #x
#define TOSTRING(x) STRING(x)
#define CODE_LOCATION __FILE__ " (" TOSTRING(__LINE__) ")"
#ifdef OSPRAY_TARGET_SYCL
#include <sycl/sycl.hpp>
@@ -23,91 +29,232 @@ using int16 = int16_t;
using int8 = int8_t;
} // namespace ispc
#define LOG(x)
#define PING \
sycl::ext::oneapi::experimental::printf(CODE_LOCATION ": " __FUNCTION__ "\n")
#undef PRINT
#undef PRINT3
#undef PRINTV
// Skip printing in host code.
#define PRINT(x)
#define PRINT3(x)
#define PRINTU(x)
#define PRINT3U(x)
#define PRINTV(x)
// Note: SYCL printf needs the type specifier, unlike ISPC. So, we need
// overloaded functions to print based on the type of the parameter. We use a
// wrapper macro to extract argument's name as a char string to print both name
// and value of the variable.
/*
// Note: SYCL printf needs the type specifier, unlike ISPC. So instead of a
// macro we make a function that looks like the macro but overloads based on the
// type
#ifdef __SYCL_DEVICE_ONLY__
// rkcommon has its own macros for the host that we conflict with
#undef PRINT
#undef PRINT3
#undef PRINTV
void PRINT(const int &x)
#define CONSTANT __attribute__((opencl_constant))
void print_(const CONSTANT char *name, const int &x)
{
sycl::ext::oneapi::experimental::printf("#x = %d\n", x);
sycl::ext::oneapi::experimental::printf("%s = %d\n", name, x);
}
void PRINT(const uint32_t &x)
void print_(const CONSTANT char *name, const float &x)
{
sycl::ext::oneapi::experimental::printf("#x = %u\n", x);
sycl::ext::oneapi::experimental::printf("%s = %f\n", name, x);
}
void PRINT(const float &x)
void print_(const CONSTANT char *name, const uint32_t &x)
{
sycl::ext::oneapi::experimental::printf("#x = %f\n", x);
sycl::ext::oneapi::experimental::printf("%s = %u\n", name, x);
}
void PRINT3(const rkcommon::math::vec3i &x)
void print_(const CONSTANT char *name, const ispc::vec2i &v)
{
sycl::ext::oneapi::experimental::printf("%s = (%d, %d)\n", name, v.x, v.y);
}
void print_(const CONSTANT char *name, const ispc::vec2f &v)
{
sycl::ext::oneapi::experimental::printf("%s = (%f, %f)\n", name, v.x, v.y);
}
void print_(const CONSTANT char *name, const ispc::vec3i &v)
{
sycl::ext::oneapi::experimental::printf(
"#x = (%d, %d, %d)\n", x.x, x.y, x.z);
"%s = (%d, %d, %d)\n", name, v.x, v.y, v.z);
}
void PRINT3(const rkcommon::math::vec3ui &x)
void print_(const CONSTANT char *name, const ispc::vec3f &v)
{
sycl::ext::oneapi::experimental::printf(
"#x = (%u, %u, %u)\n", x.x, x.y, x.z);
"%s = (%f, %f, %f)\n", name, v.x, v.y, v.z);
}
void PRINT3(const rkcommon::math::vec3f &x)
void print_(const CONSTANT char *name, const ispc::vec4i &v)
{
sycl::ext::oneapi::experimental::printf(
"#x = (%f, %f, %f)\n", x.x, x.y, x.z);
"%s = (%d, %d, %d, %d)\n", name, v.x, v.y, v.z, v.w);
}
// SYCL is scalar, PRINTU = PRINT, PRINT3U = PRINT3
#define PRINTU(x) PRINT
#define PRINT3U(x) PRINT3
void print_(const CONSTANT char *name, const ispc::vec4f &v)
{
sycl::ext::oneapi::experimental::printf(
"%s = (%f, %f, %f, %f)\n", name, v.x, v.y, v.z, v.w);
}
void print_(const CONSTANT char *name, const CONSTANT char *s)
{
sycl::ext::oneapi::experimental::printf("%s = %s\n", name, s);
}
#define PRINT(x) \
{ \
static const CONSTANT char var_name[] = #x; \
print_(var_name, x); \
}
// SYCL is scalar, PRINTV = PRINT
#define PRINTV(x) PRINT(x);
#define PRINT_STR(s) sycl::ext::oneapi::experimental::printf(s);
#endif
*/
#else
#define __noinline
#else // ISPC
#define LOG(x)
#define PING print(CODE_LOCATION "\n")
#define PRINT(x) print(#x " = %\n", x)
#define PRINT3(v) print(#v " = (%, %, %)\n", v.x, v.y, v.z)
// prints first unmasked element
#define PRINTU(x) \
print(#x "[%] = %\n", \
count_trailing_zeros(lanemask()), \
extract(x, count_trailing_zeros(lanemask())))
#define PRINT2U(v) \
print(#v "[%] = (%, %)\n", \
count_trailing_zeros(lanemask()), \
extract(v.x, count_trailing_zeros(lanemask())), \
extract(v.y, count_trailing_zeros(lanemask())))
#define PRINT3U(v) \
print(#v "[%] = (%, %, %)\n", \
count_trailing_zeros(lanemask()), \
extract(v.x, count_trailing_zeros(lanemask())), \
extract(v.y, count_trailing_zeros(lanemask())), \
extract(v.z, count_trailing_zeros(lanemask())))
#define __noinline noinline
#define PRINT_STR(s) print(s);
inline void printv_(const int &x)
{
print("%\n", x);
}
inline void printv_(const float &x)
{
print("%\n", x);
}
inline void printv_(const uint32 &x)
{
print("%\n", x);
}
inline void printv_(const vec2i &v)
{
print("(%, %)\n", v.x, v.y);
}
inline void printv_(const vec2f &v)
{
print("(%, %)\n", v.x, v.y);
}
inline void printv_(const vec3i &v)
{
print("(% % %)\n", v.x, v.y, v.z);
}
inline void printv_(const vec3f &v)
{
print("(% % %)\n", v.x, v.y, v.z);
}
inline void printv_(const vec4i &v)
{
print("(% % % %)\n", v.x, v.y, v.z, v.w);
}
inline void printv_(const vec4f &v)
{
print("(% % % %)\n", v.x, v.y, v.z, v.w);
}
#define PRINTV(x) \
{ \
print(#x " = "); \
printv_(x); \
}
inline void print_(const int &x)
{
print("[%] = %\n",
count_trailing_zeros(lanemask()),
extract(x, count_trailing_zeros(lanemask())));
}
inline void print_(const float &x)
{
print("[%] = %\n",
count_trailing_zeros(lanemask()),
extract(x, count_trailing_zeros(lanemask())));
}
inline void print_(const uint32 &x)
{
print("[%] = %\n",
count_trailing_zeros(lanemask()),
extract(x, count_trailing_zeros(lanemask())));
}
inline void print_(const vec2i &v)
{
print("[%] = (%, %)\n",
count_trailing_zeros(lanemask()),
extract(v.x, count_trailing_zeros(lanemask())),
extract(v.y, count_trailing_zeros(lanemask())));
}
inline void print_(const vec2f &v)
{
print("[%] = (%, %)\n",
count_trailing_zeros(lanemask()),
extract(v.x, count_trailing_zeros(lanemask())),
extract(v.y, count_trailing_zeros(lanemask())));
}
inline void print_(const vec3i &v)
{
print("[%] = (%, %, %)\n",
count_trailing_zeros(lanemask()),
extract(v.x, count_trailing_zeros(lanemask())),
extract(v.y, count_trailing_zeros(lanemask())),
extract(v.z, count_trailing_zeros(lanemask())));
}
inline void print_(const vec3f &v)
{
print("[%] = (%, %, %)\n",
count_trailing_zeros(lanemask()),
extract(v.x, count_trailing_zeros(lanemask())),
extract(v.y, count_trailing_zeros(lanemask())),
extract(v.z, count_trailing_zeros(lanemask())));
}
inline void print_(const vec4i &v)
{
print("[%] = (%, %, %, %)\n",
count_trailing_zeros(lanemask()),
extract(v.x, count_trailing_zeros(lanemask())),
extract(v.y, count_trailing_zeros(lanemask())),
extract(v.z, count_trailing_zeros(lanemask())),
extract(v.w, count_trailing_zeros(lanemask())));
}
inline void print_(const vec4f &v)
{
print("[%] = (%, %, %, %)\n",
count_trailing_zeros(lanemask()),
extract(v.x, count_trailing_zeros(lanemask())),
extract(v.y, count_trailing_zeros(lanemask())),
extract(v.z, count_trailing_zeros(lanemask())),
extract(v.w, count_trailing_zeros(lanemask())));
}
#define PRINT(x) \
{ \
print(#x); \
print_(x); \
}
#define PRINT_STR(s) print(#s " = %\n", s);
#endif
#ifndef OSPRAY_TARGET_SYCL

Some files were not shown because too many files have changed in this diff Show More