CUDA 13.2 samples update (#432)

- Added Python samples for CUDA Python 1.0 release
- Renamed top-level `Samples` directory to `cpp` to accommodate Python samples.
This commit is contained in:
Dheemanth
2026-05-13 15:13:18 -07:00
committed by GitHub
parent a4526d5229
commit aeab82ff30
2072 changed files with 15077 additions and 1970 deletions

View 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
}

View File

@@ -0,0 +1,7 @@
{
"recommendations": [
"nvidia.nsight-vscode-edition",
"ms-vscode.cpptools",
"ms-vscode.makefile-tools"
]
}

View File

@@ -0,0 +1,96 @@
cmake_minimum_required(VERSION 3.20)
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/Modules")
project(particles LANGUAGES C CXX CUDA)
find_package(CUDAToolkit REQUIRED)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
set(CMAKE_CUDA_ARCHITECTURES 75 80 86 87 89 90 100 110 120)
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -Wno-deprecated-gpu-targets")
if(ENABLE_CUDA_DEBUG)
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -G") # enable cuda-gdb (may significantly affect performance on some targets)
else()
set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -lineinfo") # add line information to all builds for debug tools (exclusive to -G option)
endif()
# Include directories and libraries
include_directories(../../../Common)
if(WIN32)
set(PC_GLUT_INCLUDE_DIRS "${CMAKE_CURRENT_SOURCE_DIR}/../../../Common")
set(PC_GLUT_LIBRARY_DIRS "${CMAKE_CURRENT_SOURCE_DIR}/../../../Common/lib/x64")
# The GLEW library built on Windows on Arm system is named as glew32.lib/glew32.dll by default.
if(EXISTS "${PC_GLUT_LIBRARY_DIRS}/glew32.lib")
set(GLEW_LIB_NAME "glew32")
else()
set(GLEW_LIB_NAME "glew64")
endif()
endif()
find_package(OpenGL)
find_package(GLUT)
# Source file
if(${OpenGL_FOUND})
if (${GLUT_FOUND})
# Add target for particles
add_executable(particles particleSystem.cpp particleSystem_cuda.cu particles.cpp render_particles.cpp shaders.cpp)
target_compile_options(particles PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:--extended-lambda>)
target_compile_features(particles PRIVATE cxx_std_17 cuda_std_17)
set_target_properties(particles PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
target_include_directories(particles PUBLIC
${OPENGL_INCLUDE_DIR}
${CUDAToolkit_INCLUDE_DIRS}
${GLUT_INCLUDE_DIRS}
)
target_link_libraries(particles
${OPENGL_LIBRARIES}
${GLUT_LIBRARIES}
)
# Copy clock_kernel.cu to the output directory
add_custom_command(TARGET particles POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_directory
${CMAKE_CURRENT_SOURCE_DIR}/data
${CMAKE_CURRENT_BINARY_DIR}/data
)
if(WIN32)
target_link_libraries(particles
${PC_GLUT_LIBRARY_DIRS}/freeglut.lib
${PC_GLUT_LIBRARY_DIRS}/${GLEW_LIB_NAME}.lib
)
add_custom_command(TARGET particles
POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy
${CMAKE_CURRENT_SOURCE_DIR}/../../../bin/win64/$<CONFIGURATION>/freeglut.dll
${CMAKE_CURRENT_BINARY_DIR}/$<CONFIGURATION>
)
add_custom_command(TARGET particles
POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy
${CMAKE_CURRENT_SOURCE_DIR}/../../../bin/win64/$<CONFIGURATION>/${GLEW_LIB_NAME}.dll
${CMAKE_CURRENT_BINARY_DIR}/$<CONFIGURATION>
)
endif()
else()
message(STATUS "GLUT not found - will not build sample 'particles'")
endif()
else()
message(STATUS "OpenGL not found - will not build sample 'particles'")
endif()
# Include installation configuration
include(${CMAKE_CURRENT_SOURCE_DIR}/../../../cmake/InstallSamples.cmake)
setup_samples_install()

View File

@@ -0,0 +1,38 @@
# 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 5.0 ](https://developer.nvidia.com/cuda-gpus) [SM 5.2 ](https://developer.nvidia.com/cuda-gpus) [SM 5.3 ](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) [SM 8.7 ](https://developer.nvidia.com/cuda-gpus) [SM 8.9 ](https://developer.nvidia.com/cuda-gpus) [SM 9.0 ](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)
cudaGraphicsUnmapResources, cudaMemcpy, cudaFree, cudaGraphicsResourceGetMappedPointer, cudaGraphicsMapResources, cudaDeviceSynchronize, cudaMemset, cudaMemcpyToSymbol, cudaGraphicsGLRegisterBuffer, cudaGraphicsUnregisterResource, cudaMalloc, cudaInit, cudaGLInit
## Dependencies needed to build/run
[X11](../../../README.md#x11), [OpenGL](../../../README.md#opengl), [Freeglut](../../../README.md#freeglut), [GLEW](../../../README.md#glew)
## Prerequisites
Download and install the [CUDA Toolkit](https://developer.nvidia.com/cuda-downloads) for your corresponding platform.
Make sure the dependencies mentioned in [Dependencies]() section above are installed.
## References (for more details)
[whitepaper](./doc/particles.pdf)

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

View File

@@ -0,0 +1,494 @@
/*
* 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 "particleSystem.h"
#include <algorithm>
#include <assert.h>
#include <cstdio>
#include <cstdlib>
#include <cuda_runtime.h>
#include <helper_cuda.h>
#include <helper_functions.h>
#include <helper_gl.h>
#include <math.h>
#include <memory.h>
#include "particleSystem.cuh"
#include "particles_kernel.cuh"
#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);
}

View File

@@ -0,0 +1,71 @@
/* Copyright (c) 2022, 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);
}

View File

@@ -0,0 +1,146 @@
/* Copyright (c) 2022, 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__

View File

@@ -0,0 +1,218 @@
/* Copyright (c) 2022, 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 <cstdio>
#include <cstdlib>
#include <cuda_gl_interop.h>
#include <cuda_runtime.h>
#include <helper_cuda.h>
#include <helper_functions.h>
#include <string.h>
#include "particles_kernel_impl.cuh"
#include "thrust/device_ptr.h"
#include "thrust/for_each.h"
#include "thrust/iterator/zip_iterator.h"
#include "thrust/sort.h"
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(cudaParams, 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(d_pos4, d_vel4),
thrust::make_zip_iterator(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"

View File

@@ -0,0 +1,753 @@
/* Copyright (c) 2022, 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_cuda.h> // includes cuda.h and cuda_runtime_api.h
#include <helper_functions.h>
// Includes
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <stdlib.h>
#include "paramgl.h"
#include "particleSystem.h"
#include "render_particles.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, &timestep));
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);
}

View File

@@ -0,0 +1,59 @@
/* Copyright (c) 2022, 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

View File

@@ -0,0 +1,342 @@
/* Copyright (c) 2022, 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 <cooperative_groups.h>
#include <math.h>
#include <stdio.h>
#include "thrust/device_ptr.h"
#include "thrust/for_each.h"
#include "thrust/iterator/zip_iterator.h"
#include "thrust/sort.h"
// for cuda::std::get
#include <cuda/std/utility>
namespace cg = cooperative_groups;
#include "helper_math.h"
#include "math_constants.h"
#include "particles_kernel.cuh"
// simulation parameters in constant memory
__constant__ SimParams cudaParams;
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 = cuda::std::get<0>(t);
volatile float4 velData = cuda::std::get<1>(t);
float3 pos = make_float3(posData.x, posData.y, posData.z);
float3 vel = make_float3(velData.x, velData.y, velData.z);
vel += cudaParams.gravity * deltaTime;
vel *= cudaParams.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 - cudaParams.particleRadius) {
pos.x = 1.0f - cudaParams.particleRadius;
vel.x *= cudaParams.boundaryDamping;
}
if (pos.x < -1.0f + cudaParams.particleRadius) {
pos.x = -1.0f + cudaParams.particleRadius;
vel.x *= cudaParams.boundaryDamping;
}
if (pos.y > 1.0f - cudaParams.particleRadius) {
pos.y = 1.0f - cudaParams.particleRadius;
vel.y *= cudaParams.boundaryDamping;
}
if (pos.z > 1.0f - cudaParams.particleRadius) {
pos.z = 1.0f - cudaParams.particleRadius;
vel.z *= cudaParams.boundaryDamping;
}
if (pos.z < -1.0f + cudaParams.particleRadius) {
pos.z = -1.0f + cudaParams.particleRadius;
vel.z *= cudaParams.boundaryDamping;
}
#endif
if (pos.y < -1.0f + cudaParams.particleRadius) {
pos.y = -1.0f + cudaParams.particleRadius;
vel.y *= cudaParams.boundaryDamping;
}
// store new position and velocity
cuda::std::get<0>(t) = make_float4(pos, posData.w);
cuda::std::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 - cudaParams.worldOrigin.x) / cudaParams.cellSize.x);
gridPos.y = floorf((p.y - cudaParams.worldOrigin.y) / cudaParams.cellSize.y);
gridPos.z = floorf((p.z - cudaParams.worldOrigin.z) / cudaParams.cellSize.z);
return gridPos;
}
// calculate address in grid from position (clamping to edges)
__device__ uint calcGridHash(int3 gridPos)
{
gridPos.x = gridPos.x & (cudaParams.gridSize.x - 1); // wrap grid, assumes size is power of 2
gridPos.y = gridPos.y & (cudaParams.gridSize.y - 1);
gridPos.z = gridPos.z & (cudaParams.gridSize.z - 1);
return __umul24(__umul24(gridPos.z, cudaParams.gridSize.y), cudaParams.gridSize.x)
+ __umul24(gridPos.y, cudaParams.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 = -cudaParams.spring * (collideDist - dist) * norm;
// dashpot (damping) force
force += cudaParams.damping * relVel;
// tangential shear force
force += cudaParams.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, cudaParams.particleRadius, cudaParams.particleRadius, cudaParams.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,
cudaParams.colliderPos,
vel,
make_float3(0.0f, 0.0f, 0.0f),
cudaParams.particleRadius,
cudaParams.colliderRadius,
0.0f);
// write new velocity back to original unsorted location
uint originalIndex = gridParticleIndex[index];
newVel[originalIndex] = make_float4(vel + force, 0.0f);
}
#endif

View File

@@ -0,0 +1,174 @@
/* Copyright (c) 2022, 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 <assert.h>
#include <math.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
}

View File

@@ -0,0 +1,75 @@
/* Copyright (c) 2022, 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__

View File

@@ -0,0 +1,65 @@
/* Copyright (c) 2022, 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;
});

View File

@@ -0,0 +1,29 @@
/* Copyright (c) 2022, 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;