mirror of
https://github.com/NVIDIA/cuda-samples.git
synced 2026-10-23 21:28:17 +08:00
add and update samples for CUDA 11.5
This commit is contained in:
18
Samples/particles/.vscode/c_cpp_properties.json
vendored
Normal file
18
Samples/particles/.vscode/c_cpp_properties.json
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Linux",
|
||||
"includePath": [
|
||||
"${workspaceFolder}/**",
|
||||
"${workspaceFolder}/../../Common"
|
||||
],
|
||||
"defines": [],
|
||||
"compilerPath": "/usr/local/cuda/bin/nvcc",
|
||||
"cStandard": "gnu17",
|
||||
"cppStandard": "gnu++14",
|
||||
"intelliSenseMode": "linux-gcc-x64",
|
||||
"configurationProvider": "ms-vscode.makefile-tools"
|
||||
}
|
||||
],
|
||||
"version": 4
|
||||
}
|
||||
7
Samples/particles/.vscode/extensions.json
vendored
Normal file
7
Samples/particles/.vscode/extensions.json
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"recommendations": [
|
||||
"nvidia.nsight-vscode-edition",
|
||||
"ms-vscode.cpptools",
|
||||
"ms-vscode.makefile-tools"
|
||||
]
|
||||
}
|
||||
10
Samples/particles/.vscode/launch.json
vendored
Normal file
10
Samples/particles/.vscode/launch.json
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"configurations": [
|
||||
{
|
||||
"name": "CUDA C++: Launch",
|
||||
"type": "cuda-gdb",
|
||||
"request": "launch",
|
||||
"program": "${workspaceFolder}/particles"
|
||||
}
|
||||
]
|
||||
}
|
||||
15
Samples/particles/.vscode/tasks.json
vendored
Normal file
15
Samples/particles/.vscode/tasks.json
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"version": "2.0.0",
|
||||
"tasks": [
|
||||
{
|
||||
"label": "sample",
|
||||
"type": "shell",
|
||||
"command": "make dbg=1",
|
||||
"problemMatcher": ["$nvcc"],
|
||||
"group": {
|
||||
"kind": "build",
|
||||
"isDefault": true
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
394
Samples/particles/Makefile
Normal file
394
Samples/particles/Makefile
Normal file
@@ -0,0 +1,394 @@
|
||||
################################################################################
|
||||
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions
|
||||
# are met:
|
||||
# * Redistributions of source code must retain the above copyright
|
||||
# notice, this list of conditions and the following disclaimer.
|
||||
# * Redistributions in binary form must reproduce the above copyright
|
||||
# notice, this list of conditions and the following disclaimer in the
|
||||
# documentation and/or other materials provided with the distribution.
|
||||
# * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
# contributors may be used to endorse or promote products derived
|
||||
# from this software without specific prior written permission.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
#
|
||||
################################################################################
|
||||
#
|
||||
# Makefile project only supported on Mac OS X and Linux Platforms)
|
||||
#
|
||||
################################################################################
|
||||
|
||||
# Location of the CUDA Toolkit
|
||||
CUDA_PATH ?= /usr/local/cuda
|
||||
|
||||
##############################
|
||||
# start deprecated interface #
|
||||
##############################
|
||||
ifeq ($(x86_64),1)
|
||||
$(info WARNING - x86_64 variable has been deprecated)
|
||||
$(info WARNING - please use TARGET_ARCH=x86_64 instead)
|
||||
TARGET_ARCH ?= x86_64
|
||||
endif
|
||||
ifeq ($(ARMv7),1)
|
||||
$(info WARNING - ARMv7 variable has been deprecated)
|
||||
$(info WARNING - please use TARGET_ARCH=armv7l instead)
|
||||
TARGET_ARCH ?= armv7l
|
||||
endif
|
||||
ifeq ($(aarch64),1)
|
||||
$(info WARNING - aarch64 variable has been deprecated)
|
||||
$(info WARNING - please use TARGET_ARCH=aarch64 instead)
|
||||
TARGET_ARCH ?= aarch64
|
||||
endif
|
||||
ifeq ($(ppc64le),1)
|
||||
$(info WARNING - ppc64le variable has been deprecated)
|
||||
$(info WARNING - please use TARGET_ARCH=ppc64le instead)
|
||||
TARGET_ARCH ?= ppc64le
|
||||
endif
|
||||
ifneq ($(GCC),)
|
||||
$(info WARNING - GCC variable has been deprecated)
|
||||
$(info WARNING - please use HOST_COMPILER=$(GCC) instead)
|
||||
HOST_COMPILER ?= $(GCC)
|
||||
endif
|
||||
ifneq ($(abi),)
|
||||
$(error ERROR - abi variable has been removed)
|
||||
endif
|
||||
############################
|
||||
# end deprecated interface #
|
||||
############################
|
||||
|
||||
# architecture
|
||||
HOST_ARCH := $(shell uname -m)
|
||||
TARGET_ARCH ?= $(HOST_ARCH)
|
||||
ifneq (,$(filter $(TARGET_ARCH),x86_64 aarch64 sbsa ppc64le armv7l))
|
||||
ifneq ($(TARGET_ARCH),$(HOST_ARCH))
|
||||
ifneq (,$(filter $(TARGET_ARCH),x86_64 aarch64 sbsa ppc64le))
|
||||
TARGET_SIZE := 64
|
||||
else ifneq (,$(filter $(TARGET_ARCH),armv7l))
|
||||
TARGET_SIZE := 32
|
||||
endif
|
||||
else
|
||||
TARGET_SIZE := $(shell getconf LONG_BIT)
|
||||
endif
|
||||
else
|
||||
$(error ERROR - unsupported value $(TARGET_ARCH) for TARGET_ARCH!)
|
||||
endif
|
||||
|
||||
# sbsa and aarch64 systems look similar. Need to differentiate them at host level for now.
|
||||
ifeq ($(HOST_ARCH),aarch64)
|
||||
ifeq ($(CUDA_PATH)/targets/sbsa-linux,$(shell ls -1d $(CUDA_PATH)/targets/sbsa-linux 2>/dev/null))
|
||||
HOST_ARCH := sbsa
|
||||
TARGET_ARCH := sbsa
|
||||
endif
|
||||
endif
|
||||
|
||||
ifneq ($(TARGET_ARCH),$(HOST_ARCH))
|
||||
ifeq (,$(filter $(HOST_ARCH)-$(TARGET_ARCH),aarch64-armv7l x86_64-armv7l x86_64-aarch64 x86_64-sbsa x86_64-ppc64le))
|
||||
$(error ERROR - cross compiling from $(HOST_ARCH) to $(TARGET_ARCH) is not supported!)
|
||||
endif
|
||||
endif
|
||||
|
||||
# When on native aarch64 system with userspace of 32-bit, change TARGET_ARCH to armv7l
|
||||
ifeq ($(HOST_ARCH)-$(TARGET_ARCH)-$(TARGET_SIZE),aarch64-aarch64-32)
|
||||
TARGET_ARCH = armv7l
|
||||
endif
|
||||
|
||||
# operating system
|
||||
HOST_OS := $(shell uname -s 2>/dev/null | tr "[:upper:]" "[:lower:]")
|
||||
TARGET_OS ?= $(HOST_OS)
|
||||
ifeq (,$(filter $(TARGET_OS),linux darwin qnx android))
|
||||
$(error ERROR - unsupported value $(TARGET_OS) for TARGET_OS!)
|
||||
endif
|
||||
|
||||
# host compiler
|
||||
ifeq ($(TARGET_OS),darwin)
|
||||
ifeq ($(shell expr `xcodebuild -version | grep -i xcode | awk '{print $$2}' | cut -d'.' -f1` \>= 5),1)
|
||||
HOST_COMPILER ?= clang++
|
||||
endif
|
||||
else ifneq ($(TARGET_ARCH),$(HOST_ARCH))
|
||||
ifeq ($(HOST_ARCH)-$(TARGET_ARCH),x86_64-armv7l)
|
||||
ifeq ($(TARGET_OS),linux)
|
||||
HOST_COMPILER ?= arm-linux-gnueabihf-g++
|
||||
else ifeq ($(TARGET_OS),qnx)
|
||||
ifeq ($(QNX_HOST),)
|
||||
$(error ERROR - QNX_HOST must be passed to the QNX host toolchain)
|
||||
endif
|
||||
ifeq ($(QNX_TARGET),)
|
||||
$(error ERROR - QNX_TARGET must be passed to the QNX target toolchain)
|
||||
endif
|
||||
export QNX_HOST
|
||||
export QNX_TARGET
|
||||
HOST_COMPILER ?= $(QNX_HOST)/usr/bin/arm-unknown-nto-qnx6.6.0eabi-g++
|
||||
else ifeq ($(TARGET_OS),android)
|
||||
HOST_COMPILER ?= arm-linux-androideabi-g++
|
||||
endif
|
||||
else ifeq ($(TARGET_ARCH),aarch64)
|
||||
ifeq ($(TARGET_OS), linux)
|
||||
HOST_COMPILER ?= aarch64-linux-gnu-g++
|
||||
else ifeq ($(TARGET_OS),qnx)
|
||||
ifeq ($(QNX_HOST),)
|
||||
$(error ERROR - QNX_HOST must be passed to the QNX host toolchain)
|
||||
endif
|
||||
ifeq ($(QNX_TARGET),)
|
||||
$(error ERROR - QNX_TARGET must be passed to the QNX target toolchain)
|
||||
endif
|
||||
export QNX_HOST
|
||||
export QNX_TARGET
|
||||
HOST_COMPILER ?= $(QNX_HOST)/usr/bin/q++
|
||||
else ifeq ($(TARGET_OS), android)
|
||||
HOST_COMPILER ?= aarch64-linux-android-clang++
|
||||
endif
|
||||
else ifeq ($(TARGET_ARCH),sbsa)
|
||||
HOST_COMPILER ?= aarch64-linux-gnu-g++
|
||||
else ifeq ($(TARGET_ARCH),ppc64le)
|
||||
HOST_COMPILER ?= powerpc64le-linux-gnu-g++
|
||||
endif
|
||||
endif
|
||||
HOST_COMPILER ?= g++
|
||||
NVCC := $(CUDA_PATH)/bin/nvcc -ccbin $(HOST_COMPILER)
|
||||
|
||||
# internal flags
|
||||
NVCCFLAGS := -m${TARGET_SIZE}
|
||||
CCFLAGS :=
|
||||
LDFLAGS :=
|
||||
|
||||
# build flags
|
||||
ifeq ($(TARGET_OS),darwin)
|
||||
LDFLAGS += -rpath $(CUDA_PATH)/lib
|
||||
CCFLAGS += -arch $(HOST_ARCH)
|
||||
else ifeq ($(HOST_ARCH)-$(TARGET_ARCH)-$(TARGET_OS),x86_64-armv7l-linux)
|
||||
LDFLAGS += --dynamic-linker=/lib/ld-linux-armhf.so.3
|
||||
CCFLAGS += -mfloat-abi=hard
|
||||
else ifeq ($(TARGET_OS),android)
|
||||
LDFLAGS += -pie
|
||||
CCFLAGS += -fpie -fpic -fexceptions
|
||||
endif
|
||||
|
||||
ifneq ($(TARGET_ARCH),$(HOST_ARCH))
|
||||
ifeq ($(TARGET_ARCH)-$(TARGET_OS),armv7l-linux)
|
||||
ifneq ($(TARGET_FS),)
|
||||
GCCVERSIONLTEQ46 := $(shell expr `$(HOST_COMPILER) -dumpversion` \<= 4.6)
|
||||
ifeq ($(GCCVERSIONLTEQ46),1)
|
||||
CCFLAGS += --sysroot=$(TARGET_FS)
|
||||
endif
|
||||
LDFLAGS += --sysroot=$(TARGET_FS)
|
||||
LDFLAGS += -rpath-link=$(TARGET_FS)/lib
|
||||
LDFLAGS += -rpath-link=$(TARGET_FS)/usr/lib
|
||||
LDFLAGS += -rpath-link=$(TARGET_FS)/usr/lib/arm-linux-gnueabihf
|
||||
endif
|
||||
endif
|
||||
ifeq ($(TARGET_ARCH)-$(TARGET_OS),aarch64-linux)
|
||||
ifneq ($(TARGET_FS),)
|
||||
GCCVERSIONLTEQ46 := $(shell expr `$(HOST_COMPILER) -dumpversion` \<= 4.6)
|
||||
ifeq ($(GCCVERSIONLTEQ46),1)
|
||||
CCFLAGS += --sysroot=$(TARGET_FS)
|
||||
endif
|
||||
LDFLAGS += --sysroot=$(TARGET_FS)
|
||||
LDFLAGS += -rpath-link=$(TARGET_FS)/lib -L$(TARGET_FS)/lib
|
||||
LDFLAGS += -rpath-link=$(TARGET_FS)/lib/aarch64-linux-gnu -L$(TARGET_FS)/lib/aarch64-linux-gnu
|
||||
LDFLAGS += -rpath-link=$(TARGET_FS)/usr/lib -L$(TARGET_FS)/usr/lib
|
||||
LDFLAGS += -rpath-link=$(TARGET_FS)/usr/lib/aarch64-linux-gnu -L$(TARGET_FS)/usr/lib/aarch64-linux-gnu
|
||||
LDFLAGS += --unresolved-symbols=ignore-in-shared-libs
|
||||
CCFLAGS += -isystem=$(TARGET_FS)/usr/include -I$(TARGET_FS)/usr/include -I$(TARGET_FS)/usr/include/libdrm
|
||||
CCFLAGS += -isystem=$(TARGET_FS)/usr/include/aarch64-linux-gnu -I$(TARGET_FS)/usr/include/aarch64-linux-gnu
|
||||
endif
|
||||
endif
|
||||
ifeq ($(TARGET_ARCH)-$(TARGET_OS),aarch64-qnx)
|
||||
NVCCFLAGS += --qpp-config 5.4.0,gcc_ntoaarch64le
|
||||
CCFLAGS += -DWIN_INTERFACE_CUSTOM -I/usr/include/aarch64-qnx-gnu
|
||||
LDFLAGS += -lsocket
|
||||
LDFLAGS += -L/usr/lib/aarch64-qnx-gnu
|
||||
CCFLAGS += "-Wl\,-rpath-link\,/usr/lib/aarch64-qnx-gnu"
|
||||
ifdef TARGET_OVERRIDE
|
||||
LDFLAGS += -lslog2
|
||||
endif
|
||||
|
||||
ifneq ($(TARGET_FS),)
|
||||
LDFLAGS += -L$(TARGET_FS)/usr/lib
|
||||
CCFLAGS += "-Wl\,-rpath-link\,$(TARGET_FS)/usr/lib"
|
||||
LDFLAGS += -L$(TARGET_FS)/usr/libnvidia
|
||||
CCFLAGS += "-Wl\,-rpath-link\,$(TARGET_FS)/usr/libnvidia"
|
||||
CCFLAGS += -I$(TARGET_FS)/../include
|
||||
endif
|
||||
endif
|
||||
endif
|
||||
|
||||
ifdef TARGET_OVERRIDE # cuda toolkit targets override
|
||||
NVCCFLAGS += -target-dir $(TARGET_OVERRIDE)
|
||||
endif
|
||||
|
||||
# Install directory of different arch
|
||||
CUDA_INSTALL_TARGET_DIR :=
|
||||
ifeq ($(TARGET_ARCH)-$(TARGET_OS),armv7l-linux)
|
||||
CUDA_INSTALL_TARGET_DIR = targets/armv7-linux-gnueabihf/
|
||||
else ifeq ($(TARGET_ARCH)-$(TARGET_OS),aarch64-linux)
|
||||
CUDA_INSTALL_TARGET_DIR = targets/aarch64-linux/
|
||||
else ifeq ($(TARGET_ARCH)-$(TARGET_OS),sbsa-linux)
|
||||
CUDA_INSTALL_TARGET_DIR = targets/sbsa-linux/
|
||||
else ifeq ($(TARGET_ARCH)-$(TARGET_OS),armv7l-android)
|
||||
CUDA_INSTALL_TARGET_DIR = targets/armv7-linux-androideabi/
|
||||
else ifeq ($(TARGET_ARCH)-$(TARGET_OS),aarch64-android)
|
||||
CUDA_INSTALL_TARGET_DIR = targets/aarch64-linux-androideabi/
|
||||
else ifeq ($(TARGET_ARCH)-$(TARGET_OS),armv7l-qnx)
|
||||
CUDA_INSTALL_TARGET_DIR = targets/ARMv7-linux-QNX/
|
||||
else ifeq ($(TARGET_ARCH)-$(TARGET_OS),aarch64-qnx)
|
||||
CUDA_INSTALL_TARGET_DIR = targets/aarch64-qnx/
|
||||
else ifeq ($(TARGET_ARCH),ppc64le)
|
||||
CUDA_INSTALL_TARGET_DIR = targets/ppc64le-linux/
|
||||
endif
|
||||
|
||||
# Debug build flags
|
||||
ifeq ($(dbg),1)
|
||||
NVCCFLAGS += -g -G
|
||||
BUILD_TYPE := debug
|
||||
else
|
||||
BUILD_TYPE := release
|
||||
endif
|
||||
|
||||
ALL_CCFLAGS :=
|
||||
ALL_CCFLAGS += $(NVCCFLAGS)
|
||||
ALL_CCFLAGS += $(EXTRA_NVCCFLAGS)
|
||||
ALL_CCFLAGS += $(addprefix -Xcompiler ,$(CCFLAGS))
|
||||
ALL_CCFLAGS += $(addprefix -Xcompiler ,$(EXTRA_CCFLAGS))
|
||||
|
||||
SAMPLE_ENABLED := 1
|
||||
|
||||
# This sample is not supported on QNX
|
||||
ifeq ($(TARGET_OS),qnx)
|
||||
$(info >>> WARNING - particles is not supported on QNX - waiving sample <<<)
|
||||
SAMPLE_ENABLED := 0
|
||||
endif
|
||||
|
||||
ALL_LDFLAGS :=
|
||||
ALL_LDFLAGS += $(ALL_CCFLAGS)
|
||||
ALL_LDFLAGS += $(addprefix -Xlinker ,$(LDFLAGS))
|
||||
ALL_LDFLAGS += $(addprefix -Xlinker ,$(EXTRA_LDFLAGS))
|
||||
|
||||
# Common includes and paths for CUDA
|
||||
INCLUDES := -I../../Common
|
||||
LIBRARIES :=
|
||||
|
||||
################################################################################
|
||||
|
||||
# Makefile include to help find GL Libraries
|
||||
include ./findgllib.mk
|
||||
|
||||
# OpenGL specific libraries
|
||||
ifeq ($(TARGET_OS),darwin)
|
||||
# Mac OSX specific libraries and paths to include
|
||||
LIBRARIES += -L/System/Library/Frameworks/OpenGL.framework/Libraries
|
||||
LIBRARIES += -lGL -lGLU
|
||||
ALL_LDFLAGS += -Xlinker -framework -Xlinker GLUT
|
||||
else
|
||||
LIBRARIES += $(GLLINK)
|
||||
LIBRARIES += -lGL -lGLU -lglut
|
||||
endif
|
||||
|
||||
#Detect if installed version of GCC supports required C++11
|
||||
ifeq ($(TARGET_OS),linux)
|
||||
empty :=
|
||||
space := $(empty) $(empty)
|
||||
GCCVERSIONSTRING := $(shell expr `$(HOST_COMPILER) -dumpversion`)
|
||||
#Create version number without "."
|
||||
GCCVERSION := $(shell expr `echo $(GCCVERSIONSTRING)` | cut -f1 -d.)
|
||||
GCCVERSION += $(shell expr `echo $(GCCVERSIONSTRING)` | cut -f2 -d.)
|
||||
GCCVERSION += $(shell expr `echo $(GCCVERSIONSTRING)` | cut -f3 -d.)
|
||||
# Make sure the version number has at least 3 decimals
|
||||
GCCVERSION += 00
|
||||
# Remove spaces from the version number
|
||||
GCCVERSION := $(subst $(space),$(empty),$(GCCVERSION))
|
||||
#$(warning $(GCCVERSION))
|
||||
|
||||
IS_MIN_VERSION := $(shell expr `echo $(GCCVERSION)` \>= 51000)
|
||||
|
||||
ifeq ($(IS_MIN_VERSION), 1)
|
||||
$(info >>> GCC Version is greater or equal to 5.1.0 <<<)
|
||||
else
|
||||
$(info >>> Waiving build. Minimum GCC version required is 5.1.0<<<)
|
||||
SAMPLE_ENABLED := 0
|
||||
endif
|
||||
endif
|
||||
|
||||
# Gencode arguments
|
||||
ifeq ($(TARGET_ARCH),$(filter $(TARGET_ARCH),armv7l aarch64))
|
||||
SMS ?= 35 37 50 52 60 61 70 72 75 80 86
|
||||
else
|
||||
SMS ?= 35 37 50 52 60 61 70 75 80 86
|
||||
endif
|
||||
|
||||
ifeq ($(SMS),)
|
||||
$(info >>> WARNING - no SM architectures have been specified - waiving sample <<<)
|
||||
SAMPLE_ENABLED := 0
|
||||
endif
|
||||
|
||||
ifeq ($(GENCODE_FLAGS),)
|
||||
# Generate SASS code for each SM architecture listed in $(SMS)
|
||||
$(foreach sm,$(SMS),$(eval GENCODE_FLAGS += -gencode arch=compute_$(sm),code=sm_$(sm)))
|
||||
|
||||
# Generate PTX code from the highest SM architecture in $(SMS) to guarantee forward-compatibility
|
||||
HIGHEST_SM := $(lastword $(sort $(SMS)))
|
||||
ifneq ($(HIGHEST_SM),)
|
||||
GENCODE_FLAGS += -gencode arch=compute_$(HIGHEST_SM),code=compute_$(HIGHEST_SM)
|
||||
endif
|
||||
endif
|
||||
|
||||
ALL_CCFLAGS += --std=c++14 --threads 0
|
||||
|
||||
ifeq ($(SAMPLE_ENABLED),0)
|
||||
EXEC ?= @echo "[@]"
|
||||
endif
|
||||
|
||||
################################################################################
|
||||
|
||||
# Target rules
|
||||
all: build
|
||||
|
||||
build: particles
|
||||
|
||||
check.deps:
|
||||
ifeq ($(SAMPLE_ENABLED),0)
|
||||
@echo "Sample will be waived due to the above missing dependencies"
|
||||
else
|
||||
@echo "Sample is ready - all dependencies have been met"
|
||||
endif
|
||||
|
||||
particleSystem.o:particleSystem.cpp
|
||||
$(EXEC) $(NVCC) $(INCLUDES) $(ALL_CCFLAGS) $(GENCODE_FLAGS) -o $@ -c $<
|
||||
|
||||
particleSystem_cuda.o:particleSystem_cuda.cu
|
||||
$(EXEC) $(NVCC) $(INCLUDES) $(ALL_CCFLAGS) $(GENCODE_FLAGS) -o $@ -c $<
|
||||
|
||||
particles.o:particles.cpp
|
||||
$(EXEC) $(NVCC) $(INCLUDES) $(ALL_CCFLAGS) $(GENCODE_FLAGS) -o $@ -c $<
|
||||
|
||||
render_particles.o:render_particles.cpp
|
||||
$(EXEC) $(NVCC) $(INCLUDES) $(ALL_CCFLAGS) $(GENCODE_FLAGS) -o $@ -c $<
|
||||
|
||||
shaders.o:shaders.cpp
|
||||
$(EXEC) $(NVCC) $(INCLUDES) $(ALL_CCFLAGS) $(GENCODE_FLAGS) -o $@ -c $<
|
||||
|
||||
particles: particleSystem.o particleSystem_cuda.o particles.o render_particles.o shaders.o
|
||||
$(EXEC) $(NVCC) $(ALL_LDFLAGS) $(GENCODE_FLAGS) -o $@ $+ $(LIBRARIES)
|
||||
$(EXEC) mkdir -p ../../bin/$(TARGET_ARCH)/$(TARGET_OS)/$(BUILD_TYPE)
|
||||
$(EXEC) cp $@ ../../bin/$(TARGET_ARCH)/$(TARGET_OS)/$(BUILD_TYPE)
|
||||
|
||||
run: build
|
||||
$(EXEC) ./particles
|
||||
|
||||
clean:
|
||||
rm -f particles particleSystem.o particleSystem_cuda.o particles.o render_particles.o shaders.o
|
||||
rm -rf ../../bin/$(TARGET_ARCH)/$(TARGET_OS)/$(BUILD_TYPE)/particles
|
||||
|
||||
clobber: clean
|
||||
104
Samples/particles/NsightEclipse.xml
Normal file
104
Samples/particles/NsightEclipse.xml
Normal file
@@ -0,0 +1,104 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE entry SYSTEM "SamplesInfo.dtd">
|
||||
<entry>
|
||||
<name>particles</name>
|
||||
<cflags>
|
||||
<flag>--std=c++14</flag>
|
||||
</cflags>
|
||||
<cuda_api_list>
|
||||
<toolkit>cudaGraphicsMapResources</toolkit>
|
||||
<toolkit>cudaGraphicsUnmapResources</toolkit>
|
||||
<toolkit>cudaGraphicsResourceGetMappedPointer</toolkit>
|
||||
<toolkit>cudaGraphicsRegisterResource</toolkit>
|
||||
<toolkit>cudaGraphicsGLRegisterBuffer</toolkit>
|
||||
<toolkit>cudaGraphicsUnregisterResource</toolkit>
|
||||
</cuda_api_list>
|
||||
<description><![CDATA[This sample uses CUDA to simulate and visualize a large set of particles and their physical interaction. Adding "-particles=<N>" to the command line will allow users to set # of particles for simulation. This example implements a uniform grid data structure using either atomic operations or a fast radix sort from the Thrust library]]></description>
|
||||
<devicecompilation>whole</devicecompilation>
|
||||
<files>
|
||||
<file>data\ref_particles.ppm</file>
|
||||
<file>data\ref_particles.bin</file>
|
||||
</files>
|
||||
<includepaths>
|
||||
<path>./</path>
|
||||
<path>../</path>
|
||||
<path>../../Common</path>
|
||||
</includepaths>
|
||||
<keyconcepts>
|
||||
<concept level="advanced">Graphics Interop</concept>
|
||||
<concept level="advanced">Data Parallel Algorithms</concept>
|
||||
<concept level="advanced">Physically-Based Simulation</concept>
|
||||
<concept level="advanced">Performance Strategies</concept>
|
||||
</keyconcepts>
|
||||
<keywords>
|
||||
<keyword>CUDA</keyword>
|
||||
<keyword>GPGPU</keyword>
|
||||
<keyword>OpenGL</keyword>
|
||||
<keyword>openGL</keyword>
|
||||
<keyword>CPP14</keyword>
|
||||
</keywords>
|
||||
<libraries>
|
||||
<library>GLU</library>
|
||||
<library>GL</library>
|
||||
<library framework="true" os="macosx">GLUT</library>
|
||||
<library os="linux">GLEW</library>
|
||||
<library os="linux">glut</library>
|
||||
<library os="linux">X11</library>
|
||||
</libraries>
|
||||
<librarypaths>
|
||||
<path arch="x86_64" os="linux">../../common/lib/linux/x86_64</path>
|
||||
<path arch="armv7l" os="linux">../../common/lib/linux/armv7l</path>
|
||||
<path os="macosx">../../common/lib/darwin</path>
|
||||
</librarypaths>
|
||||
<nsight_eclipse>true</nsight_eclipse>
|
||||
<primary_file>particles.cpp</primary_file>
|
||||
<qatests>
|
||||
<qatest>-file=ref_particles.bin</qatest>
|
||||
</qatests>
|
||||
<required_dependencies>
|
||||
<dependency>X11</dependency>
|
||||
<dependency>GL</dependency>
|
||||
</required_dependencies>
|
||||
<scopes>
|
||||
<scope>2:Graphics Interop</scope>
|
||||
<scope>3:Physically-Based Simulation</scope>
|
||||
</scopes>
|
||||
<sm-arch>sm35</sm-arch>
|
||||
<sm-arch>sm37</sm-arch>
|
||||
<sm-arch>sm50</sm-arch>
|
||||
<sm-arch>sm52</sm-arch>
|
||||
<sm-arch>sm60</sm-arch>
|
||||
<sm-arch>sm61</sm-arch>
|
||||
<sm-arch>sm70</sm-arch>
|
||||
<sm-arch>sm72</sm-arch>
|
||||
<sm-arch>sm75</sm-arch>
|
||||
<sm-arch>sm80</sm-arch>
|
||||
<sm-arch>sm86</sm-arch>
|
||||
<sources>
|
||||
<extraheader>..\..\Common\param.h</extraheader>
|
||||
<extraheader>..\..\Common\paramgl.h</extraheader>
|
||||
<extraheader>..\..\Common\rendercheck_gl.h</extraheader>
|
||||
</sources>
|
||||
<supported_envs>
|
||||
<env>
|
||||
<arch>x86_64</arch>
|
||||
<platform>linux</platform>
|
||||
</env>
|
||||
<env>
|
||||
<platform>windows7</platform>
|
||||
</env>
|
||||
<env>
|
||||
<arch>x86_64</arch>
|
||||
<platform>macosx</platform>
|
||||
</env>
|
||||
<env>
|
||||
<arch>arm</arch>
|
||||
</env>
|
||||
</supported_envs>
|
||||
<supported_sm_architectures>
|
||||
<include>all</include>
|
||||
</supported_sm_architectures>
|
||||
<title>Particles</title>
|
||||
<type>exe</type>
|
||||
<whitepaper>doc\particles.pdf</whitepaper>
|
||||
</entry>
|
||||
74
Samples/particles/README.md
Normal file
74
Samples/particles/README.md
Normal file
@@ -0,0 +1,74 @@
|
||||
# particles - Particles
|
||||
|
||||
## Description
|
||||
|
||||
This sample uses CUDA to simulate and visualize a large set of particles and their physical interaction. Adding "-particles=<N>" to the command line will allow users to set # of particles for simulation. This example implements a uniform grid data structure using either atomic operations or a fast radix sort from the Thrust library
|
||||
|
||||
## Key Concepts
|
||||
|
||||
Graphics Interop, Data Parallel Algorithms, Physically-Based Simulation, Performance Strategies
|
||||
|
||||
## Supported SM Architectures
|
||||
|
||||
[SM 3.5 ](https://developer.nvidia.com/cuda-gpus) [SM 3.7 ](https://developer.nvidia.com/cuda-gpus) [SM 5.0 ](https://developer.nvidia.com/cuda-gpus) [SM 5.2 ](https://developer.nvidia.com/cuda-gpus) [SM 6.0 ](https://developer.nvidia.com/cuda-gpus) [SM 6.1 ](https://developer.nvidia.com/cuda-gpus) [SM 7.0 ](https://developer.nvidia.com/cuda-gpus) [SM 7.2 ](https://developer.nvidia.com/cuda-gpus) [SM 7.5 ](https://developer.nvidia.com/cuda-gpus) [SM 8.0 ](https://developer.nvidia.com/cuda-gpus) [SM 8.6 ](https://developer.nvidia.com/cuda-gpus)
|
||||
|
||||
## Supported OSes
|
||||
|
||||
Linux, Windows
|
||||
|
||||
## Supported CPU Architecture
|
||||
|
||||
x86_64, armv7l
|
||||
|
||||
## CUDA APIs involved
|
||||
|
||||
### [CUDA Runtime API](http://docs.nvidia.com/cuda/cuda-runtime-api/index.html)
|
||||
cudaGraphicsMapResources, cudaGraphicsUnmapResources, cudaGraphicsResourceGetMappedPointer, cudaGraphicsRegisterResource, cudaGraphicsGLRegisterBuffer, cudaGraphicsUnregisterResource
|
||||
|
||||
## Dependencies needed to build/run
|
||||
[X11](../../README.md#x11), [GL](../../README.md#gl)
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Download and install the [CUDA Toolkit 11.5](https://developer.nvidia.com/cuda-downloads) for your corresponding platform.
|
||||
Make sure the dependencies mentioned in [Dependencies]() section above are installed.
|
||||
|
||||
## Build and Run
|
||||
|
||||
### Windows
|
||||
The Windows samples are built using the Visual Studio IDE. Solution files (.sln) are provided for each supported version of Visual Studio, using the format:
|
||||
```
|
||||
*_vs<version>.sln - for Visual Studio <version>
|
||||
```
|
||||
Each individual sample has its own set of solution files in its directory:
|
||||
|
||||
To build/examine all the samples at once, the complete solution files should be used. To build/examine a single sample, the individual sample solution files should be used.
|
||||
> **Note:** Some samples require that the Microsoft DirectX SDK (June 2010 or newer) be installed and that the VC++ directory paths are properly set up (**Tools > Options...**). Check DirectX Dependencies section for details."
|
||||
|
||||
### Linux
|
||||
The Linux samples are built using makefiles. To use the makefiles, change the current directory to the sample directory you wish to build, and run make:
|
||||
```
|
||||
$ cd <sample_dir>
|
||||
$ make
|
||||
```
|
||||
The samples makefiles can take advantage of certain options:
|
||||
* **TARGET_ARCH=<arch>** - cross-compile targeting a specific architecture. Allowed architectures are x86_64, armv7l.
|
||||
By default, TARGET_ARCH is set to HOST_ARCH. On a x86_64 machine, not setting TARGET_ARCH is the equivalent of setting TARGET_ARCH=x86_64.<br/>
|
||||
`$ make TARGET_ARCH=x86_64` <br/> `$ make TARGET_ARCH=armv7l` <br/>
|
||||
See [here](http://docs.nvidia.com/cuda/cuda-samples/index.html#cross-samples) for more details.
|
||||
* **dbg=1** - build with debug symbols
|
||||
```
|
||||
$ make dbg=1
|
||||
```
|
||||
* **SMS="A B ..."** - override the SM architectures for which the sample will be built, where `"A B ..."` is a space-delimited list of SM architectures. For example, to generate SASS for SM 50 and SM 60, use `SMS="50 60"`.
|
||||
```
|
||||
$ make SMS="50 60"
|
||||
```
|
||||
|
||||
* **HOST_COMPILER=<host_compiler>** - override the default g++ host compiler. See the [Linux Installation Guide](http://docs.nvidia.com/cuda/cuda-installation-guide-linux/index.html#system-requirements) for a list of supported host compilers.
|
||||
```
|
||||
$ make HOST_COMPILER=g++
|
||||
```
|
||||
|
||||
## References (for more details)
|
||||
|
||||
BIN
Samples/particles/data/ref_particles.bin
Normal file
BIN
Samples/particles/data/ref_particles.bin
Normal file
Binary file not shown.
BIN
Samples/particles/doc/particles.doc
Normal file
BIN
Samples/particles/doc/particles.doc
Normal file
Binary file not shown.
BIN
Samples/particles/doc/particles.pdf
Normal file
BIN
Samples/particles/doc/particles.pdf
Normal file
Binary file not shown.
BIN
Samples/particles/doc/screenshot_lg.png
Normal file
BIN
Samples/particles/doc/screenshot_lg.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 136 KiB |
BIN
Samples/particles/doc/screenshot_md.png
Normal file
BIN
Samples/particles/doc/screenshot_md.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 51 KiB |
BIN
Samples/particles/doc/screenshot_sm.png
Normal file
BIN
Samples/particles/doc/screenshot_sm.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 17 KiB |
145
Samples/particles/findgllib.mk
Normal file
145
Samples/particles/findgllib.mk
Normal file
@@ -0,0 +1,145 @@
|
||||
################################################################################
|
||||
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions
|
||||
# are met:
|
||||
# * Redistributions of source code must retain the above copyright
|
||||
# notice, this list of conditions and the following disclaimer.
|
||||
# * Redistributions in binary form must reproduce the above copyright
|
||||
# notice, this list of conditions and the following disclaimer in the
|
||||
# documentation and/or other materials provided with the distribution.
|
||||
# * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
# contributors may be used to endorse or promote products derived
|
||||
# from this software without specific prior written permission.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
#
|
||||
################################################################################
|
||||
#
|
||||
# findgllib.mk is used to find the necessary GL Libraries for specific distributions
|
||||
# this is supported on Mac OSX and Linux Platforms
|
||||
#
|
||||
################################################################################
|
||||
|
||||
# Determine OS platform and unix distribution
|
||||
ifeq ("$(TARGET_OS)","linux")
|
||||
# first search lsb_release
|
||||
DISTRO := $(shell lsb_release -i -s 2>/dev/null | tr "[:upper:]" "[:lower:]")
|
||||
ifeq ("$(DISTRO)","")
|
||||
# second search and parse /etc/issue
|
||||
DISTRO := $(shell awk '{print $$1}' /etc/issue | tr -d "[:space:]" | sed -e "/^$$/d" | tr "[:upper:]" "[:lower:]")
|
||||
# ensure data from /etc/issue is valid
|
||||
ifeq (,$(filter $(DISTRO),ubuntu fedora red rhel centos suse))
|
||||
DISTRO :=
|
||||
endif
|
||||
ifeq ("$(DISTRO)","")
|
||||
# third, we can search in /etc/os-release or /etc/{distro}-release
|
||||
DISTRO := $(shell awk '/ID/' /etc/*-release | sed 's/ID=//' | grep -v "VERSION" | grep -v "ID" | grep -v "DISTRIB")
|
||||
endif
|
||||
endif
|
||||
endif
|
||||
|
||||
ifeq ("$(TARGET_OS)","linux")
|
||||
# $(info) >> findgllib.mk -> LINUX path <<<)
|
||||
# Each set of Linux Distros have different paths for where to find their OpenGL libraries reside
|
||||
UBUNTU = $(shell echo $(DISTRO) | grep -i ubuntu >/dev/null 2>&1; echo $$?)
|
||||
FEDORA = $(shell echo $(DISTRO) | grep -i fedora >/dev/null 2>&1; echo $$?)
|
||||
RHEL = $(shell echo $(DISTRO) | grep -i 'red\|rhel' >/dev/null 2>&1; echo $$?)
|
||||
CENTOS = $(shell echo $(DISTRO) | grep -i centos >/dev/null 2>&1; echo $$?)
|
||||
SUSE = $(shell echo $(DISTRO) | grep -i 'suse\|sles' >/dev/null 2>&1; echo $$?)
|
||||
ifeq ("$(UBUNTU)","0")
|
||||
ifeq ($(HOST_ARCH)-$(TARGET_ARCH),x86_64-armv7l)
|
||||
GLPATH := /usr/arm-linux-gnueabihf/lib
|
||||
GLLINK := -L/usr/arm-linux-gnueabihf/lib
|
||||
ifneq ($(TARGET_FS),)
|
||||
GLPATH += $(TARGET_FS)/usr/lib/arm-linux-gnueabihf
|
||||
GLLINK += -L$(TARGET_FS)/usr/lib/arm-linux-gnueabihf
|
||||
endif
|
||||
else ifeq ($(HOST_ARCH)-$(TARGET_ARCH),x86_64-aarch64)
|
||||
GLPATH := /usr/aarch64-linux-gnu/lib
|
||||
GLLINK := -L/usr/aarch64-linux-gnu/lib
|
||||
ifneq ($(TARGET_FS),)
|
||||
GLPATH += $(TARGET_FS)/usr/lib
|
||||
GLPATH += $(TARGET_FS)/usr/lib/aarch64-linux-gnu
|
||||
GLLINK += -L$(TARGET_FS)/usr/lib/aarch64-linux-gnu
|
||||
endif
|
||||
else ifeq ($(HOST_ARCH)-$(TARGET_ARCH),x86_64-ppc64le)
|
||||
GLPATH := /usr/powerpc64le-linux-gnu/lib
|
||||
GLLINK := -L/usr/powerpc64le-linux-gnu/lib
|
||||
else
|
||||
UBUNTU_PKG_NAME = $(shell which dpkg >/dev/null 2>&1 && dpkg -l 'nvidia-*' | grep '^ii' | awk '{print $$2}' | head -1)
|
||||
ifneq ("$(UBUNTU_PKG_NAME)","")
|
||||
GLPATH ?= /usr/lib/$(UBUNTU_PKG_NAME)
|
||||
GLLINK ?= -L/usr/lib/$(UBUNTU_PKG_NAME)
|
||||
endif
|
||||
|
||||
DFLT_PATH ?= /usr/lib
|
||||
endif
|
||||
endif
|
||||
ifeq ("$(SUSE)","0")
|
||||
GLPATH ?= /usr/X11R6/lib64
|
||||
GLLINK ?= -L/usr/X11R6/lib64
|
||||
DFLT_PATH ?= /usr/lib64
|
||||
endif
|
||||
ifeq ("$(FEDORA)","0")
|
||||
GLPATH ?= /usr/lib64/nvidia
|
||||
GLLINK ?= -L/usr/lib64/nvidia
|
||||
DFLT_PATH ?= /usr/lib64
|
||||
endif
|
||||
ifeq ("$(RHEL)","0")
|
||||
GLPATH ?= /usr/lib64/nvidia
|
||||
GLLINK ?= -L/usr/lib64/nvidia
|
||||
DFLT_PATH ?= /usr/lib64
|
||||
endif
|
||||
ifeq ("$(CENTOS)","0")
|
||||
GLPATH ?= /usr/lib64/nvidia
|
||||
GLLINK ?= -L/usr/lib64/nvidia
|
||||
DFLT_PATH ?= /usr/lib64
|
||||
endif
|
||||
|
||||
# find libGL, libGLU
|
||||
GLLIB := $(shell find -L $(GLPATH) $(DFLT_PATH) -name libGL.so -print 2>/dev/null)
|
||||
GLULIB := $(shell find -L $(GLPATH) $(DFLT_PATH) -name libGLU.so -print 2>/dev/null)
|
||||
|
||||
ifeq ("$(GLLIB)","")
|
||||
$(info >>> WARNING - libGL.so not found, refer to CUDA Getting Started Guide for how to find and install them. <<<)
|
||||
SAMPLE_ENABLED := 0
|
||||
endif
|
||||
ifeq ("$(GLULIB)","")
|
||||
$(info >>> WARNING - libGLU.so not found, refer to CUDA Getting Started Guide for how to find and install them. <<<)
|
||||
SAMPLE_ENABLED := 0
|
||||
endif
|
||||
|
||||
HEADER_SEARCH_PATH ?= $(TARGET_FS)/usr/include
|
||||
ifeq ($(HOST_ARCH)-$(TARGET_ARCH)-$(TARGET_OS),x86_64-armv7l-linux)
|
||||
HEADER_SEARCH_PATH += /usr/arm-linux-gnueabihf/include
|
||||
else ifeq ($(HOST_ARCH)-$(TARGET_ARCH)-$(TARGET_OS),x86_64-aarch64-linux)
|
||||
HEADER_SEARCH_PATH += /usr/aarch64-linux-gnu/include
|
||||
endif
|
||||
|
||||
GLHEADER := $(shell find -L $(HEADER_SEARCH_PATH) -name gl.h -print 2>/dev/null)
|
||||
GLUHEADER := $(shell find -L $(HEADER_SEARCH_PATH) -name glu.h -print 2>/dev/null)
|
||||
|
||||
ifeq ("$(GLHEADER)","")
|
||||
$(info >>> WARNING - gl.h not found, refer to CUDA Getting Started Guide for how to find and install them. <<<)
|
||||
SAMPLE_ENABLED := 0
|
||||
endif
|
||||
ifeq ("$(GLUHEADER)","")
|
||||
$(info >>> WARNING - glu.h not found, refer to CUDA Getting Started Guide for how to find and install them. <<<)
|
||||
SAMPLE_ENABLED := 0
|
||||
endif
|
||||
else
|
||||
# This would be the Mac OS X path if we had to do anything special
|
||||
endif
|
||||
|
||||
519
Samples/particles/particleSystem.cpp
Normal file
519
Samples/particles/particleSystem.cpp
Normal file
@@ -0,0 +1,519 @@
|
||||
/*
|
||||
* Copyright 1993-2015 NVIDIA Corporation. All rights reserved.
|
||||
*
|
||||
* Please refer to the NVIDIA end user license agreement (EULA) associated
|
||||
* with this source code for terms and conditions that govern your use of
|
||||
* this software. Any use, reproduction, disclosure, or distribution of
|
||||
* this software and related documentation outside the terms of the EULA
|
||||
* is strictly prohibited.
|
||||
*
|
||||
*/
|
||||
|
||||
// OpenGL Graphics includes
|
||||
#define HELPERGL_EXTERN_GL_FUNC_IMPLEMENTATION
|
||||
#include <helper_gl.h>
|
||||
|
||||
#include "particleSystem.h"
|
||||
#include "particleSystem.cuh"
|
||||
#include "particles_kernel.cuh"
|
||||
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
#include <helper_functions.h>
|
||||
#include <helper_cuda.h>
|
||||
|
||||
#include <assert.h>
|
||||
#include <math.h>
|
||||
#include <memory.h>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <algorithm>
|
||||
|
||||
#ifndef CUDART_PI_F
|
||||
#define CUDART_PI_F 3.141592654f
|
||||
#endif
|
||||
|
||||
ParticleSystem::ParticleSystem(uint numParticles, uint3 gridSize, bool bUseOpenGL) :
|
||||
m_bInitialized(false),
|
||||
m_bUseOpenGL(bUseOpenGL),
|
||||
m_numParticles(numParticles),
|
||||
m_hPos(0),
|
||||
m_hVel(0),
|
||||
m_dPos(0),
|
||||
m_dVel(0),
|
||||
m_gridSize(gridSize),
|
||||
m_timer(NULL),
|
||||
m_solverIterations(1)
|
||||
{
|
||||
m_numGridCells = m_gridSize.x*m_gridSize.y*m_gridSize.z;
|
||||
// float3 worldSize = make_float3(2.0f, 2.0f, 2.0f);
|
||||
|
||||
m_gridSortBits = 18; // increase this for larger grids
|
||||
|
||||
// set simulation parameters
|
||||
m_params.gridSize = m_gridSize;
|
||||
m_params.numCells = m_numGridCells;
|
||||
m_params.numBodies = m_numParticles;
|
||||
|
||||
m_params.particleRadius = 1.0f / 64.0f;
|
||||
m_params.colliderPos = make_float3(-1.2f, -0.8f, 0.8f);
|
||||
m_params.colliderRadius = 0.2f;
|
||||
|
||||
m_params.worldOrigin = make_float3(-1.0f, -1.0f, -1.0f);
|
||||
// m_params.cellSize = make_float3(worldSize.x / m_gridSize.x, worldSize.y / m_gridSize.y, worldSize.z / m_gridSize.z);
|
||||
float cellSize = m_params.particleRadius * 2.0f; // cell size equal to particle diameter
|
||||
m_params.cellSize = make_float3(cellSize, cellSize, cellSize);
|
||||
|
||||
m_params.spring = 0.5f;
|
||||
m_params.damping = 0.02f;
|
||||
m_params.shear = 0.1f;
|
||||
m_params.attraction = 0.0f;
|
||||
m_params.boundaryDamping = -0.5f;
|
||||
|
||||
m_params.gravity = make_float3(0.0f, -0.0003f, 0.0f);
|
||||
m_params.globalDamping = 1.0f;
|
||||
|
||||
_initialize(numParticles);
|
||||
}
|
||||
|
||||
ParticleSystem::~ParticleSystem()
|
||||
{
|
||||
_finalize();
|
||||
m_numParticles = 0;
|
||||
}
|
||||
|
||||
uint
|
||||
ParticleSystem::createVBO(uint size)
|
||||
{
|
||||
GLuint vbo;
|
||||
glGenBuffers(1, &vbo);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, vbo);
|
||||
glBufferData(GL_ARRAY_BUFFER, size, 0, GL_DYNAMIC_DRAW);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, 0);
|
||||
return vbo;
|
||||
}
|
||||
|
||||
inline float lerp(float a, float b, float t)
|
||||
{
|
||||
return a + t*(b-a);
|
||||
}
|
||||
|
||||
// create a color ramp
|
||||
void colorRamp(float t, float *r)
|
||||
{
|
||||
const int ncolors = 7;
|
||||
float c[ncolors][3] =
|
||||
{
|
||||
{ 1.0, 0.0, 0.0, },
|
||||
{ 1.0, 0.5, 0.0, },
|
||||
{ 1.0, 1.0, 0.0, },
|
||||
{ 0.0, 1.0, 0.0, },
|
||||
{ 0.0, 1.0, 1.0, },
|
||||
{ 0.0, 0.0, 1.0, },
|
||||
{ 1.0, 0.0, 1.0, },
|
||||
};
|
||||
t = t * (ncolors-1);
|
||||
int i = (int) t;
|
||||
float u = t - floorf(t);
|
||||
r[0] = lerp(c[i][0], c[i+1][0], u);
|
||||
r[1] = lerp(c[i][1], c[i+1][1], u);
|
||||
r[2] = lerp(c[i][2], c[i+1][2], u);
|
||||
}
|
||||
|
||||
void
|
||||
ParticleSystem::_initialize(int numParticles)
|
||||
{
|
||||
assert(!m_bInitialized);
|
||||
|
||||
m_numParticles = numParticles;
|
||||
|
||||
// allocate host storage
|
||||
m_hPos = new float[m_numParticles*4];
|
||||
m_hVel = new float[m_numParticles*4];
|
||||
memset(m_hPos, 0, m_numParticles*4*sizeof(float));
|
||||
memset(m_hVel, 0, m_numParticles*4*sizeof(float));
|
||||
|
||||
m_hCellStart = new uint[m_numGridCells];
|
||||
memset(m_hCellStart, 0, m_numGridCells*sizeof(uint));
|
||||
|
||||
m_hCellEnd = new uint[m_numGridCells];
|
||||
memset(m_hCellEnd, 0, m_numGridCells*sizeof(uint));
|
||||
|
||||
// allocate GPU data
|
||||
unsigned int memSize = sizeof(float) * 4 * m_numParticles;
|
||||
|
||||
if (m_bUseOpenGL)
|
||||
{
|
||||
m_posVbo = createVBO(memSize);
|
||||
registerGLBufferObject(m_posVbo, &m_cuda_posvbo_resource);
|
||||
}
|
||||
else
|
||||
{
|
||||
checkCudaErrors(cudaMalloc((void **)&m_cudaPosVBO, memSize)) ;
|
||||
}
|
||||
|
||||
allocateArray((void **)&m_dVel, memSize);
|
||||
|
||||
allocateArray((void **)&m_dSortedPos, memSize);
|
||||
allocateArray((void **)&m_dSortedVel, memSize);
|
||||
|
||||
allocateArray((void **)&m_dGridParticleHash, m_numParticles*sizeof(uint));
|
||||
allocateArray((void **)&m_dGridParticleIndex, m_numParticles*sizeof(uint));
|
||||
|
||||
allocateArray((void **)&m_dCellStart, m_numGridCells*sizeof(uint));
|
||||
allocateArray((void **)&m_dCellEnd, m_numGridCells*sizeof(uint));
|
||||
|
||||
if (m_bUseOpenGL)
|
||||
{
|
||||
m_colorVBO = createVBO(m_numParticles*4*sizeof(float));
|
||||
registerGLBufferObject(m_colorVBO, &m_cuda_colorvbo_resource);
|
||||
|
||||
// fill color buffer
|
||||
glBindBuffer(GL_ARRAY_BUFFER, m_colorVBO);
|
||||
float *data = (float *) glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
|
||||
float *ptr = data;
|
||||
|
||||
for (uint i=0; i<m_numParticles; i++)
|
||||
{
|
||||
float t = i / (float) m_numParticles;
|
||||
#if 0
|
||||
*ptr++ = rand() / (float) RAND_MAX;
|
||||
*ptr++ = rand() / (float) RAND_MAX;
|
||||
*ptr++ = rand() / (float) RAND_MAX;
|
||||
#else
|
||||
colorRamp(t, ptr);
|
||||
ptr+=3;
|
||||
#endif
|
||||
*ptr++ = 1.0f;
|
||||
}
|
||||
|
||||
glUnmapBuffer(GL_ARRAY_BUFFER);
|
||||
}
|
||||
else
|
||||
{
|
||||
checkCudaErrors(cudaMalloc((void **)&m_cudaColorVBO, sizeof(float)*numParticles*4));
|
||||
}
|
||||
|
||||
sdkCreateTimer(&m_timer);
|
||||
|
||||
setParameters(&m_params);
|
||||
|
||||
m_bInitialized = true;
|
||||
}
|
||||
|
||||
void
|
||||
ParticleSystem::_finalize()
|
||||
{
|
||||
assert(m_bInitialized);
|
||||
|
||||
delete [] m_hPos;
|
||||
delete [] m_hVel;
|
||||
delete [] m_hCellStart;
|
||||
delete [] m_hCellEnd;
|
||||
|
||||
freeArray(m_dVel);
|
||||
freeArray(m_dSortedPos);
|
||||
freeArray(m_dSortedVel);
|
||||
|
||||
freeArray(m_dGridParticleHash);
|
||||
freeArray(m_dGridParticleIndex);
|
||||
freeArray(m_dCellStart);
|
||||
freeArray(m_dCellEnd);
|
||||
|
||||
if (m_bUseOpenGL)
|
||||
{
|
||||
unregisterGLBufferObject(m_cuda_colorvbo_resource);
|
||||
unregisterGLBufferObject(m_cuda_posvbo_resource);
|
||||
glDeleteBuffers(1, (const GLuint *)&m_posVbo);
|
||||
glDeleteBuffers(1, (const GLuint *)&m_colorVBO);
|
||||
}
|
||||
else
|
||||
{
|
||||
checkCudaErrors(cudaFree(m_cudaPosVBO));
|
||||
checkCudaErrors(cudaFree(m_cudaColorVBO));
|
||||
}
|
||||
}
|
||||
|
||||
// step the simulation
|
||||
void
|
||||
ParticleSystem::update(float deltaTime)
|
||||
{
|
||||
assert(m_bInitialized);
|
||||
|
||||
float *dPos;
|
||||
|
||||
if (m_bUseOpenGL)
|
||||
{
|
||||
dPos = (float *) mapGLBufferObject(&m_cuda_posvbo_resource);
|
||||
}
|
||||
else
|
||||
{
|
||||
dPos = (float *) m_cudaPosVBO;
|
||||
}
|
||||
|
||||
// update constants
|
||||
setParameters(&m_params);
|
||||
|
||||
// integrate
|
||||
integrateSystem(
|
||||
dPos,
|
||||
m_dVel,
|
||||
deltaTime,
|
||||
m_numParticles);
|
||||
|
||||
// calculate grid hash
|
||||
calcHash(
|
||||
m_dGridParticleHash,
|
||||
m_dGridParticleIndex,
|
||||
dPos,
|
||||
m_numParticles);
|
||||
|
||||
// sort particles based on hash
|
||||
sortParticles(m_dGridParticleHash, m_dGridParticleIndex, m_numParticles);
|
||||
|
||||
// reorder particle arrays into sorted order and
|
||||
// find start and end of each cell
|
||||
reorderDataAndFindCellStart(
|
||||
m_dCellStart,
|
||||
m_dCellEnd,
|
||||
m_dSortedPos,
|
||||
m_dSortedVel,
|
||||
m_dGridParticleHash,
|
||||
m_dGridParticleIndex,
|
||||
dPos,
|
||||
m_dVel,
|
||||
m_numParticles,
|
||||
m_numGridCells);
|
||||
|
||||
// process collisions
|
||||
collide(
|
||||
m_dVel,
|
||||
m_dSortedPos,
|
||||
m_dSortedVel,
|
||||
m_dGridParticleIndex,
|
||||
m_dCellStart,
|
||||
m_dCellEnd,
|
||||
m_numParticles,
|
||||
m_numGridCells);
|
||||
|
||||
// note: do unmap at end here to avoid unnecessary graphics/CUDA context switch
|
||||
if (m_bUseOpenGL)
|
||||
{
|
||||
unmapGLBufferObject(m_cuda_posvbo_resource);
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
ParticleSystem::dumpGrid()
|
||||
{
|
||||
// dump grid information
|
||||
copyArrayFromDevice(m_hCellStart, m_dCellStart, 0, sizeof(uint)*m_numGridCells);
|
||||
copyArrayFromDevice(m_hCellEnd, m_dCellEnd, 0, sizeof(uint)*m_numGridCells);
|
||||
uint maxCellSize = 0;
|
||||
|
||||
for (uint i=0; i<m_numGridCells; i++)
|
||||
{
|
||||
if (m_hCellStart[i] != 0xffffffff)
|
||||
{
|
||||
uint cellSize = m_hCellEnd[i] - m_hCellStart[i];
|
||||
|
||||
// printf("cell: %d, %d particles\n", i, cellSize);
|
||||
if (cellSize > maxCellSize)
|
||||
{
|
||||
maxCellSize = cellSize;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
printf("maximum particles per cell = %d\n", maxCellSize);
|
||||
}
|
||||
|
||||
void
|
||||
ParticleSystem::dumpParticles(uint start, uint count)
|
||||
{
|
||||
// debug
|
||||
copyArrayFromDevice(m_hPos, 0, &m_cuda_posvbo_resource, sizeof(float)*4*count);
|
||||
copyArrayFromDevice(m_hVel, m_dVel, 0, sizeof(float)*4*count);
|
||||
|
||||
for (uint i=start; i<start+count; i++)
|
||||
{
|
||||
// printf("%d: ", i);
|
||||
printf("pos: (%.4f, %.4f, %.4f, %.4f)\n", m_hPos[i*4+0], m_hPos[i*4+1], m_hPos[i*4+2], m_hPos[i*4+3]);
|
||||
printf("vel: (%.4f, %.4f, %.4f, %.4f)\n", m_hVel[i*4+0], m_hVel[i*4+1], m_hVel[i*4+2], m_hVel[i*4+3]);
|
||||
}
|
||||
}
|
||||
|
||||
float *
|
||||
ParticleSystem::getArray(ParticleArray array)
|
||||
{
|
||||
assert(m_bInitialized);
|
||||
|
||||
float *hdata = 0;
|
||||
float *ddata = 0;
|
||||
struct cudaGraphicsResource *cuda_vbo_resource = 0;
|
||||
|
||||
switch (array)
|
||||
{
|
||||
default:
|
||||
case POSITION:
|
||||
hdata = m_hPos;
|
||||
ddata = m_dPos;
|
||||
cuda_vbo_resource = m_cuda_posvbo_resource;
|
||||
break;
|
||||
|
||||
case VELOCITY:
|
||||
hdata = m_hVel;
|
||||
ddata = m_dVel;
|
||||
break;
|
||||
}
|
||||
|
||||
copyArrayFromDevice(hdata, ddata, &cuda_vbo_resource, m_numParticles*4*sizeof(float));
|
||||
return hdata;
|
||||
}
|
||||
|
||||
void
|
||||
ParticleSystem::setArray(ParticleArray array, const float *data, int start, int count)
|
||||
{
|
||||
assert(m_bInitialized);
|
||||
|
||||
switch (array)
|
||||
{
|
||||
default:
|
||||
case POSITION:
|
||||
{
|
||||
if (m_bUseOpenGL)
|
||||
{
|
||||
unregisterGLBufferObject(m_cuda_posvbo_resource);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, m_posVbo);
|
||||
glBufferSubData(GL_ARRAY_BUFFER, start*4*sizeof(float), count*4*sizeof(float), data);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, 0);
|
||||
registerGLBufferObject(m_posVbo, &m_cuda_posvbo_resource);
|
||||
}
|
||||
else
|
||||
{
|
||||
copyArrayToDevice(m_cudaPosVBO, data, start*4*sizeof(float), count*4*sizeof(float));
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case VELOCITY:
|
||||
copyArrayToDevice(m_dVel, data, start*4*sizeof(float), count*4*sizeof(float));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
inline float frand()
|
||||
{
|
||||
return rand() / (float) RAND_MAX;
|
||||
}
|
||||
|
||||
void
|
||||
ParticleSystem::initGrid(uint *size, float spacing, float jitter, uint numParticles)
|
||||
{
|
||||
srand(1973);
|
||||
|
||||
for (uint z=0; z<size[2]; z++)
|
||||
{
|
||||
for (uint y=0; y<size[1]; y++)
|
||||
{
|
||||
for (uint x=0; x<size[0]; x++)
|
||||
{
|
||||
uint i = (z*size[1]*size[0]) + (y*size[0]) + x;
|
||||
|
||||
if (i < numParticles)
|
||||
{
|
||||
m_hPos[i*4] = (spacing * x) + m_params.particleRadius - 1.0f + (frand()*2.0f-1.0f)*jitter;
|
||||
m_hPos[i*4+1] = (spacing * y) + m_params.particleRadius - 1.0f + (frand()*2.0f-1.0f)*jitter;
|
||||
m_hPos[i*4+2] = (spacing * z) + m_params.particleRadius - 1.0f + (frand()*2.0f-1.0f)*jitter;
|
||||
m_hPos[i*4+3] = 1.0f;
|
||||
|
||||
m_hVel[i*4] = 0.0f;
|
||||
m_hVel[i*4+1] = 0.0f;
|
||||
m_hVel[i*4+2] = 0.0f;
|
||||
m_hVel[i*4+3] = 0.0f;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
ParticleSystem::reset(ParticleConfig config)
|
||||
{
|
||||
switch (config)
|
||||
{
|
||||
default:
|
||||
case CONFIG_RANDOM:
|
||||
{
|
||||
int p = 0, v = 0;
|
||||
|
||||
for (uint i=0; i < m_numParticles; i++)
|
||||
{
|
||||
float point[3];
|
||||
point[0] = frand();
|
||||
point[1] = frand();
|
||||
point[2] = frand();
|
||||
m_hPos[p++] = 2 * (point[0] - 0.5f);
|
||||
m_hPos[p++] = 2 * (point[1] - 0.5f);
|
||||
m_hPos[p++] = 2 * (point[2] - 0.5f);
|
||||
m_hPos[p++] = 1.0f; // radius
|
||||
m_hVel[v++] = 0.0f;
|
||||
m_hVel[v++] = 0.0f;
|
||||
m_hVel[v++] = 0.0f;
|
||||
m_hVel[v++] = 0.0f;
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case CONFIG_GRID:
|
||||
{
|
||||
float jitter = m_params.particleRadius*0.01f;
|
||||
uint s = (int) ceilf(powf((float) m_numParticles, 1.0f / 3.0f));
|
||||
uint gridSize[3];
|
||||
gridSize[0] = gridSize[1] = gridSize[2] = s;
|
||||
initGrid(gridSize, m_params.particleRadius*2.0f, jitter, m_numParticles);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
setArray(POSITION, m_hPos, 0, m_numParticles);
|
||||
setArray(VELOCITY, m_hVel, 0, m_numParticles);
|
||||
}
|
||||
|
||||
void
|
||||
ParticleSystem::addSphere(int start, float *pos, float *vel, int r, float spacing)
|
||||
{
|
||||
uint index = start;
|
||||
|
||||
for (int z=-r; z<=r; z++)
|
||||
{
|
||||
for (int y=-r; y<=r; y++)
|
||||
{
|
||||
for (int x=-r; x<=r; x++)
|
||||
{
|
||||
float dx = x*spacing;
|
||||
float dy = y*spacing;
|
||||
float dz = z*spacing;
|
||||
float l = sqrtf(dx*dx + dy*dy + dz*dz);
|
||||
float jitter = m_params.particleRadius*0.01f;
|
||||
|
||||
if ((l <= m_params.particleRadius*2.0f*r) && (index < m_numParticles))
|
||||
{
|
||||
m_hPos[index*4] = pos[0] + dx + (frand()*2.0f-1.0f)*jitter;
|
||||
m_hPos[index*4+1] = pos[1] + dy + (frand()*2.0f-1.0f)*jitter;
|
||||
m_hPos[index*4+2] = pos[2] + dz + (frand()*2.0f-1.0f)*jitter;
|
||||
m_hPos[index*4+3] = pos[3];
|
||||
|
||||
m_hVel[index*4] = vel[0];
|
||||
m_hVel[index*4+1] = vel[1];
|
||||
m_hVel[index*4+2] = vel[2];
|
||||
m_hVel[index*4+3] = vel[3];
|
||||
index++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setArray(POSITION, m_hPos, start, index);
|
||||
setArray(VELOCITY, m_hVel, start, index);
|
||||
}
|
||||
67
Samples/particles/particleSystem.cuh
Normal file
67
Samples/particles/particleSystem.cuh
Normal file
@@ -0,0 +1,67 @@
|
||||
/* Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
extern "C" {
|
||||
void cudaInit(int argc, char **argv);
|
||||
|
||||
void allocateArray(void **devPtr, int size);
|
||||
void freeArray(void *devPtr);
|
||||
|
||||
void threadSync();
|
||||
|
||||
void copyArrayFromDevice(void *host, const void *device,
|
||||
struct cudaGraphicsResource **cuda_vbo_resource,
|
||||
int size);
|
||||
void copyArrayToDevice(void *device, const void *host, int offset, int size);
|
||||
void registerGLBufferObject(uint vbo,
|
||||
struct cudaGraphicsResource **cuda_vbo_resource);
|
||||
void unregisterGLBufferObject(struct cudaGraphicsResource *cuda_vbo_resource);
|
||||
void *mapGLBufferObject(struct cudaGraphicsResource **cuda_vbo_resource);
|
||||
void unmapGLBufferObject(struct cudaGraphicsResource *cuda_vbo_resource);
|
||||
|
||||
void setParameters(SimParams *hostParams);
|
||||
|
||||
void integrateSystem(float *pos, float *vel, float deltaTime,
|
||||
uint numParticles);
|
||||
|
||||
void calcHash(uint *gridParticleHash, uint *gridParticleIndex, float *pos,
|
||||
int numParticles);
|
||||
|
||||
void reorderDataAndFindCellStart(uint *cellStart, uint *cellEnd,
|
||||
float *sortedPos, float *sortedVel,
|
||||
uint *gridParticleHash,
|
||||
uint *gridParticleIndex, float *oldPos,
|
||||
float *oldVel, uint numParticles,
|
||||
uint numCells);
|
||||
|
||||
void collide(float *newVel, float *sortedPos, float *sortedVel,
|
||||
uint *gridParticleIndex, uint *cellStart, uint *cellEnd,
|
||||
uint numParticles, uint numCells);
|
||||
|
||||
void sortParticles(uint *dGridParticleHash, uint *dGridParticleIndex,
|
||||
uint numParticles);
|
||||
}
|
||||
146
Samples/particles/particleSystem.h
Normal file
146
Samples/particles/particleSystem.h
Normal file
@@ -0,0 +1,146 @@
|
||||
/* Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#ifndef __PARTICLESYSTEM_H__
|
||||
#define __PARTICLESYSTEM_H__
|
||||
|
||||
#define DEBUG_GRID 0
|
||||
#define DO_TIMING 0
|
||||
|
||||
#include <helper_functions.h>
|
||||
#include "particles_kernel.cuh"
|
||||
#include "vector_functions.h"
|
||||
|
||||
// Particle system class
|
||||
class ParticleSystem {
|
||||
public:
|
||||
ParticleSystem(uint numParticles, uint3 gridSize, bool bUseOpenGL);
|
||||
~ParticleSystem();
|
||||
|
||||
enum ParticleConfig { CONFIG_RANDOM, CONFIG_GRID, _NUM_CONFIGS };
|
||||
|
||||
enum ParticleArray {
|
||||
POSITION,
|
||||
VELOCITY,
|
||||
};
|
||||
|
||||
void update(float deltaTime);
|
||||
void reset(ParticleConfig config);
|
||||
|
||||
float *getArray(ParticleArray array);
|
||||
void setArray(ParticleArray array, const float *data, int start, int count);
|
||||
|
||||
int getNumParticles() const { return m_numParticles; }
|
||||
|
||||
unsigned int getCurrentReadBuffer() const { return m_posVbo; }
|
||||
unsigned int getColorBuffer() const { return m_colorVBO; }
|
||||
|
||||
void *getCudaPosVBO() const { return (void *)m_cudaPosVBO; }
|
||||
void *getCudaColorVBO() const { return (void *)m_cudaColorVBO; }
|
||||
|
||||
void dumpGrid();
|
||||
void dumpParticles(uint start, uint count);
|
||||
|
||||
void setIterations(int i) { m_solverIterations = i; }
|
||||
|
||||
void setDamping(float x) { m_params.globalDamping = x; }
|
||||
void setGravity(float x) { m_params.gravity = make_float3(0.0f, x, 0.0f); }
|
||||
|
||||
void setCollideSpring(float x) { m_params.spring = x; }
|
||||
void setCollideDamping(float x) { m_params.damping = x; }
|
||||
void setCollideShear(float x) { m_params.shear = x; }
|
||||
void setCollideAttraction(float x) { m_params.attraction = x; }
|
||||
|
||||
void setColliderPos(float3 x) { m_params.colliderPos = x; }
|
||||
|
||||
float getParticleRadius() { return m_params.particleRadius; }
|
||||
float3 getColliderPos() { return m_params.colliderPos; }
|
||||
float getColliderRadius() { return m_params.colliderRadius; }
|
||||
uint3 getGridSize() { return m_params.gridSize; }
|
||||
float3 getWorldOrigin() { return m_params.worldOrigin; }
|
||||
float3 getCellSize() { return m_params.cellSize; }
|
||||
|
||||
void addSphere(int index, float *pos, float *vel, int r, float spacing);
|
||||
|
||||
protected: // methods
|
||||
ParticleSystem() {}
|
||||
uint createVBO(uint size);
|
||||
|
||||
void _initialize(int numParticles);
|
||||
void _finalize();
|
||||
|
||||
void initGrid(uint *size, float spacing, float jitter, uint numParticles);
|
||||
|
||||
protected: // data
|
||||
bool m_bInitialized, m_bUseOpenGL;
|
||||
uint m_numParticles;
|
||||
|
||||
// CPU data
|
||||
float *m_hPos; // particle positions
|
||||
float *m_hVel; // particle velocities
|
||||
|
||||
uint *m_hParticleHash;
|
||||
uint *m_hCellStart;
|
||||
uint *m_hCellEnd;
|
||||
|
||||
// GPU data
|
||||
float *m_dPos;
|
||||
float *m_dVel;
|
||||
|
||||
float *m_dSortedPos;
|
||||
float *m_dSortedVel;
|
||||
|
||||
// grid data for sorting method
|
||||
uint *m_dGridParticleHash; // grid hash value for each particle
|
||||
uint *m_dGridParticleIndex; // particle index for each particle
|
||||
uint *m_dCellStart; // index of start of each cell in sorted list
|
||||
uint *m_dCellEnd; // index of end of cell
|
||||
|
||||
uint m_gridSortBits;
|
||||
|
||||
uint m_posVbo; // vertex buffer object for particle positions
|
||||
uint m_colorVBO; // vertex buffer object for colors
|
||||
|
||||
float *m_cudaPosVBO; // these are the CUDA deviceMem Pos
|
||||
float *m_cudaColorVBO; // these are the CUDA deviceMem Color
|
||||
|
||||
struct cudaGraphicsResource
|
||||
*m_cuda_posvbo_resource; // handles OpenGL-CUDA exchange
|
||||
struct cudaGraphicsResource
|
||||
*m_cuda_colorvbo_resource; // handles OpenGL-CUDA exchange
|
||||
|
||||
// params
|
||||
SimParams m_params;
|
||||
uint3 m_gridSize;
|
||||
uint m_numGridCells;
|
||||
|
||||
StopWatchInterface *m_timer;
|
||||
|
||||
uint m_solverIterations;
|
||||
};
|
||||
|
||||
#endif // __PARTICLESYSTEM_H__
|
||||
204
Samples/particles/particleSystem_cuda.cu
Normal file
204
Samples/particles/particleSystem_cuda.cu
Normal file
@@ -0,0 +1,204 @@
|
||||
/* Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
// This file contains C wrappers around the some of the CUDA API and the
|
||||
// kernel functions so that they can be called from "particleSystem.cpp"
|
||||
|
||||
#if defined(__APPLE__) || defined(MACOSX)
|
||||
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
|
||||
#include <GLUT/glut.h>
|
||||
#else
|
||||
#include <GL/freeglut.h>
|
||||
#endif
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstdio>
|
||||
#include <string.h>
|
||||
|
||||
#include <cuda_runtime.h>
|
||||
#include <cuda_gl_interop.h>
|
||||
|
||||
#include <helper_cuda.h>
|
||||
|
||||
#include <helper_functions.h>
|
||||
#include "thrust/device_ptr.h"
|
||||
#include "thrust/for_each.h"
|
||||
#include "thrust/iterator/zip_iterator.h"
|
||||
#include "thrust/sort.h"
|
||||
|
||||
#include "particles_kernel_impl.cuh"
|
||||
|
||||
extern "C" {
|
||||
|
||||
void cudaInit(int argc, char **argv) {
|
||||
int devID;
|
||||
|
||||
// use command-line specified CUDA device, otherwise use device with highest
|
||||
// Gflops/s
|
||||
devID = findCudaDevice(argc, (const char **)argv);
|
||||
|
||||
if (devID < 0) {
|
||||
printf("No CUDA Capable devices found, exiting...\n");
|
||||
exit(EXIT_SUCCESS);
|
||||
}
|
||||
}
|
||||
|
||||
void allocateArray(void **devPtr, size_t size) {
|
||||
checkCudaErrors(cudaMalloc(devPtr, size));
|
||||
}
|
||||
|
||||
void freeArray(void *devPtr) { checkCudaErrors(cudaFree(devPtr)); }
|
||||
|
||||
void threadSync() { checkCudaErrors(cudaDeviceSynchronize()); }
|
||||
|
||||
void copyArrayToDevice(void *device, const void *host, int offset, int size) {
|
||||
checkCudaErrors(
|
||||
cudaMemcpy((char *)device + offset, host, size, cudaMemcpyHostToDevice));
|
||||
}
|
||||
|
||||
void registerGLBufferObject(uint vbo,
|
||||
struct cudaGraphicsResource **cuda_vbo_resource) {
|
||||
checkCudaErrors(cudaGraphicsGLRegisterBuffer(cuda_vbo_resource, vbo,
|
||||
cudaGraphicsMapFlagsNone));
|
||||
}
|
||||
|
||||
void unregisterGLBufferObject(struct cudaGraphicsResource *cuda_vbo_resource) {
|
||||
checkCudaErrors(cudaGraphicsUnregisterResource(cuda_vbo_resource));
|
||||
}
|
||||
|
||||
void *mapGLBufferObject(struct cudaGraphicsResource **cuda_vbo_resource) {
|
||||
void *ptr;
|
||||
checkCudaErrors(cudaGraphicsMapResources(1, cuda_vbo_resource, 0));
|
||||
size_t num_bytes;
|
||||
checkCudaErrors(cudaGraphicsResourceGetMappedPointer(
|
||||
(void **)&ptr, &num_bytes, *cuda_vbo_resource));
|
||||
return ptr;
|
||||
}
|
||||
|
||||
void unmapGLBufferObject(struct cudaGraphicsResource *cuda_vbo_resource) {
|
||||
checkCudaErrors(cudaGraphicsUnmapResources(1, &cuda_vbo_resource, 0));
|
||||
}
|
||||
|
||||
void copyArrayFromDevice(void *host, const void *device,
|
||||
struct cudaGraphicsResource **cuda_vbo_resource,
|
||||
int size) {
|
||||
if (cuda_vbo_resource) {
|
||||
device = mapGLBufferObject(cuda_vbo_resource);
|
||||
}
|
||||
|
||||
checkCudaErrors(cudaMemcpy(host, device, size, cudaMemcpyDeviceToHost));
|
||||
|
||||
if (cuda_vbo_resource) {
|
||||
unmapGLBufferObject(*cuda_vbo_resource);
|
||||
}
|
||||
}
|
||||
|
||||
void setParameters(SimParams *hostParams) {
|
||||
// copy parameters to constant memory
|
||||
checkCudaErrors(cudaMemcpyToSymbol(params, hostParams, sizeof(SimParams)));
|
||||
}
|
||||
|
||||
// Round a / b to nearest higher integer value
|
||||
uint iDivUp(uint a, uint b) { return (a % b != 0) ? (a / b + 1) : (a / b); }
|
||||
|
||||
// compute grid and thread block size for a given number of elements
|
||||
void computeGridSize(uint n, uint blockSize, uint &numBlocks,
|
||||
uint &numThreads) {
|
||||
numThreads = min(blockSize, n);
|
||||
numBlocks = iDivUp(n, numThreads);
|
||||
}
|
||||
|
||||
void integrateSystem(float *pos, float *vel, float deltaTime,
|
||||
uint numParticles) {
|
||||
thrust::device_ptr<float4> d_pos4((float4 *)pos);
|
||||
thrust::device_ptr<float4> d_vel4((float4 *)vel);
|
||||
|
||||
thrust::for_each(
|
||||
thrust::make_zip_iterator(thrust::make_tuple(d_pos4, d_vel4)),
|
||||
thrust::make_zip_iterator(
|
||||
thrust::make_tuple(d_pos4 + numParticles, d_vel4 + numParticles)),
|
||||
integrate_functor(deltaTime));
|
||||
}
|
||||
|
||||
void calcHash(uint *gridParticleHash, uint *gridParticleIndex, float *pos,
|
||||
int numParticles) {
|
||||
uint numThreads, numBlocks;
|
||||
computeGridSize(numParticles, 256, numBlocks, numThreads);
|
||||
|
||||
// execute the kernel
|
||||
calcHashD<<<numBlocks, numThreads>>>(gridParticleHash, gridParticleIndex,
|
||||
(float4 *)pos, numParticles);
|
||||
|
||||
// check if kernel invocation generated an error
|
||||
getLastCudaError("Kernel execution failed");
|
||||
}
|
||||
|
||||
void reorderDataAndFindCellStart(uint *cellStart, uint *cellEnd,
|
||||
float *sortedPos, float *sortedVel,
|
||||
uint *gridParticleHash,
|
||||
uint *gridParticleIndex, float *oldPos,
|
||||
float *oldVel, uint numParticles,
|
||||
uint numCells) {
|
||||
uint numThreads, numBlocks;
|
||||
computeGridSize(numParticles, 256, numBlocks, numThreads);
|
||||
|
||||
// set all cells to empty
|
||||
checkCudaErrors(cudaMemset(cellStart, 0xffffffff, numCells * sizeof(uint)));
|
||||
|
||||
uint smemSize = sizeof(uint) * (numThreads + 1);
|
||||
reorderDataAndFindCellStartD<<<numBlocks, numThreads, smemSize>>>(
|
||||
cellStart, cellEnd, (float4 *)sortedPos, (float4 *)sortedVel,
|
||||
gridParticleHash, gridParticleIndex, (float4 *)oldPos, (float4 *)oldVel,
|
||||
numParticles);
|
||||
getLastCudaError("Kernel execution failed: reorderDataAndFindCellStartD");
|
||||
}
|
||||
|
||||
void collide(float *newVel, float *sortedPos, float *sortedVel,
|
||||
uint *gridParticleIndex, uint *cellStart, uint *cellEnd,
|
||||
uint numParticles, uint numCells) {
|
||||
// thread per particle
|
||||
uint numThreads, numBlocks;
|
||||
computeGridSize(numParticles, 64, numBlocks, numThreads);
|
||||
|
||||
// execute the kernel
|
||||
collideD<<<numBlocks, numThreads>>>((float4 *)newVel, (float4 *)sortedPos,
|
||||
(float4 *)sortedVel, gridParticleIndex,
|
||||
cellStart, cellEnd, numParticles);
|
||||
|
||||
// check if kernel invocation generated an error
|
||||
getLastCudaError("Kernel execution failed");
|
||||
}
|
||||
|
||||
void sortParticles(uint *dGridParticleHash, uint *dGridParticleIndex,
|
||||
uint numParticles) {
|
||||
thrust::sort_by_key(
|
||||
thrust::device_ptr<uint>(dGridParticleHash),
|
||||
thrust::device_ptr<uint>(dGridParticleHash + numParticles),
|
||||
thrust::device_ptr<uint>(dGridParticleIndex));
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
745
Samples/particles/particles.cpp
Normal file
745
Samples/particles/particles.cpp
Normal file
@@ -0,0 +1,745 @@
|
||||
/* Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
/*
|
||||
Particle system example with collisions using uniform grid
|
||||
|
||||
CUDA 2.1 SDK release 12/2008
|
||||
- removed atomic grid method, some optimization, added demo mode.
|
||||
|
||||
CUDA 2.2 release 3/2009
|
||||
- replaced sort function with latest radix sort, now disables v-sync.
|
||||
- added support for automated testing and comparison to a reference value.
|
||||
*/
|
||||
|
||||
// OpenGL Graphics includes
|
||||
#include <helper_gl.h>
|
||||
#if defined(WIN32)
|
||||
#include <GL/wglew.h>
|
||||
#endif
|
||||
#if defined(__APPLE__) || defined(__MACOSX)
|
||||
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
|
||||
#include <GLUT/glut.h>
|
||||
#ifndef glutCloseFunc
|
||||
#define glutCloseFunc glutWMCloseFunc
|
||||
#endif
|
||||
#else
|
||||
#include <GL/freeglut.h>
|
||||
#endif
|
||||
|
||||
// CUDA runtime
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
// CUDA utilities and system includes
|
||||
#include <helper_functions.h>
|
||||
#include <helper_cuda.h> // includes cuda.h and cuda_runtime_api.h
|
||||
|
||||
// Includes
|
||||
#include <stdlib.h>
|
||||
#include <cstdlib>
|
||||
#include <cstdio>
|
||||
#include <algorithm>
|
||||
|
||||
#include "particleSystem.h"
|
||||
#include "render_particles.h"
|
||||
#include "paramgl.h"
|
||||
|
||||
#define MAX_EPSILON_ERROR 5.00f
|
||||
#define THRESHOLD 0.30f
|
||||
|
||||
#define GRID_SIZE 64
|
||||
#define NUM_PARTICLES 16384
|
||||
|
||||
const uint width = 640, height = 480;
|
||||
|
||||
// view params
|
||||
int ox, oy;
|
||||
int buttonState = 0;
|
||||
float camera_trans[] = {0, 0, -3};
|
||||
float camera_rot[] = {0, 0, 0};
|
||||
float camera_trans_lag[] = {0, 0, -3};
|
||||
float camera_rot_lag[] = {0, 0, 0};
|
||||
const float inertia = 0.1f;
|
||||
ParticleRenderer::DisplayMode displayMode = ParticleRenderer::PARTICLE_SPHERES;
|
||||
|
||||
int mode = 0;
|
||||
bool displayEnabled = true;
|
||||
bool bPause = false;
|
||||
bool displaySliders = false;
|
||||
bool wireframe = false;
|
||||
bool demoMode = false;
|
||||
int idleCounter = 0;
|
||||
int demoCounter = 0;
|
||||
const int idleDelay = 2000;
|
||||
|
||||
enum { M_VIEW = 0, M_MOVE };
|
||||
|
||||
uint numParticles = 0;
|
||||
uint3 gridSize;
|
||||
int numIterations = 0; // run until exit
|
||||
|
||||
// simulation parameters
|
||||
float timestep = 0.5f;
|
||||
float damping = 1.0f;
|
||||
float gravity = 0.0003f;
|
||||
int iterations = 1;
|
||||
int ballr = 10;
|
||||
|
||||
float collideSpring = 0.5f;
|
||||
;
|
||||
float collideDamping = 0.02f;
|
||||
;
|
||||
float collideShear = 0.1f;
|
||||
float collideAttraction = 0.0f;
|
||||
|
||||
ParticleSystem *psystem = 0;
|
||||
|
||||
// fps
|
||||
static int fpsCount = 0;
|
||||
static int fpsLimit = 1;
|
||||
StopWatchInterface *timer = NULL;
|
||||
|
||||
ParticleRenderer *renderer = 0;
|
||||
|
||||
float modelView[16];
|
||||
|
||||
ParamListGL *params;
|
||||
|
||||
// Auto-Verification Code
|
||||
const int frameCheckNumber = 4;
|
||||
unsigned int frameCount = 0;
|
||||
unsigned int g_TotalErrors = 0;
|
||||
char *g_refFile = NULL;
|
||||
|
||||
const char *sSDKsample = "CUDA Particles Simulation";
|
||||
|
||||
extern "C" void cudaInit(int argc, char **argv);
|
||||
extern "C" void cudaGLInit(int argc, char **argv);
|
||||
extern "C" void copyArrayFromDevice(void *host, const void *device,
|
||||
unsigned int vbo, int size);
|
||||
|
||||
// initialize particle system
|
||||
void initParticleSystem(int numParticles, uint3 gridSize, bool bUseOpenGL) {
|
||||
psystem = new ParticleSystem(numParticles, gridSize, bUseOpenGL);
|
||||
psystem->reset(ParticleSystem::CONFIG_GRID);
|
||||
|
||||
if (bUseOpenGL) {
|
||||
renderer = new ParticleRenderer;
|
||||
renderer->setParticleRadius(psystem->getParticleRadius());
|
||||
renderer->setColorBuffer(psystem->getColorBuffer());
|
||||
}
|
||||
|
||||
sdkCreateTimer(&timer);
|
||||
}
|
||||
|
||||
void cleanup() {
|
||||
sdkDeleteTimer(&timer);
|
||||
|
||||
if (psystem) {
|
||||
delete psystem;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// initialize OpenGL
|
||||
void initGL(int *argc, char **argv) {
|
||||
glutInit(argc, argv);
|
||||
glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
|
||||
glutInitWindowSize(width, height);
|
||||
glutCreateWindow("CUDA Particles");
|
||||
|
||||
if (!isGLVersionSupported(2, 0) ||
|
||||
!areGLExtensionsSupported(
|
||||
"GL_ARB_multitexture GL_ARB_vertex_buffer_object")) {
|
||||
fprintf(stderr, "Required OpenGL extensions missing.");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
#if defined(WIN32)
|
||||
|
||||
if (wglewIsSupported("WGL_EXT_swap_control")) {
|
||||
// disable vertical sync
|
||||
wglSwapIntervalEXT(0);
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
glEnable(GL_DEPTH_TEST);
|
||||
glClearColor(0.25, 0.25, 0.25, 1.0);
|
||||
|
||||
glutReportErrors();
|
||||
}
|
||||
|
||||
void runBenchmark(int iterations, char *exec_path) {
|
||||
printf("Run %u particles simulation for %d iterations...\n\n", numParticles,
|
||||
iterations);
|
||||
cudaDeviceSynchronize();
|
||||
sdkStartTimer(&timer);
|
||||
|
||||
for (int i = 0; i < iterations; ++i) {
|
||||
psystem->update(timestep);
|
||||
}
|
||||
|
||||
cudaDeviceSynchronize();
|
||||
sdkStopTimer(&timer);
|
||||
float fAvgSeconds =
|
||||
((float)1.0e-3 * (float)sdkGetTimerValue(&timer) / (float)iterations);
|
||||
|
||||
printf(
|
||||
"particles, Throughput = %.4f KParticles/s, Time = %.5f s, Size = %u "
|
||||
"particles, NumDevsUsed = %u, Workgroup = %u\n",
|
||||
(1.0e-3 * numParticles) / fAvgSeconds, fAvgSeconds, numParticles, 1, 0);
|
||||
|
||||
if (g_refFile) {
|
||||
printf("\nChecking result...\n\n");
|
||||
float *hPos =
|
||||
(float *)malloc(sizeof(float) * 4 * psystem->getNumParticles());
|
||||
copyArrayFromDevice(hPos, psystem->getCudaPosVBO(), 0,
|
||||
sizeof(float) * 4 * psystem->getNumParticles());
|
||||
|
||||
sdkDumpBin((void *)hPos, sizeof(float) * 4 * psystem->getNumParticles(),
|
||||
"particles.bin");
|
||||
|
||||
if (!sdkCompareBin2BinFloat("particles.bin", g_refFile,
|
||||
4 * psystem->getNumParticles(),
|
||||
MAX_EPSILON_ERROR, THRESHOLD, exec_path)) {
|
||||
g_TotalErrors++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void computeFPS() {
|
||||
frameCount++;
|
||||
fpsCount++;
|
||||
|
||||
if (fpsCount == fpsLimit) {
|
||||
char fps[256];
|
||||
float ifps = 1.f / (sdkGetAverageTimerValue(&timer) / 1000.f);
|
||||
sprintf(fps, "CUDA Particles (%d particles): %3.1f fps", numParticles,
|
||||
ifps);
|
||||
|
||||
glutSetWindowTitle(fps);
|
||||
fpsCount = 0;
|
||||
|
||||
fpsLimit = (int)MAX(ifps, 1.f);
|
||||
sdkResetTimer(&timer);
|
||||
}
|
||||
}
|
||||
|
||||
void display() {
|
||||
sdkStartTimer(&timer);
|
||||
|
||||
// update the simulation
|
||||
if (!bPause) {
|
||||
psystem->setIterations(iterations);
|
||||
psystem->setDamping(damping);
|
||||
psystem->setGravity(-gravity);
|
||||
psystem->setCollideSpring(collideSpring);
|
||||
psystem->setCollideDamping(collideDamping);
|
||||
psystem->setCollideShear(collideShear);
|
||||
psystem->setCollideAttraction(collideAttraction);
|
||||
|
||||
psystem->update(timestep);
|
||||
|
||||
if (renderer) {
|
||||
renderer->setVertexBuffer(psystem->getCurrentReadBuffer(),
|
||||
psystem->getNumParticles());
|
||||
}
|
||||
}
|
||||
|
||||
// render
|
||||
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
|
||||
|
||||
// view transform
|
||||
glMatrixMode(GL_MODELVIEW);
|
||||
glLoadIdentity();
|
||||
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
camera_trans_lag[c] += (camera_trans[c] - camera_trans_lag[c]) * inertia;
|
||||
camera_rot_lag[c] += (camera_rot[c] - camera_rot_lag[c]) * inertia;
|
||||
}
|
||||
|
||||
glTranslatef(camera_trans_lag[0], camera_trans_lag[1], camera_trans_lag[2]);
|
||||
glRotatef(camera_rot_lag[0], 1.0, 0.0, 0.0);
|
||||
glRotatef(camera_rot_lag[1], 0.0, 1.0, 0.0);
|
||||
|
||||
glGetFloatv(GL_MODELVIEW_MATRIX, modelView);
|
||||
|
||||
// cube
|
||||
glColor3f(1.0, 1.0, 1.0);
|
||||
glutWireCube(2.0);
|
||||
|
||||
// collider
|
||||
glPushMatrix();
|
||||
float3 p = psystem->getColliderPos();
|
||||
glTranslatef(p.x, p.y, p.z);
|
||||
glColor3f(1.0, 0.0, 0.0);
|
||||
glutSolidSphere(psystem->getColliderRadius(), 20, 10);
|
||||
glPopMatrix();
|
||||
|
||||
if (renderer && displayEnabled) {
|
||||
renderer->display(displayMode);
|
||||
}
|
||||
|
||||
if (displaySliders) {
|
||||
glDisable(GL_DEPTH_TEST);
|
||||
glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ZERO); // invert color
|
||||
glEnable(GL_BLEND);
|
||||
params->Render(0, 0);
|
||||
glDisable(GL_BLEND);
|
||||
glEnable(GL_DEPTH_TEST);
|
||||
}
|
||||
|
||||
sdkStopTimer(&timer);
|
||||
|
||||
glutSwapBuffers();
|
||||
glutReportErrors();
|
||||
|
||||
computeFPS();
|
||||
}
|
||||
|
||||
inline float frand() { return rand() / (float)RAND_MAX; }
|
||||
|
||||
void addSphere() {
|
||||
// inject a sphere of particles
|
||||
float pr = psystem->getParticleRadius();
|
||||
float tr = pr + (pr * 2.0f) * ballr;
|
||||
float pos[4], vel[4];
|
||||
pos[0] = -1.0f + tr + frand() * (2.0f - tr * 2.0f);
|
||||
pos[1] = 1.0f - tr;
|
||||
pos[2] = -1.0f + tr + frand() * (2.0f - tr * 2.0f);
|
||||
pos[3] = 0.0f;
|
||||
vel[0] = vel[1] = vel[2] = vel[3] = 0.0f;
|
||||
psystem->addSphere(0, pos, vel, ballr, pr * 2.0f);
|
||||
}
|
||||
|
||||
void reshape(int w, int h) {
|
||||
glMatrixMode(GL_PROJECTION);
|
||||
glLoadIdentity();
|
||||
gluPerspective(60.0, (float)w / (float)h, 0.1, 100.0);
|
||||
|
||||
glMatrixMode(GL_MODELVIEW);
|
||||
glViewport(0, 0, w, h);
|
||||
|
||||
if (renderer) {
|
||||
renderer->setWindowSize(w, h);
|
||||
renderer->setFOV(60.0);
|
||||
}
|
||||
}
|
||||
|
||||
void mouse(int button, int state, int x, int y) {
|
||||
int mods;
|
||||
|
||||
if (state == GLUT_DOWN) {
|
||||
buttonState |= 1 << button;
|
||||
} else if (state == GLUT_UP) {
|
||||
buttonState = 0;
|
||||
}
|
||||
|
||||
mods = glutGetModifiers();
|
||||
|
||||
if (mods & GLUT_ACTIVE_SHIFT) {
|
||||
buttonState = 2;
|
||||
} else if (mods & GLUT_ACTIVE_CTRL) {
|
||||
buttonState = 3;
|
||||
}
|
||||
|
||||
ox = x;
|
||||
oy = y;
|
||||
|
||||
demoMode = false;
|
||||
idleCounter = 0;
|
||||
|
||||
if (displaySliders) {
|
||||
if (params->Mouse(x, y, button, state)) {
|
||||
glutPostRedisplay();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
glutPostRedisplay();
|
||||
}
|
||||
|
||||
// transform vector by matrix
|
||||
void xform(float *v, float *r, GLfloat *m) {
|
||||
r[0] = v[0] * m[0] + v[1] * m[4] + v[2] * m[8] + m[12];
|
||||
r[1] = v[0] * m[1] + v[1] * m[5] + v[2] * m[9] + m[13];
|
||||
r[2] = v[0] * m[2] + v[1] * m[6] + v[2] * m[10] + m[14];
|
||||
}
|
||||
|
||||
// transform vector by transpose of matrix
|
||||
void ixform(float *v, float *r, GLfloat *m) {
|
||||
r[0] = v[0] * m[0] + v[1] * m[1] + v[2] * m[2];
|
||||
r[1] = v[0] * m[4] + v[1] * m[5] + v[2] * m[6];
|
||||
r[2] = v[0] * m[8] + v[1] * m[9] + v[2] * m[10];
|
||||
}
|
||||
|
||||
void ixformPoint(float *v, float *r, GLfloat *m) {
|
||||
float x[4];
|
||||
x[0] = v[0] - m[12];
|
||||
x[1] = v[1] - m[13];
|
||||
x[2] = v[2] - m[14];
|
||||
x[3] = 1.0f;
|
||||
ixform(x, r, m);
|
||||
}
|
||||
|
||||
void motion(int x, int y) {
|
||||
float dx, dy;
|
||||
dx = (float)(x - ox);
|
||||
dy = (float)(y - oy);
|
||||
|
||||
if (displaySliders) {
|
||||
if (params->Motion(x, y)) {
|
||||
ox = x;
|
||||
oy = y;
|
||||
glutPostRedisplay();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
switch (mode) {
|
||||
case M_VIEW:
|
||||
if (buttonState == 3) {
|
||||
// left+middle = zoom
|
||||
camera_trans[2] += (dy / 100.0f) * 0.5f * fabs(camera_trans[2]);
|
||||
} else if (buttonState & 2) {
|
||||
// middle = translate
|
||||
camera_trans[0] += dx / 100.0f;
|
||||
camera_trans[1] -= dy / 100.0f;
|
||||
} else if (buttonState & 1) {
|
||||
// left = rotate
|
||||
camera_rot[0] += dy / 5.0f;
|
||||
camera_rot[1] += dx / 5.0f;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case M_MOVE: {
|
||||
float translateSpeed = 0.003f;
|
||||
float3 p = psystem->getColliderPos();
|
||||
|
||||
if (buttonState == 1) {
|
||||
float v[3], r[3];
|
||||
v[0] = dx * translateSpeed;
|
||||
v[1] = -dy * translateSpeed;
|
||||
v[2] = 0.0f;
|
||||
ixform(v, r, modelView);
|
||||
p.x += r[0];
|
||||
p.y += r[1];
|
||||
p.z += r[2];
|
||||
} else if (buttonState == 2) {
|
||||
float v[3], r[3];
|
||||
v[0] = 0.0f;
|
||||
v[1] = 0.0f;
|
||||
v[2] = dy * translateSpeed;
|
||||
ixform(v, r, modelView);
|
||||
p.x += r[0];
|
||||
p.y += r[1];
|
||||
p.z += r[2];
|
||||
}
|
||||
|
||||
psystem->setColliderPos(p);
|
||||
} break;
|
||||
}
|
||||
|
||||
ox = x;
|
||||
oy = y;
|
||||
|
||||
demoMode = false;
|
||||
idleCounter = 0;
|
||||
|
||||
glutPostRedisplay();
|
||||
}
|
||||
|
||||
// commented out to remove unused parameter warnings in Linux
|
||||
void key(unsigned char key, int /*x*/, int /*y*/) {
|
||||
switch (key) {
|
||||
case ' ':
|
||||
bPause = !bPause;
|
||||
break;
|
||||
|
||||
case 13:
|
||||
psystem->update(timestep);
|
||||
|
||||
if (renderer) {
|
||||
renderer->setVertexBuffer(psystem->getCurrentReadBuffer(),
|
||||
psystem->getNumParticles());
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case '\033':
|
||||
case 'q':
|
||||
#if defined(__APPLE__) || defined(MACOSX)
|
||||
exit(EXIT_SUCCESS);
|
||||
#else
|
||||
glutDestroyWindow(glutGetWindow());
|
||||
return;
|
||||
#endif
|
||||
case 'v':
|
||||
mode = M_VIEW;
|
||||
break;
|
||||
|
||||
case 'm':
|
||||
mode = M_MOVE;
|
||||
break;
|
||||
|
||||
case 'p':
|
||||
displayMode = (ParticleRenderer::DisplayMode)(
|
||||
(displayMode + 1) % ParticleRenderer::PARTICLE_NUM_MODES);
|
||||
break;
|
||||
|
||||
case 'd':
|
||||
psystem->dumpGrid();
|
||||
break;
|
||||
|
||||
case 'u':
|
||||
psystem->dumpParticles(0, numParticles - 1);
|
||||
break;
|
||||
|
||||
case 'r':
|
||||
displayEnabled = !displayEnabled;
|
||||
break;
|
||||
|
||||
case '1':
|
||||
psystem->reset(ParticleSystem::CONFIG_GRID);
|
||||
break;
|
||||
|
||||
case '2':
|
||||
psystem->reset(ParticleSystem::CONFIG_RANDOM);
|
||||
break;
|
||||
|
||||
case '3':
|
||||
addSphere();
|
||||
break;
|
||||
|
||||
case '4': {
|
||||
// shoot ball from camera
|
||||
float pr = psystem->getParticleRadius();
|
||||
float vel[4], velw[4], pos[4], posw[4];
|
||||
vel[0] = 0.0f;
|
||||
vel[1] = 0.0f;
|
||||
vel[2] = -0.05f;
|
||||
vel[3] = 0.0f;
|
||||
ixform(vel, velw, modelView);
|
||||
|
||||
pos[0] = 0.0f;
|
||||
pos[1] = 0.0f;
|
||||
pos[2] = -2.5f;
|
||||
pos[3] = 1.0;
|
||||
ixformPoint(pos, posw, modelView);
|
||||
posw[3] = 0.0f;
|
||||
|
||||
psystem->addSphere(0, posw, velw, ballr, pr * 2.0f);
|
||||
} break;
|
||||
|
||||
case 'w':
|
||||
wireframe = !wireframe;
|
||||
break;
|
||||
|
||||
case 'h':
|
||||
displaySliders = !displaySliders;
|
||||
break;
|
||||
}
|
||||
|
||||
demoMode = false;
|
||||
idleCounter = 0;
|
||||
glutPostRedisplay();
|
||||
}
|
||||
|
||||
void special(int k, int x, int y) {
|
||||
if (displaySliders) {
|
||||
params->Special(k, x, y);
|
||||
}
|
||||
|
||||
demoMode = false;
|
||||
idleCounter = 0;
|
||||
}
|
||||
|
||||
void idle(void) {
|
||||
if ((idleCounter++ > idleDelay) && (demoMode == false)) {
|
||||
demoMode = true;
|
||||
printf("Entering demo mode\n");
|
||||
}
|
||||
|
||||
if (demoMode) {
|
||||
camera_rot[1] += 0.1f;
|
||||
|
||||
if (demoCounter++ > 1000) {
|
||||
ballr = 10 + (rand() % 10);
|
||||
addSphere();
|
||||
demoCounter = 0;
|
||||
}
|
||||
}
|
||||
|
||||
glutPostRedisplay();
|
||||
}
|
||||
|
||||
void initParams() {
|
||||
if (g_refFile) {
|
||||
timestep = 0.0f;
|
||||
damping = 0.0f;
|
||||
gravity = 0.0f;
|
||||
ballr = 1;
|
||||
collideSpring = 0.0f;
|
||||
collideDamping = 0.0f;
|
||||
collideShear = 0.0f;
|
||||
collideAttraction = 0.0f;
|
||||
} else {
|
||||
// create a new parameter list
|
||||
params = new ParamListGL("misc");
|
||||
params->AddParam(
|
||||
new Param<float>("time step", timestep, 0.0f, 1.0f, 0.01f, ×tep));
|
||||
params->AddParam(
|
||||
new Param<float>("damping", damping, 0.0f, 1.0f, 0.001f, &damping));
|
||||
params->AddParam(
|
||||
new Param<float>("gravity", gravity, 0.0f, 0.001f, 0.0001f, &gravity));
|
||||
params->AddParam(new Param<int>("ball radius", ballr, 1, 20, 1, &ballr));
|
||||
|
||||
params->AddParam(new Param<float>("collide spring", collideSpring, 0.0f,
|
||||
1.0f, 0.001f, &collideSpring));
|
||||
params->AddParam(new Param<float>("collide damping", collideDamping, 0.0f,
|
||||
0.1f, 0.001f, &collideDamping));
|
||||
params->AddParam(new Param<float>("collide shear", collideShear, 0.0f, 0.1f,
|
||||
0.001f, &collideShear));
|
||||
params->AddParam(new Param<float>("collide attract", collideAttraction,
|
||||
0.0f, 0.1f, 0.001f, &collideAttraction));
|
||||
}
|
||||
}
|
||||
|
||||
void mainMenu(int i) { key((unsigned char)i, 0, 0); }
|
||||
|
||||
void initMenus() {
|
||||
glutCreateMenu(mainMenu);
|
||||
glutAddMenuEntry("Reset block [1]", '1');
|
||||
glutAddMenuEntry("Reset random [2]", '2');
|
||||
glutAddMenuEntry("Add sphere [3]", '3');
|
||||
glutAddMenuEntry("View mode [v]", 'v');
|
||||
glutAddMenuEntry("Move cursor mode [m]", 'm');
|
||||
glutAddMenuEntry("Toggle point rendering [p]", 'p');
|
||||
glutAddMenuEntry("Toggle animation [ ]", ' ');
|
||||
glutAddMenuEntry("Step animation [ret]", 13);
|
||||
glutAddMenuEntry("Toggle sliders [h]", 'h');
|
||||
glutAddMenuEntry("Quit (esc)", '\033');
|
||||
glutAttachMenu(GLUT_RIGHT_BUTTON);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Program main
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
int main(int argc, char **argv) {
|
||||
#if defined(__linux__)
|
||||
setenv("DISPLAY", ":0", 0);
|
||||
#endif
|
||||
|
||||
printf("%s Starting...\n\n", sSDKsample);
|
||||
|
||||
printf(
|
||||
"NOTE: The CUDA Samples are not meant for performance measurements. "
|
||||
"Results may vary when GPU Boost is enabled.\n\n");
|
||||
|
||||
numParticles = NUM_PARTICLES;
|
||||
uint gridDim = GRID_SIZE;
|
||||
numIterations = 0;
|
||||
|
||||
if (argc > 1) {
|
||||
if (checkCmdLineFlag(argc, (const char **)argv, "n")) {
|
||||
numParticles = getCmdLineArgumentInt(argc, (const char **)argv, "n");
|
||||
}
|
||||
|
||||
if (checkCmdLineFlag(argc, (const char **)argv, "grid")) {
|
||||
gridDim = getCmdLineArgumentInt(argc, (const char **)argv, "grid");
|
||||
}
|
||||
|
||||
if (checkCmdLineFlag(argc, (const char **)argv, "file")) {
|
||||
getCmdLineArgumentString(argc, (const char **)argv, "file", &g_refFile);
|
||||
fpsLimit = frameCheckNumber;
|
||||
numIterations = 1;
|
||||
}
|
||||
}
|
||||
|
||||
gridSize.x = gridSize.y = gridSize.z = gridDim;
|
||||
printf("grid: %d x %d x %d = %d cells\n", gridSize.x, gridSize.y, gridSize.z,
|
||||
gridSize.x * gridSize.y * gridSize.z);
|
||||
printf("particles: %d\n", numParticles);
|
||||
|
||||
bool benchmark =
|
||||
checkCmdLineFlag(argc, (const char **)argv, "benchmark") != 0;
|
||||
|
||||
if (checkCmdLineFlag(argc, (const char **)argv, "i")) {
|
||||
numIterations = getCmdLineArgumentInt(argc, (const char **)argv, "i");
|
||||
}
|
||||
|
||||
if (benchmark || g_refFile) {
|
||||
cudaInit(argc, argv);
|
||||
} else {
|
||||
if (checkCmdLineFlag(argc, (const char **)argv, "device")) {
|
||||
printf("[%s]\n", argv[0]);
|
||||
printf(" Does not explicitly support -device=n in OpenGL mode\n");
|
||||
printf(" To use -device=n, the sample must be running w/o OpenGL\n\n");
|
||||
printf(" > %s -device=n -file=<*.bin>\n", argv[0]);
|
||||
printf("exiting...\n");
|
||||
exit(EXIT_SUCCESS);
|
||||
}
|
||||
|
||||
initGL(&argc, argv);
|
||||
cudaInit(argc, argv);
|
||||
}
|
||||
|
||||
initParticleSystem(numParticles, gridSize, !benchmark && g_refFile == NULL);
|
||||
initParams();
|
||||
|
||||
if (benchmark || g_refFile) {
|
||||
if (numIterations <= 0) {
|
||||
numIterations = 300;
|
||||
}
|
||||
|
||||
runBenchmark(numIterations, argv[0]);
|
||||
} else {
|
||||
if (!g_refFile) {
|
||||
initMenus();
|
||||
}
|
||||
|
||||
glutDisplayFunc(display);
|
||||
glutReshapeFunc(reshape);
|
||||
glutMouseFunc(mouse);
|
||||
glutMotionFunc(motion);
|
||||
glutKeyboardFunc(key);
|
||||
glutSpecialFunc(special);
|
||||
glutIdleFunc(idle);
|
||||
|
||||
glutCloseFunc(cleanup);
|
||||
|
||||
glutMainLoop();
|
||||
}
|
||||
|
||||
if (psystem) {
|
||||
delete psystem;
|
||||
}
|
||||
|
||||
exit(g_TotalErrors > 0 ? EXIT_FAILURE : EXIT_SUCCESS);
|
||||
}
|
||||
58
Samples/particles/particles_kernel.cuh
Normal file
58
Samples/particles/particles_kernel.cuh
Normal file
@@ -0,0 +1,58 @@
|
||||
/* Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#ifndef PARTICLES_KERNEL_H
|
||||
#define PARTICLES_KERNEL_H
|
||||
|
||||
#include "vector_types.h"
|
||||
typedef unsigned int uint;
|
||||
|
||||
// simulation parameters
|
||||
struct SimParams {
|
||||
float3 colliderPos;
|
||||
float colliderRadius;
|
||||
|
||||
float3 gravity;
|
||||
float globalDamping;
|
||||
float particleRadius;
|
||||
|
||||
uint3 gridSize;
|
||||
uint numCells;
|
||||
float3 worldOrigin;
|
||||
float3 cellSize;
|
||||
|
||||
uint numBodies;
|
||||
uint maxParticlesPerCell;
|
||||
|
||||
float spring;
|
||||
float damping;
|
||||
float shear;
|
||||
float attraction;
|
||||
float boundaryDamping;
|
||||
};
|
||||
|
||||
#endif
|
||||
315
Samples/particles/particles_kernel_impl.cuh
Normal file
315
Samples/particles/particles_kernel_impl.cuh
Normal file
@@ -0,0 +1,315 @@
|
||||
/* Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
/*
|
||||
* CUDA particle system kernel code.
|
||||
*/
|
||||
|
||||
#ifndef _PARTICLES_KERNEL_H_
|
||||
#define _PARTICLES_KERNEL_H_
|
||||
|
||||
#include <stdio.h>
|
||||
#include <math.h>
|
||||
#include <cooperative_groups.h>
|
||||
|
||||
namespace cg = cooperative_groups;
|
||||
#include "helper_math.h"
|
||||
#include "math_constants.h"
|
||||
#include "particles_kernel.cuh"
|
||||
|
||||
// simulation parameters in constant memory
|
||||
__constant__ SimParams params;
|
||||
|
||||
struct integrate_functor {
|
||||
float deltaTime;
|
||||
|
||||
__host__ __device__ integrate_functor(float delta_time)
|
||||
: deltaTime(delta_time) {}
|
||||
|
||||
template <typename Tuple>
|
||||
__device__ void operator()(Tuple t) {
|
||||
volatile float4 posData = thrust::get<0>(t);
|
||||
volatile float4 velData = thrust::get<1>(t);
|
||||
float3 pos = make_float3(posData.x, posData.y, posData.z);
|
||||
float3 vel = make_float3(velData.x, velData.y, velData.z);
|
||||
|
||||
vel += params.gravity * deltaTime;
|
||||
vel *= params.globalDamping;
|
||||
|
||||
// new position = old position + velocity * deltaTime
|
||||
pos += vel * deltaTime;
|
||||
|
||||
// set this to zero to disable collisions with cube sides
|
||||
#if 1
|
||||
|
||||
if (pos.x > 1.0f - params.particleRadius) {
|
||||
pos.x = 1.0f - params.particleRadius;
|
||||
vel.x *= params.boundaryDamping;
|
||||
}
|
||||
|
||||
if (pos.x < -1.0f + params.particleRadius) {
|
||||
pos.x = -1.0f + params.particleRadius;
|
||||
vel.x *= params.boundaryDamping;
|
||||
}
|
||||
|
||||
if (pos.y > 1.0f - params.particleRadius) {
|
||||
pos.y = 1.0f - params.particleRadius;
|
||||
vel.y *= params.boundaryDamping;
|
||||
}
|
||||
|
||||
if (pos.z > 1.0f - params.particleRadius) {
|
||||
pos.z = 1.0f - params.particleRadius;
|
||||
vel.z *= params.boundaryDamping;
|
||||
}
|
||||
|
||||
if (pos.z < -1.0f + params.particleRadius) {
|
||||
pos.z = -1.0f + params.particleRadius;
|
||||
vel.z *= params.boundaryDamping;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
if (pos.y < -1.0f + params.particleRadius) {
|
||||
pos.y = -1.0f + params.particleRadius;
|
||||
vel.y *= params.boundaryDamping;
|
||||
}
|
||||
|
||||
// store new position and velocity
|
||||
thrust::get<0>(t) = make_float4(pos, posData.w);
|
||||
thrust::get<1>(t) = make_float4(vel, velData.w);
|
||||
}
|
||||
};
|
||||
|
||||
// calculate position in uniform grid
|
||||
__device__ int3 calcGridPos(float3 p) {
|
||||
int3 gridPos;
|
||||
gridPos.x = floorf((p.x - params.worldOrigin.x) / params.cellSize.x);
|
||||
gridPos.y = floorf((p.y - params.worldOrigin.y) / params.cellSize.y);
|
||||
gridPos.z = floorf((p.z - params.worldOrigin.z) / params.cellSize.z);
|
||||
return gridPos;
|
||||
}
|
||||
|
||||
// calculate address in grid from position (clamping to edges)
|
||||
__device__ uint calcGridHash(int3 gridPos) {
|
||||
gridPos.x = gridPos.x &
|
||||
(params.gridSize.x - 1); // wrap grid, assumes size is power of 2
|
||||
gridPos.y = gridPos.y & (params.gridSize.y - 1);
|
||||
gridPos.z = gridPos.z & (params.gridSize.z - 1);
|
||||
return __umul24(__umul24(gridPos.z, params.gridSize.y), params.gridSize.x) +
|
||||
__umul24(gridPos.y, params.gridSize.x) + gridPos.x;
|
||||
}
|
||||
|
||||
// calculate grid hash value for each particle
|
||||
__global__ void calcHashD(uint *gridParticleHash, // output
|
||||
uint *gridParticleIndex, // output
|
||||
float4 *pos, // input: positions
|
||||
uint numParticles) {
|
||||
uint index = __umul24(blockIdx.x, blockDim.x) + threadIdx.x;
|
||||
|
||||
if (index >= numParticles) return;
|
||||
|
||||
volatile float4 p = pos[index];
|
||||
|
||||
// get address in grid
|
||||
int3 gridPos = calcGridPos(make_float3(p.x, p.y, p.z));
|
||||
uint hash = calcGridHash(gridPos);
|
||||
|
||||
// store grid hash and particle index
|
||||
gridParticleHash[index] = hash;
|
||||
gridParticleIndex[index] = index;
|
||||
}
|
||||
|
||||
// rearrange particle data into sorted order, and find the start of each cell
|
||||
// in the sorted hash array
|
||||
__global__ void reorderDataAndFindCellStartD(
|
||||
uint *cellStart, // output: cell start index
|
||||
uint *cellEnd, // output: cell end index
|
||||
float4 *sortedPos, // output: sorted positions
|
||||
float4 *sortedVel, // output: sorted velocities
|
||||
uint *gridParticleHash, // input: sorted grid hashes
|
||||
uint *gridParticleIndex, // input: sorted particle indices
|
||||
float4 *oldPos, // input: sorted position array
|
||||
float4 *oldVel, // input: sorted velocity array
|
||||
uint numParticles) {
|
||||
// Handle to thread block group
|
||||
cg::thread_block cta = cg::this_thread_block();
|
||||
extern __shared__ uint sharedHash[]; // blockSize + 1 elements
|
||||
uint index = __umul24(blockIdx.x, blockDim.x) + threadIdx.x;
|
||||
|
||||
uint hash;
|
||||
|
||||
// handle case when no. of particles not multiple of block size
|
||||
if (index < numParticles) {
|
||||
hash = gridParticleHash[index];
|
||||
|
||||
// Load hash data into shared memory so that we can look
|
||||
// at neighboring particle's hash value without loading
|
||||
// two hash values per thread
|
||||
sharedHash[threadIdx.x + 1] = hash;
|
||||
|
||||
if (index > 0 && threadIdx.x == 0) {
|
||||
// first thread in block must load neighbor particle hash
|
||||
sharedHash[0] = gridParticleHash[index - 1];
|
||||
}
|
||||
}
|
||||
|
||||
cg::sync(cta);
|
||||
|
||||
if (index < numParticles) {
|
||||
// If this particle has a different cell index to the previous
|
||||
// particle then it must be the first particle in the cell,
|
||||
// so store the index of this particle in the cell.
|
||||
// As it isn't the first particle, it must also be the cell end of
|
||||
// the previous particle's cell
|
||||
|
||||
if (index == 0 || hash != sharedHash[threadIdx.x]) {
|
||||
cellStart[hash] = index;
|
||||
|
||||
if (index > 0) cellEnd[sharedHash[threadIdx.x]] = index;
|
||||
}
|
||||
|
||||
if (index == numParticles - 1) {
|
||||
cellEnd[hash] = index + 1;
|
||||
}
|
||||
|
||||
// Now use the sorted index to reorder the pos and vel data
|
||||
uint sortedIndex = gridParticleIndex[index];
|
||||
float4 pos = oldPos[sortedIndex];
|
||||
float4 vel = oldVel[sortedIndex];
|
||||
|
||||
sortedPos[index] = pos;
|
||||
sortedVel[index] = vel;
|
||||
}
|
||||
}
|
||||
|
||||
// collide two spheres using DEM method
|
||||
__device__ float3 collideSpheres(float3 posA, float3 posB, float3 velA,
|
||||
float3 velB, float radiusA, float radiusB,
|
||||
float attraction) {
|
||||
// calculate relative position
|
||||
float3 relPos = posB - posA;
|
||||
|
||||
float dist = length(relPos);
|
||||
float collideDist = radiusA + radiusB;
|
||||
|
||||
float3 force = make_float3(0.0f);
|
||||
|
||||
if (dist < collideDist) {
|
||||
float3 norm = relPos / dist;
|
||||
|
||||
// relative velocity
|
||||
float3 relVel = velB - velA;
|
||||
|
||||
// relative tangential velocity
|
||||
float3 tanVel = relVel - (dot(relVel, norm) * norm);
|
||||
|
||||
// spring force
|
||||
force = -params.spring * (collideDist - dist) * norm;
|
||||
// dashpot (damping) force
|
||||
force += params.damping * relVel;
|
||||
// tangential shear force
|
||||
force += params.shear * tanVel;
|
||||
// attraction
|
||||
force += attraction * relPos;
|
||||
}
|
||||
|
||||
return force;
|
||||
}
|
||||
|
||||
// collide a particle against all other particles in a given cell
|
||||
__device__ float3 collideCell(int3 gridPos, uint index, float3 pos, float3 vel,
|
||||
float4 *oldPos, float4 *oldVel, uint *cellStart,
|
||||
uint *cellEnd) {
|
||||
uint gridHash = calcGridHash(gridPos);
|
||||
|
||||
// get start of bucket for this cell
|
||||
uint startIndex = cellStart[gridHash];
|
||||
|
||||
float3 force = make_float3(0.0f);
|
||||
|
||||
if (startIndex != 0xffffffff) // cell is not empty
|
||||
{
|
||||
// iterate over particles in this cell
|
||||
uint endIndex = cellEnd[gridHash];
|
||||
|
||||
for (uint j = startIndex; j < endIndex; j++) {
|
||||
if (j != index) // check not colliding with self
|
||||
{
|
||||
float3 pos2 = make_float3(oldPos[j]);
|
||||
float3 vel2 = make_float3(oldVel[j]);
|
||||
|
||||
// collide two spheres
|
||||
force += collideSpheres(pos, pos2, vel, vel2, params.particleRadius,
|
||||
params.particleRadius, params.attraction);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return force;
|
||||
}
|
||||
|
||||
__global__ void collideD(
|
||||
float4 *newVel, // output: new velocity
|
||||
float4 *oldPos, // input: sorted positions
|
||||
float4 *oldVel, // input: sorted velocities
|
||||
uint *gridParticleIndex, // input: sorted particle indices
|
||||
uint *cellStart, uint *cellEnd, uint numParticles) {
|
||||
uint index = __mul24(blockIdx.x, blockDim.x) + threadIdx.x;
|
||||
|
||||
if (index >= numParticles) return;
|
||||
|
||||
// read particle data from sorted arrays
|
||||
float3 pos = make_float3(oldPos[index]);
|
||||
float3 vel = make_float3(oldVel[index]);
|
||||
|
||||
// get address in grid
|
||||
int3 gridPos = calcGridPos(pos);
|
||||
|
||||
// examine neighbouring cells
|
||||
float3 force = make_float3(0.0f);
|
||||
|
||||
for (int z = -1; z <= 1; z++) {
|
||||
for (int y = -1; y <= 1; y++) {
|
||||
for (int x = -1; x <= 1; x++) {
|
||||
int3 neighbourPos = gridPos + make_int3(x, y, z);
|
||||
force += collideCell(neighbourPos, index, pos, vel, oldPos, oldVel,
|
||||
cellStart, cellEnd);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// collide with cursor sphere
|
||||
force += collideSpheres(pos, params.colliderPos, vel,
|
||||
make_float3(0.0f, 0.0f, 0.0f), params.particleRadius,
|
||||
params.colliderRadius, 0.0f);
|
||||
|
||||
// write new velocity back to original unsorted location
|
||||
uint originalIndex = gridParticleIndex[index];
|
||||
newVel[originalIndex] = make_float4(vel + force, 0.0f);
|
||||
}
|
||||
|
||||
#endif
|
||||
20
Samples/particles/particles_vs2017.sln
Normal file
20
Samples/particles/particles_vs2017.sln
Normal file
@@ -0,0 +1,20 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio 2017
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "particles", "particles_vs2017.vcxproj", "{997E0757-EA74-4A4E-A0FC-47D8C8831A15}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|x64 = Debug|x64
|
||||
Release|x64 = Release|x64
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{997E0757-EA74-4A4E-A0FC-47D8C8831A15}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{997E0757-EA74-4A4E-A0FC-47D8C8831A15}.Debug|x64.Build.0 = Debug|x64
|
||||
{997E0757-EA74-4A4E-A0FC-47D8C8831A15}.Release|x64.ActiveCfg = Release|x64
|
||||
{997E0757-EA74-4A4E-A0FC-47D8C8831A15}.Release|x64.Build.0 = Release|x64
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
135
Samples/particles/particles_vs2017.vcxproj
Normal file
135
Samples/particles/particles_vs2017.vcxproj
Normal file
@@ -0,0 +1,135 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<CUDAPropsPath Condition="'$(CUDAPropsPath)'==''">$(VCTargetsPath)\BuildCustomizations</CUDAPropsPath>
|
||||
</PropertyGroup>
|
||||
<ItemGroup Label="ProjectConfigurations">
|
||||
<ProjectConfiguration Include="Debug|x64">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|x64">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
</ItemGroup>
|
||||
<PropertyGroup Label="Globals">
|
||||
<ProjectGuid>{997E0757-EA74-4A4E-A0FC-47D8C8831A15}</ProjectGuid>
|
||||
<RootNamespace>particles_vs2017</RootNamespace>
|
||||
<ProjectName>particles</ProjectName>
|
||||
<CudaToolkitCustomDir />
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(WindowsTargetPlatformVersion)'==''">
|
||||
<LatestTargetPlatformVersion>$([Microsoft.Build.Utilities.ToolLocationHelper]::GetLatestSDKTargetPlatformVersion('Windows', '10.0'))</LatestTargetPlatformVersion>
|
||||
<WindowsTargetPlatformVersion Condition="'$(WindowsTargetPlatformVersion)' == ''">$(LatestTargetPlatformVersion)</WindowsTargetPlatformVersion>
|
||||
<TargetPlatformVersion>$(WindowsTargetPlatformVersion)</TargetPlatformVersion>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
|
||||
<PropertyGroup>
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
<PlatformToolset>v141</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)'=='Debug'">
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)'=='Release'">
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||
<ImportGroup Label="ExtensionSettings">
|
||||
<Import Project="$(CUDAPropsPath)\CUDA 11.5.props" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Label="PropertySheets">
|
||||
<Import Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" />
|
||||
</ImportGroup>
|
||||
<PropertyGroup Label="UserMacros" />
|
||||
<PropertyGroup>
|
||||
<IntDir>$(Platform)/$(Configuration)/</IntDir>
|
||||
<IncludePath>$(IncludePath)</IncludePath>
|
||||
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
|
||||
<CodeAnalysisRules />
|
||||
<CodeAnalysisRuleAssemblies />
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Platform)'=='x64'">
|
||||
<OutDir>../../bin/win64/$(Configuration)/</OutDir>
|
||||
</PropertyGroup>
|
||||
<ItemDefinitionGroup>
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<PreprocessorDefinitions>WIN32;_MBCS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AdditionalIncludeDirectories>./;$(CudaToolkitDir)/include;../../Common;</AdditionalIncludeDirectories>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<AdditionalDependencies>cudart_static.lib;freeglut.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
<AdditionalLibraryDirectories>$(CudaToolkitLibDir);../../Common/lib/$(PlatformName);</AdditionalLibraryDirectories>
|
||||
<OutputFile>$(OutDir)/particles.exe</OutputFile>
|
||||
</Link>
|
||||
<CudaCompile>
|
||||
<CodeGeneration>compute_35,sm_35;compute_37,sm_37;compute_50,sm_50;compute_52,sm_52;compute_60,sm_60;compute_61,sm_61;compute_70,sm_70;compute_75,sm_75;compute_80,sm_80;compute_86,sm_86;</CodeGeneration>
|
||||
<AdditionalOptions>-Xcompiler "/wd 4819" %(AdditionalOptions)</AdditionalOptions>
|
||||
<Include>./;../../Common</Include>
|
||||
<Defines>WIN32</Defines>
|
||||
<AdditionalOptions>--threads 0</AdditionalOptions>
|
||||
</CudaCompile>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)'=='Debug'">
|
||||
<ClCompile>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<LinkTimeCodeGeneration>Default</LinkTimeCodeGeneration>
|
||||
</Link>
|
||||
<CudaCompile>
|
||||
<Runtime>MTd</Runtime>
|
||||
<TargetMachinePlatform>64</TargetMachinePlatform>
|
||||
</CudaCompile>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)'=='Release'">
|
||||
<ClCompile>
|
||||
<Optimization>MaxSpeed</Optimization>
|
||||
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<GenerateDebugInformation>false</GenerateDebugInformation>
|
||||
<LinkTimeCodeGeneration>UseLinkTimeCodeGeneration</LinkTimeCodeGeneration>
|
||||
</Link>
|
||||
<CudaCompile>
|
||||
<Runtime>MT</Runtime>
|
||||
<TargetMachinePlatform>64</TargetMachinePlatform>
|
||||
</CudaCompile>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Platform)'=='Win32'">
|
||||
<Link>
|
||||
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Platform)'=='x64'">
|
||||
<Link>
|
||||
<AdditionalDependencies>glew64.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="particleSystem.cpp" />
|
||||
<CudaCompile Include="particleSystem_cuda.cu" />
|
||||
<ClCompile Include="particles.cpp" />
|
||||
<ClCompile Include="render_particles.cpp" />
|
||||
<ClCompile Include="shaders.cpp" />
|
||||
<ClInclude Include="particleSystem.h" />
|
||||
<ClInclude Include="render_particles.h" />
|
||||
<ClInclude Include="shaders.h" />
|
||||
<ClInclude Include="..\..\Common\param.h" />
|
||||
<ClInclude Include="..\..\Common\paramgl.h" />
|
||||
<ClInclude Include="..\..\Common\rendercheck_gl.h" />
|
||||
<None Include="particleSystem.cuh" />
|
||||
<None Include="particles_kernel.cuh" />
|
||||
<None Include="particles_kernel_impl.cuh" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
<Import Project="$(CUDAPropsPath)\CUDA 11.5.targets" />
|
||||
</ImportGroup>
|
||||
</Project>
|
||||
20
Samples/particles/particles_vs2019.sln
Normal file
20
Samples/particles/particles_vs2019.sln
Normal file
@@ -0,0 +1,20 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio 2019
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "particles", "particles_vs2019.vcxproj", "{997E0757-EA74-4A4E-A0FC-47D8C8831A15}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|x64 = Debug|x64
|
||||
Release|x64 = Release|x64
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{997E0757-EA74-4A4E-A0FC-47D8C8831A15}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{997E0757-EA74-4A4E-A0FC-47D8C8831A15}.Debug|x64.Build.0 = Debug|x64
|
||||
{997E0757-EA74-4A4E-A0FC-47D8C8831A15}.Release|x64.ActiveCfg = Release|x64
|
||||
{997E0757-EA74-4A4E-A0FC-47D8C8831A15}.Release|x64.Build.0 = Release|x64
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
131
Samples/particles/particles_vs2019.vcxproj
Normal file
131
Samples/particles/particles_vs2019.vcxproj
Normal file
@@ -0,0 +1,131 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<CUDAPropsPath Condition="'$(CUDAPropsPath)'==''">$(VCTargetsPath)\BuildCustomizations</CUDAPropsPath>
|
||||
</PropertyGroup>
|
||||
<ItemGroup Label="ProjectConfigurations">
|
||||
<ProjectConfiguration Include="Debug|x64">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|x64">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
</ItemGroup>
|
||||
<PropertyGroup Label="Globals">
|
||||
<ProjectGuid>{997E0757-EA74-4A4E-A0FC-47D8C8831A15}</ProjectGuid>
|
||||
<RootNamespace>particles_vs2019</RootNamespace>
|
||||
<ProjectName>particles</ProjectName>
|
||||
<CudaToolkitCustomDir />
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
|
||||
<PropertyGroup>
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
<PlatformToolset>v142</PlatformToolset>
|
||||
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)'=='Debug'">
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)'=='Release'">
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||
<ImportGroup Label="ExtensionSettings">
|
||||
<Import Project="$(CUDAPropsPath)\CUDA 11.5.props" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Label="PropertySheets">
|
||||
<Import Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" />
|
||||
</ImportGroup>
|
||||
<PropertyGroup Label="UserMacros" />
|
||||
<PropertyGroup>
|
||||
<IntDir>$(Platform)/$(Configuration)/</IntDir>
|
||||
<IncludePath>$(IncludePath)</IncludePath>
|
||||
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
|
||||
<CodeAnalysisRules />
|
||||
<CodeAnalysisRuleAssemblies />
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Platform)'=='x64'">
|
||||
<OutDir>../../bin/win64/$(Configuration)/</OutDir>
|
||||
</PropertyGroup>
|
||||
<ItemDefinitionGroup>
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<PreprocessorDefinitions>WIN32;_MBCS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AdditionalIncludeDirectories>./;$(CudaToolkitDir)/include;../../Common;</AdditionalIncludeDirectories>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<AdditionalDependencies>cudart_static.lib;freeglut.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
<AdditionalLibraryDirectories>$(CudaToolkitLibDir);../../Common/lib/$(PlatformName);</AdditionalLibraryDirectories>
|
||||
<OutputFile>$(OutDir)/particles.exe</OutputFile>
|
||||
</Link>
|
||||
<CudaCompile>
|
||||
<CodeGeneration>compute_35,sm_35;compute_37,sm_37;compute_50,sm_50;compute_52,sm_52;compute_60,sm_60;compute_61,sm_61;compute_70,sm_70;compute_75,sm_75;compute_80,sm_80;compute_86,sm_86;</CodeGeneration>
|
||||
<AdditionalOptions>-Xcompiler "/wd 4819" %(AdditionalOptions)</AdditionalOptions>
|
||||
<Include>./;../../Common</Include>
|
||||
<Defines>WIN32</Defines>
|
||||
<AdditionalOptions>--threads 0</AdditionalOptions>
|
||||
</CudaCompile>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)'=='Debug'">
|
||||
<ClCompile>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<LinkTimeCodeGeneration>Default</LinkTimeCodeGeneration>
|
||||
</Link>
|
||||
<CudaCompile>
|
||||
<Runtime>MTd</Runtime>
|
||||
<TargetMachinePlatform>64</TargetMachinePlatform>
|
||||
</CudaCompile>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)'=='Release'">
|
||||
<ClCompile>
|
||||
<Optimization>MaxSpeed</Optimization>
|
||||
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<GenerateDebugInformation>false</GenerateDebugInformation>
|
||||
<LinkTimeCodeGeneration>UseLinkTimeCodeGeneration</LinkTimeCodeGeneration>
|
||||
</Link>
|
||||
<CudaCompile>
|
||||
<Runtime>MT</Runtime>
|
||||
<TargetMachinePlatform>64</TargetMachinePlatform>
|
||||
</CudaCompile>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Platform)'=='Win32'">
|
||||
<Link>
|
||||
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Platform)'=='x64'">
|
||||
<Link>
|
||||
<AdditionalDependencies>glew64.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="particleSystem.cpp" />
|
||||
<CudaCompile Include="particleSystem_cuda.cu" />
|
||||
<ClCompile Include="particles.cpp" />
|
||||
<ClCompile Include="render_particles.cpp" />
|
||||
<ClCompile Include="shaders.cpp" />
|
||||
<ClInclude Include="particleSystem.h" />
|
||||
<ClInclude Include="render_particles.h" />
|
||||
<ClInclude Include="shaders.h" />
|
||||
<ClInclude Include="..\..\Common\param.h" />
|
||||
<ClInclude Include="..\..\Common\paramgl.h" />
|
||||
<ClInclude Include="..\..\Common\rendercheck_gl.h" />
|
||||
<None Include="particleSystem.cuh" />
|
||||
<None Include="particles_kernel.cuh" />
|
||||
<None Include="particles_kernel_impl.cuh" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
<Import Project="$(CUDAPropsPath)\CUDA 11.5.targets" />
|
||||
</ImportGroup>
|
||||
</Project>
|
||||
168
Samples/particles/render_particles.cpp
Normal file
168
Samples/particles/render_particles.cpp
Normal file
@@ -0,0 +1,168 @@
|
||||
/* Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#include <math.h>
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
|
||||
// OpenGL Graphics includes
|
||||
#define HELPERGL_EXTERN_GL_FUNC_IMPLEMENTATION
|
||||
#include <helper_gl.h>
|
||||
|
||||
#include "render_particles.h"
|
||||
#include "shaders.h"
|
||||
|
||||
#ifndef M_PI
|
||||
#define M_PI 3.1415926535897932384626433832795
|
||||
#endif
|
||||
|
||||
ParticleRenderer::ParticleRenderer()
|
||||
: m_pos(0),
|
||||
m_numParticles(0),
|
||||
m_pointSize(1.0f),
|
||||
m_particleRadius(0.125f * 0.5f),
|
||||
m_program(0),
|
||||
m_vbo(0),
|
||||
m_colorVBO(0) {
|
||||
_initGL();
|
||||
}
|
||||
|
||||
ParticleRenderer::~ParticleRenderer() { m_pos = 0; }
|
||||
|
||||
void ParticleRenderer::setPositions(float *pos, int numParticles) {
|
||||
m_pos = pos;
|
||||
m_numParticles = numParticles;
|
||||
}
|
||||
|
||||
void ParticleRenderer::setVertexBuffer(unsigned int vbo, int numParticles) {
|
||||
m_vbo = vbo;
|
||||
m_numParticles = numParticles;
|
||||
}
|
||||
|
||||
void ParticleRenderer::_drawPoints() {
|
||||
if (!m_vbo) {
|
||||
glBegin(GL_POINTS);
|
||||
{
|
||||
int k = 0;
|
||||
|
||||
for (int i = 0; i < m_numParticles; ++i) {
|
||||
glVertex3fv(&m_pos[k]);
|
||||
k += 4;
|
||||
}
|
||||
}
|
||||
glEnd();
|
||||
} else {
|
||||
glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
|
||||
glVertexPointer(4, GL_FLOAT, 0, 0);
|
||||
glEnableClientState(GL_VERTEX_ARRAY);
|
||||
|
||||
if (m_colorVBO) {
|
||||
glBindBuffer(GL_ARRAY_BUFFER, m_colorVBO);
|
||||
glColorPointer(4, GL_FLOAT, 0, 0);
|
||||
glEnableClientState(GL_COLOR_ARRAY);
|
||||
}
|
||||
|
||||
glDrawArrays(GL_POINTS, 0, m_numParticles);
|
||||
|
||||
glBindBuffer(GL_ARRAY_BUFFER, 0);
|
||||
glDisableClientState(GL_VERTEX_ARRAY);
|
||||
glDisableClientState(GL_COLOR_ARRAY);
|
||||
}
|
||||
}
|
||||
|
||||
void ParticleRenderer::display(DisplayMode mode /* = PARTICLE_POINTS */) {
|
||||
switch (mode) {
|
||||
case PARTICLE_POINTS:
|
||||
glColor3f(1, 1, 1);
|
||||
glPointSize(m_pointSize);
|
||||
_drawPoints();
|
||||
break;
|
||||
|
||||
default:
|
||||
case PARTICLE_SPHERES:
|
||||
glEnable(GL_POINT_SPRITE_ARB);
|
||||
glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
|
||||
glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
|
||||
glDepthMask(GL_TRUE);
|
||||
glEnable(GL_DEPTH_TEST);
|
||||
|
||||
glUseProgram(m_program);
|
||||
glUniform1f(glGetUniformLocation(m_program, "pointScale"),
|
||||
m_window_h / tanf(m_fov * 0.5f * (float)M_PI / 180.0f));
|
||||
glUniform1f(glGetUniformLocation(m_program, "pointRadius"),
|
||||
m_particleRadius);
|
||||
|
||||
glColor3f(1, 1, 1);
|
||||
_drawPoints();
|
||||
|
||||
glUseProgram(0);
|
||||
glDisable(GL_POINT_SPRITE_ARB);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
GLuint ParticleRenderer::_compileProgram(const char *vsource,
|
||||
const char *fsource) {
|
||||
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
|
||||
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
|
||||
|
||||
glShaderSource(vertexShader, 1, &vsource, 0);
|
||||
glShaderSource(fragmentShader, 1, &fsource, 0);
|
||||
|
||||
glCompileShader(vertexShader);
|
||||
glCompileShader(fragmentShader);
|
||||
|
||||
GLuint program = glCreateProgram();
|
||||
|
||||
glAttachShader(program, vertexShader);
|
||||
glAttachShader(program, fragmentShader);
|
||||
|
||||
glLinkProgram(program);
|
||||
|
||||
// check if program linked
|
||||
GLint success = 0;
|
||||
glGetProgramiv(program, GL_LINK_STATUS, &success);
|
||||
|
||||
if (!success) {
|
||||
char temp[256];
|
||||
glGetProgramInfoLog(program, 256, 0, temp);
|
||||
printf("Failed to link program:\n%s\n", temp);
|
||||
glDeleteProgram(program);
|
||||
program = 0;
|
||||
}
|
||||
|
||||
return program;
|
||||
}
|
||||
|
||||
void ParticleRenderer::_initGL() {
|
||||
m_program = _compileProgram(vertexShader, spherePixelShader);
|
||||
|
||||
#if !defined(__APPLE__) && !defined(MACOSX)
|
||||
glClampColorARB(GL_CLAMP_VERTEX_COLOR_ARB, GL_FALSE);
|
||||
glClampColorARB(GL_CLAMP_FRAGMENT_COLOR_ARB, GL_FALSE);
|
||||
#endif
|
||||
}
|
||||
73
Samples/particles/render_particles.h
Normal file
73
Samples/particles/render_particles.h
Normal file
@@ -0,0 +1,73 @@
|
||||
/* Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#ifndef __RENDER_PARTICLES__
|
||||
#define __RENDER_PARTICLES__
|
||||
|
||||
class ParticleRenderer {
|
||||
public:
|
||||
ParticleRenderer();
|
||||
~ParticleRenderer();
|
||||
|
||||
void setPositions(float *pos, int numParticles);
|
||||
void setVertexBuffer(unsigned int vbo, int numParticles);
|
||||
void setColorBuffer(unsigned int vbo) { m_colorVBO = vbo; }
|
||||
|
||||
enum DisplayMode { PARTICLE_POINTS, PARTICLE_SPHERES, PARTICLE_NUM_MODES };
|
||||
|
||||
void display(DisplayMode mode = PARTICLE_POINTS);
|
||||
void displayGrid();
|
||||
|
||||
void setPointSize(float size) { m_pointSize = size; }
|
||||
void setParticleRadius(float r) { m_particleRadius = r; }
|
||||
void setFOV(float fov) { m_fov = fov; }
|
||||
void setWindowSize(int w, int h) {
|
||||
m_window_w = w;
|
||||
m_window_h = h;
|
||||
}
|
||||
|
||||
protected: // methods
|
||||
void _initGL();
|
||||
void _drawPoints();
|
||||
GLuint _compileProgram(const char *vsource, const char *fsource);
|
||||
|
||||
protected: // data
|
||||
float *m_pos;
|
||||
int m_numParticles;
|
||||
|
||||
float m_pointSize;
|
||||
float m_particleRadius;
|
||||
float m_fov;
|
||||
int m_window_w, m_window_h;
|
||||
|
||||
GLuint m_program;
|
||||
|
||||
GLuint m_vbo;
|
||||
GLuint m_colorVBO;
|
||||
};
|
||||
|
||||
#endif //__ RENDER_PARTICLES__
|
||||
68
Samples/particles/shaders.cpp
Normal file
68
Samples/particles/shaders.cpp
Normal file
@@ -0,0 +1,68 @@
|
||||
/* Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#define STRINGIFY(A) #A
|
||||
|
||||
// vertex shader
|
||||
const char *vertexShader = STRINGIFY(
|
||||
uniform float pointRadius; // point size in world space
|
||||
uniform float pointScale; // scale to calculate size in pixels
|
||||
uniform float densityScale;
|
||||
uniform float densityOffset;
|
||||
void main()
|
||||
{
|
||||
// calculate window-space point size
|
||||
vec3 posEye = vec3(gl_ModelViewMatrix * vec4(gl_Vertex.xyz, 1.0));
|
||||
float dist = length(posEye);
|
||||
gl_PointSize = pointRadius * (pointScale / dist);
|
||||
|
||||
gl_TexCoord[0] = gl_MultiTexCoord0;
|
||||
gl_Position = gl_ModelViewProjectionMatrix * vec4(gl_Vertex.xyz, 1.0);
|
||||
|
||||
gl_FrontColor = gl_Color;
|
||||
});
|
||||
|
||||
// pixel shader for rendering points as shaded spheres
|
||||
const char *spherePixelShader = STRINGIFY(
|
||||
void main()
|
||||
{
|
||||
const vec3 lightDir = vec3(0.577, 0.577, 0.577);
|
||||
|
||||
// calculate normal from texture coordinates
|
||||
vec3 N;
|
||||
N.xy = gl_TexCoord[0].xy*vec2(2.0, -2.0) + vec2(-1.0, 1.0);
|
||||
float mag = dot(N.xy, N.xy);
|
||||
|
||||
if (mag > 1.0) discard; // kill pixels outside circle
|
||||
|
||||
N.z = sqrt(1.0-mag);
|
||||
|
||||
// calculate lighting
|
||||
float diffuse = max(0.0, dot(lightDir, N));
|
||||
|
||||
gl_FragColor = gl_Color * diffuse;
|
||||
});
|
||||
29
Samples/particles/shaders.h
Normal file
29
Samples/particles/shaders.h
Normal file
@@ -0,0 +1,29 @@
|
||||
/* Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* * Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of NVIDIA CORPORATION nor the names of its
|
||||
* contributors may be used to endorse or promote products derived
|
||||
* from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
|
||||
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
|
||||
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
extern const char *vertexShader;
|
||||
extern const char *spherePixelShader;
|
||||
Reference in New Issue
Block a user