├── .gitignore ├── Dockerfile ├── Experiments └── 10_12_11_23 │ ├── Model_Epoch_04650_ValLoss_2.591095e-02.pt │ ├── plots4650_1.025_0.0259_0.png │ └── plots4650_occ.png ├── README.md ├── bvh-distance-queries ├── .gitignore ├── LICENSE ├── README.md ├── bvh_distance_queries │ ├── __init__.py │ ├── bvh_search_tree.py │ └── mesh_distance.py ├── cuda-samples │ ├── Common │ │ ├── GL │ │ │ ├── freeglut.h │ │ │ ├── freeglut_ext.h │ │ │ ├── freeglut_std.h │ │ │ ├── glew.h │ │ │ ├── glext.h │ │ │ ├── glut.h │ │ │ ├── glxew.h │ │ │ ├── glxext.h │ │ │ ├── wglew.h │ │ │ └── wglext.h │ │ ├── UtilNPP │ │ │ ├── Exceptions.h │ │ │ ├── Image.h │ │ │ ├── ImageAllocatorsCPU.h │ │ │ ├── ImageAllocatorsNPP.h │ │ │ ├── ImageIO.h │ │ │ ├── ImagePacked.h │ │ │ ├── ImagesCPU.h │ │ │ ├── ImagesNPP.h │ │ │ ├── Pixel.h │ │ │ ├── Signal.h │ │ │ ├── SignalAllocatorsCPU.h │ │ │ ├── SignalAllocatorsNPP.h │ │ │ ├── SignalsCPU.h │ │ │ └── SignalsNPP.h │ │ ├── data │ │ │ ├── CT_skull_512x512_8u.raw │ │ │ ├── CT_skull_512x512_8u_Gray.raw │ │ │ ├── PCB2_1024x683_8u.raw │ │ │ ├── PCB_1280x720_8u.raw │ │ │ ├── PCB_METAL_509x335_8u.raw │ │ │ ├── Rocks_512x512_8u_Gray.raw │ │ │ ├── teapot512.pgm │ │ │ ├── teapot_512x512_8u.raw │ │ │ └── teapot_512x512_8u_Gray.raw │ │ ├── drvapi_error_string.h │ │ ├── dynlink_d3d10.h │ │ ├── dynlink_d3d11.h │ │ ├── exception.h │ │ ├── helper_cuda.h │ │ ├── helper_cuda_drvapi.h │ │ ├── helper_cusolver.h │ │ ├── helper_functions.h │ │ ├── helper_gl.h │ │ ├── helper_image.h │ │ ├── helper_math.h │ │ ├── helper_multiprocess.cpp │ │ ├── helper_multiprocess.h │ │ ├── helper_nvJPEG.hxx │ │ ├── helper_string.h │ │ ├── helper_timer.h │ │ ├── multithreading.cpp │ │ ├── multithreading.h │ │ ├── nvMath.h │ │ ├── nvMatrix.h │ │ ├── nvQuaternion.h │ │ ├── nvShaderUtils.h │ │ ├── nvVector.h │ │ ├── nvrtc_helper.h │ │ ├── param.h │ │ ├── paramgl.h │ │ ├── rendercheck_d3d10.cpp │ │ ├── rendercheck_d3d10.h │ │ ├── rendercheck_d3d11.cpp │ │ ├── rendercheck_d3d11.h │ │ ├── rendercheck_d3d9.cpp │ │ ├── rendercheck_d3d9.h │ │ ├── rendercheck_gl.h │ │ └── rendercheck_gles.h │ └── LICENSE ├── data │ └── test_box.ply ├── examples │ ├── benchmark_time.py │ ├── fit_cube_to_cube.py │ ├── fit_cube_to_random_points.py │ └── random_points_to_surface.py ├── include │ ├── aabb.hpp │ ├── defs.hpp │ ├── double_vec_ops.h │ ├── helper_math.h │ ├── math_utils.hpp │ ├── priority_queue.hpp │ └── triangle.hpp ├── optional-requirements.txt ├── requirements.txt ├── setup.py └── src │ ├── aabb.hpp │ ├── bvh.cpp │ ├── bvh_cuda_op.cu │ ├── defs.hpp │ ├── double_vec_ops.h │ ├── helper_math.h │ ├── math_utils.hpp │ ├── priority_queue.hpp │ └── triangle.hpp ├── data └── mesh.obj ├── dataprocessing ├── data_pc_validate.py ├── eval_points_speeds.py ├── isdf_sample.py ├── speed_sampling_gpu.py ├── torch_IK_UR5.py └── transform.py ├── eval.py ├── gridmap.py ├── igib_runner.py ├── main.py ├── models └── model_igibson.py └── test_igib.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.npy 2 | *.pyc -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Start from the iGibson base image or another if more appropriate 2 | FROM igibson/igibson 3 | 4 | # Set the working directory (customize as needed) 5 | # WORKDIR /app 6 | 7 | # Assuming your requirements.txt is in the same directory as your Dockerfile, 8 | # otherwise, change './requirements.txt' to the correct path inside your project 9 | # COPY ./requirements.txt /app/requirements.txt 10 | 11 | # Copy the rest of your application's code 12 | # COPY /home/exx/Documents/igibson-scripts /app 13 | 14 | # Install dependencies 15 | RUN apt-get update && apt-get install -y \ 16 | python3 \ 17 | python3-pip \ 18 | python3-dev \ 19 | mesa-utils \ 20 | libgl1-mesa-glx \ 21 | libgl1-mesa-dri \ 22 | libglu1-mesa \ 23 | freeglut3-dev \ 24 | libosmesa6-dev \ 25 | patchelf \ 26 | x11-apps 27 | 28 | # Install any needed packages specified in requirements.txt 29 | # RUN pip install --no-cache-dir -r requirements.txt 30 | RUN pip install torch 31 | RUN pip install pickle5 32 | RUN pip install libigl 33 | RUN pip install pytorch-kinematics 34 | RUN pip install --upgrade pyglet==v1.5.28 35 | RUN pip install matplotlib 36 | 37 | 38 | WORKDIR /antfields 39 | COPY bvh-distance-queries /antfields/bvh-distance-queries 40 | RUN cd /antfields/bvh-distance-queries && pip install -e . -------------------------------------------------------------------------------- /Experiments/10_12_11_23/Model_Epoch_04650_ValLoss_2.591095e-02.pt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rtlyc/antfields-demo/3743ba2a41699ceea57051162388643c8d0e33fb/Experiments/10_12_11_23/Model_Epoch_04650_ValLoss_2.591095e-02.pt -------------------------------------------------------------------------------- /Experiments/10_12_11_23/plots4650_1.025_0.0259_0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rtlyc/antfields-demo/3743ba2a41699ceea57051162388643c8d0e33fb/Experiments/10_12_11_23/plots4650_1.025_0.0259_0.png -------------------------------------------------------------------------------- /Experiments/10_12_11_23/plots4650_occ.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rtlyc/antfields-demo/3743ba2a41699ceea57051162388643c8d0e33fb/Experiments/10_12_11_23/plots4650_occ.png -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## About 2 | This is a minimal example of active learning ntfields with igibson setup. 3 | 4 | ## Setup 5 | 1. git clone this repo 6 | 2. run `docker build -t antfields:demo .` under the root directory of this repo, once you built the docker image, you don't need to build it again unless you change the dockerfile. 7 | 3. run `docker run --rm -it -e DISPLAY=$DISPLAY --env="QT_X11_NO_MITSHM=1" -v /tmp/.X11-unix:/tmp/.X11-unix --volume="/home/exx/Documents/antfields-demo:/antfields" --gpus all antfields:demo /bin/bash` to start the docker container. Note that you need to change the path to your own path. BVH library is only needed during evaluation. 8 | 4. run `python main.py` to start the training. In main.py, you can switch mode. READ_FROM_COOKED_DATA: train model with previous collected data, EXPLORATION: train model with active learning(exploration) in gibson env. 9 | ``` 10 | # train model with default EXPLORATION mode 11 | python main.py 12 | 13 | # train model with READ_FROM_COOKED_DATA mode 14 | python main.py --no_explore 15 | 16 | # evaluate model 17 | python eval.py 18 | ``` 19 | 20 | ## Note 21 | 22 | We use bvh-distance-queries library [repo](https://github.com/YuliangXiu/bvh-distance-queries?tab=readme-ov-file) to calculate the distance between two objects. If the bvh library fails to install in dockerfile, you can install it manually by "cd /antfields/bvh-distance-queries && pip install -e .". 23 | Occupancy map is modified from [repo](https://github.com/richardos/occupancy-grid-a-star) to fit the igibson env. 24 | Data sampling and preprocessing is modified from [repo](https://github.com/facebookresearch/iSDF) 25 | -------------------------------------------------------------------------------- /bvh-distance-queries/.gitignore: -------------------------------------------------------------------------------- 1 | #### joe made this: http://goel.io/joe 2 | 3 | #### cuda #### 4 | *.i 5 | *.ii 6 | *.gpu 7 | *.ptx 8 | *.cubin 9 | *.fatbin 10 | #### joe made this: http://goel.io/joe 11 | 12 | #### python #### 13 | # Byte-compiled / optimized / DLL files 14 | __pycache__/ 15 | *.py[cod] 16 | *$py.class 17 | 18 | # C extensions 19 | *.so 20 | 21 | # Distribution / packaging 22 | .Python 23 | build/ 24 | develop-eggs/ 25 | dist/ 26 | downloads/ 27 | eggs/ 28 | .eggs/ 29 | lib/ 30 | lib64/ 31 | parts/ 32 | sdist/ 33 | var/ 34 | wheels/ 35 | pip-wheel-metadata/ 36 | share/python-wheels/ 37 | *.egg-info/ 38 | .installed.cfg 39 | *.egg 40 | MANIFEST 41 | 42 | # PyInstaller 43 | # Usually these files are written by a python script from a template 44 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 45 | *.manifest 46 | *.spec 47 | 48 | # Installer logs 49 | pip-log.txt 50 | pip-delete-this-directory.txt 51 | 52 | # Unit test / coverage reports 53 | htmlcov/ 54 | .tox/ 55 | .nox/ 56 | .coverage 57 | .coverage.* 58 | .cache 59 | nosetests.xml 60 | coverage.xml 61 | *.cover 62 | *.py,cover 63 | .hypothesis/ 64 | .pytest_cache/ 65 | 66 | # Translations 67 | *.mo 68 | *.pot 69 | 70 | # Django stuff: 71 | *.log 72 | local_settings.py 73 | db.sqlite3 74 | db.sqlite3-journal 75 | 76 | # Flask stuff: 77 | instance/ 78 | .webassets-cache 79 | 80 | # Scrapy stuff: 81 | .scrapy 82 | 83 | # Sphinx documentation 84 | docs/_build/ 85 | 86 | # PyBuilder 87 | target/ 88 | 89 | # Jupyter Notebook 90 | .ipynb_checkpoints 91 | 92 | # IPython 93 | profile_default/ 94 | ipython_config.py 95 | 96 | # pyenv 97 | .python-version 98 | 99 | # pipenv 100 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 101 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 102 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 103 | # install all needed dependencies. 104 | #Pipfile.lock 105 | 106 | # pyflow 107 | __pypackages__/ 108 | 109 | # Celery stuff 110 | celerybeat-schedule 111 | celerybeat.pid 112 | 113 | # SageMath parsed files 114 | *.sage.py 115 | 116 | # Environments 117 | .env 118 | .venv 119 | env/ 120 | venv/ 121 | ENV/ 122 | env.bak/ 123 | venv.bak/ 124 | 125 | # Spyder project settings 126 | .spyderproject 127 | .spyproject 128 | 129 | # Rope project settings 130 | .ropeproject 131 | 132 | # mkdocs documentation 133 | /site 134 | 135 | # mypy 136 | .mypy_cache/ 137 | .dmypy.json 138 | dmypy.json 139 | 140 | # Pyre type checker 141 | .pyre/ 142 | #### joe made this: http://goel.io/joe 143 | 144 | #### c++ #### 145 | # Prerequisites 146 | *.d 147 | 148 | # Compiled Object files 149 | *.slo 150 | *.lo 151 | *.o 152 | *.obj 153 | 154 | # Precompiled Headers 155 | *.gch 156 | *.pch 157 | 158 | # Compiled Dynamic libraries 159 | *.so 160 | *.dylib 161 | *.dll 162 | 163 | # Fortran module files 164 | *.mod 165 | *.smod 166 | 167 | # Compiled Static libraries 168 | *.lai 169 | *.la 170 | *.a 171 | *.lib 172 | 173 | # Executables 174 | *.exe 175 | *.out 176 | *.app 177 | -------------------------------------------------------------------------------- /bvh-distance-queries/LICENSE: -------------------------------------------------------------------------------- 1 | License 2 | 3 | Software Copyright License for non-commercial scientific research purposes 4 | Please read carefully the following terms and conditions and any accompanying documentation before you download and/or use the SMPL-X/SMPLify-X model, data and software, (the "Model & Software"), including 3D meshes, blend weights, blend shapes, textures, software, scripts, and animations. By downloading and/or using the Model & Software (including downloading, cloning, installing, and any other use of this github repository), you acknowledge that you have read these terms and conditions, understand them, and agree to be bound by them. If you do not agree with these terms and conditions, you must not download and/or use the Model & Software. Any infringement of the terms of this agreement will automatically terminate your rights under this License 5 | 6 | Ownership / Licensees 7 | The Software and the associated materials has been developed at the 8 | 9 | Max Planck Institute for Intelligent Systems (hereinafter "MPI"). 10 | 11 | Any copyright or patent right is owned by and proprietary material of the 12 | 13 | Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (hereinafter “MPG”; MPI and MPG hereinafter collectively “Max-Planck”) 14 | 15 | hereinafter the “Licensor”. 16 | 17 | License Grant 18 | Licensor grants you (Licensee) personally a single-user, non-exclusive, non-transferable, free of charge right: 19 | 20 | To install the Model & Software on computers owned, leased or otherwise controlled by you and/or your organization; 21 | To use the Model & Software for the sole purpose of performing non-commercial scientific research, non-commercial education, or non-commercial artistic projects; 22 | To modify, adapt, translate or create derivative works based upon the Model & Software. 23 | Any other use, in particular any use for commercial purposes, is prohibited. This includes, without limitation, incorporation in a commercial product, use in a commercial service, or production of other artifacts for commercial purposes. The Model & Software may not be reproduced, modified and/or made available in any form to any third party without Max-Planck’s prior written permission. 24 | 25 | The Model & Software may not be used for pornographic purposes or to generate pornographic material whether commercial or not. This license also prohibits the use of the Model & Software to train methods/algorithms/neural networks/etc. for commercial use of any kind. By downloading the Model & Software, you agree not to reverse engineer it. 26 | 27 | No Distribution 28 | The Model & Software and the license herein granted shall not be copied, shared, distributed, re-sold, offered for re-sale, transferred or sub-licensed in whole or in part except that you may make one copy for archive purposes only. 29 | 30 | Disclaimer of Representations and Warranties 31 | You expressly acknowledge and agree that the Model & Software results from basic research, is provided “AS IS”, may contain errors, and that any use of the Model & Software is at your sole risk. LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE MODEL & SOFTWARE, NEITHER EXPRESS NOR IMPLIED, AND THE ABSENCE OF ANY LEGAL OR ACTUAL DEFECTS, WHETHER DISCOVERABLE OR NOT. Specifically, and not to limit the foregoing, licensor makes no representations or warranties (i) regarding the merchantability or fitness for a particular purpose of the Model & Software, (ii) that the use of the Model & Software will not infringe any patents, copyrights or other intellectual property rights of a third party, and (iii) that the use of the Model & Software will not cause any damage of any kind to you or a third party. 32 | 33 | Limitation of Liability 34 | Because this Model & Software License Agreement qualifies as a donation, according to Section 521 of the German Civil Code (Bürgerliches Gesetzbuch – BGB) Licensor as a donor is liable for intent and gross negligence only. If the Licensor fraudulently conceals a legal or material defect, they are obliged to compensate the Licensee for the resulting damage. 35 | Licensor shall be liable for loss of data only up to the amount of typical recovery costs which would have arisen had proper and regular data backup measures been taken. For the avoidance of doubt Licensor shall be liable in accordance with the German Product Liability Act in the event of product liability. The foregoing applies also to Licensor’s legal representatives or assistants in performance. Any further liability shall be excluded. 36 | Patent claims generated through the usage of the Model & Software cannot be directed towards the copyright holders. 37 | The Model & Software is provided in the state of development the licensor defines. If modified or extended by Licensee, the Licensor makes no claims about the fitness of the Model & Software and is not responsible for any problems such modifications cause. 38 | 39 | No Maintenance Services 40 | You understand and agree that Licensor is under no obligation to provide either maintenance services, update services, notices of latent defects, or corrections of defects with regard to the Model & Software. Licensor nevertheless reserves the right to update, modify, or discontinue the Model & Software at any time. 41 | 42 | Defects of the Model & Software must be notified in writing to the Licensor with a comprehensible description of the error symptoms. The notification of the defect should enable the reproduction of the error. The Licensee is encouraged to communicate any use, results, modification or publication. 43 | 44 | Publications using the Model & Software 45 | You acknowledge that the Model & Software is a valuable scientific resource and agree to appropriately reference the following paper in any publication making use of the Model & Software. 46 | 47 | Commercial licensing opportunities 48 | For commercial uses of the Software, please send email to ps-license@tue.mpg.de 49 | 50 | This Agreement shall be governed by the laws of the Federal Republic of Germany except for the UN Sales Convention. 51 | -------------------------------------------------------------------------------- /bvh-distance-queries/README.md: -------------------------------------------------------------------------------- 1 | # Point to Mesh distance computation 2 | 3 | This package provides a PyTorch module that performs point to surface queries 4 | on the GPU 5 | 6 | 7 | ## Table of Contents 8 | * [License](#license) 9 | * [Description](#description) 10 | * [Installation](#installation) 11 | * [Examples](#examples) 12 | * [Citation](#citation) 13 | * [Contact](#contact) 14 | 15 | ## License 16 | 17 | Software Copyright License for **non-commercial scientific research purposes**. 18 | By downloading and/or using the Model & Software (including downloading, cloning, 19 | installing, and any other use of this github repository), you acknowledge that 20 | you have read these terms and conditions, understand them, and agree to be bound 21 | by them. If you do not agree with these terms and conditions, you must not 22 | download and/or use the Model & Software. Any infringement of the terms of this 23 | agreement will automatically terminate your rights under this 24 | [License](./LICENSE). 25 | 26 | 27 | ## Description 28 | 29 | This repository provides a PyTorch wrapper around a CUDA kernel that implements 30 | the method described in [Maximizing parallelism in the construction of BVHs, 31 | octrees, and k-d trees](https://dl.acm.org/citation.cfm?id=2383801). More 32 | specifically, given a batch of meshes it builds a 33 | BVH tree for each one, which can then be used for distance quries. 34 | 35 | ## Installation 36 | 37 | Before installing anything please make sure to set the environment variable 38 | *$CUDA_SAMPLES_INC* to the path that contains the header `helper_math.h` , which 39 | can be found in the [CUDA Samples repository](https://github.com/NVIDIA/cuda-samples). 40 | To install the module run the following commands: 41 | 42 | **1. Install the dependencies** 43 | ```Shell 44 | pip install -r requirements.txt 45 | ``` 46 | **2. Run the *setup.py* script** 47 | ```Shell 48 | python setup.py install 49 | ``` 50 | 51 | If you want to modify any part of the code then use the following command: 52 | ```Shell 53 | python setup.py build develop 54 | ``` 55 | 56 | 57 | ## Examples 58 | 59 | * [Random points to surface](./examples/random_points_to_surface.py): Generate 60 | random points and compute their distance to a mesh. Use: 61 | ```Shell 62 | python examples/random_points_to_surface.py --mesh-fn MESH_FN --num-query-points 100000 63 | ``` 64 | * [Fit a cube to a cube](./examples/fit_cube_to_cube.py): Randomly translate 65 | and rotate a cube then fit it to the original, without using the 66 | correspondences by using the point to mesh distances. 67 | ```Shell 68 | python examples/fit_cube_to_cube.py 69 | ``` 70 | 71 | * [Fit a cube to random points](./examples/fit_cube_to_random_points.py): 72 | First generate a set of random points and compute their convex hull, which 73 | gives us a dummy scan. We then try to rigidly align a cube to this scan using 74 | the provided point-to-mesh residuals. 75 | ```Shell 76 | python examples/fit_cube_to_random_points.py 77 | ``` 78 | 79 | ## Dependencies 80 | 81 | 1. [PyTorch](https://pytorch.org) 82 | 83 | 84 | ## Example dependencies 85 | 86 | 1. [open3d](http://www.open3d.org/) 87 | 1. [mesh](https://github.com/MPI-IS/mesh) 88 | 89 | ## Running on Cluster 90 | If you want to run this on the cluster you need to build it using the GPU availabe on the cluster. If you use the local build there might be GPU architecture compatibility issue and you can encounter following error message 91 | ``` 92 | RuntimeError: parallel_for failed: unrecognized error code: unrecognized error code 93 | ``` 94 | 95 | ## Citation 96 | 97 | If you find this code useful in your research please cite the relevant work(s) of the following list: 98 | 99 | ``` 100 | @inproceedings{Karras:2012:MPC:2383795.2383801, 101 | author = {Karras, Tero}, 102 | title = {Maximizing Parallelism in the Construction of BVHs, Octrees, and K-d Trees}, 103 | booktitle = {Proceedings of the Fourth ACM SIGGRAPH / Eurographics Conference on High-Performance Graphics}, 104 | year = {2012}, 105 | pages = {33--37}, 106 | numpages = {5}, 107 | url = {https://doi.org/10.2312/EGGH/HPG12/033-037}, 108 | doi = {10.2312/EGGH/HPG12/033-037}, 109 | publisher = {Eurographics Association} 110 | } 111 | ``` 112 | 113 | ## Contact 114 | The code of this repository was implemented by [Vassilis Choutas](vassilis.choutas@tuebingen.mpg.de). 115 | For commercial licensing, please contact [ps-licensing@tue.mpg.de](ps-licensing@tue.mpg.de). 116 | -------------------------------------------------------------------------------- /bvh-distance-queries/bvh_distance_queries/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is 4 | # holder of all proprietary rights on this computer program. 5 | # You can only use this computer program if you have closed 6 | # a license agreement with MPG or you get the right to use the computer 7 | # program from someone who is authorized to grant you that right. 8 | # Any use of the computer program without a valid license is prohibited and 9 | # liable to prosecution. 10 | # 11 | # Copyright©2019 Max-Planck-Gesellschaft zur Förderung 12 | # der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute 13 | # for Intelligent Systems. All rights reserved. 14 | # 15 | # @author Vasileios Choutas 16 | # Contact: vassilis.choutas@tuebingen.mpg.de 17 | # Contact: ps-license@tuebingen.mpg.de 18 | 19 | import torch 20 | from .bvh_search_tree import BVH 21 | from .mesh_distance import PointToMeshResidual 22 | -------------------------------------------------------------------------------- /bvh-distance-queries/bvh_distance_queries/bvh_search_tree.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is 4 | # holder of all proprietary rights on this computer program. 5 | # You can only use this computer program if you have closed 6 | # a license agreement with MPG or you get the right to use the computer 7 | # program from someone who is authorized to grant you that right. 8 | # Any use of the computer program without a valid license is prohibited and 9 | # liable to prosecution. 10 | # 11 | # Copyright©2019 Max-Planck-Gesellschaft zur Förderung 12 | # der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute 13 | # for Intelligent Systems. All rights reserved. 14 | # 15 | # @author Vasileios Choutas 16 | # Contact: vassilis.choutas@tuebingen.mpg.de 17 | # Contact: ps-license@tuebingen.mpg.de 18 | 19 | import sys 20 | 21 | from typing import Tuple, NewType 22 | 23 | import torch 24 | import torch.nn as nn 25 | import torch.autograd as autograd 26 | 27 | import bvh_distance_queries_cuda 28 | 29 | Tensor = NewType('Tensor', torch.Tensor) 30 | 31 | 32 | class BVHFunction(autograd.Function): 33 | ''' Autograd wrapper for the BVH nearest neighbor kernel 34 | ''' 35 | QUEUE_SIZE = 128 36 | SORT_POINTS_BY_MORTON = True 37 | 38 | @staticmethod 39 | def forward(ctx, 40 | triangles: Tensor, 41 | points: Tensor) -> Tuple[Tensor, Tensor, Tensor, Tensor]: 42 | outputs = bvh_distance_queries_cuda.distance_queries( 43 | triangles, points, 44 | queue_size=BVHFunction.QUEUE_SIZE, 45 | sort_points_by_morton=BVHFunction.SORT_POINTS_BY_MORTON, 46 | ) 47 | ctx.save_for_backward(triangles, *outputs) 48 | return outputs[0], outputs[1], outputs[2], outputs[3] 49 | 50 | @staticmethod 51 | def backward(ctx, grad_output, *args, **kwargs): 52 | raise NotImplementedError 53 | 54 | 55 | class BVH(nn.Module): 56 | 57 | def __init__(self, 58 | sort_points_by_morton: bool = True, 59 | queue_size: int = 128) -> None: 60 | ''' Constructor for the BVH acceleration structure 61 | 62 | Parameters 63 | ---------- 64 | sort_points_by_morton: bool, optional 65 | Sort input points by their morton code. Helps improve query 66 | speed. Default is true 67 | queue_size: int, optional 68 | The size of the data structure used to store intermediate 69 | distance computations 70 | ''' 71 | super(BVH, self).__init__() 72 | assert queue_size in [32, 64, 128, 256, 512, 1024], ( 73 | f'Queue/Stack size must be in {str[32, 64, 128, 256, 512, 1024]()}' 74 | ) 75 | BVHFunction.QUEUE_SIZE = queue_size 76 | BVHFunction.SORT_POINTS_BY_MORTON = sort_points_by_morton 77 | 78 | @torch.no_grad() 79 | def forward( 80 | self, 81 | triangles: Tensor, 82 | points: Tensor) -> Tuple[Tensor, Tensor, Tensor, Tensor]: 83 | ''' Forward pass of the search tree 84 | 85 | Parameters 86 | ---------- 87 | triangles: torch.tensor 88 | A BxFx3x3 PyTorch tensor that contains the triangle 89 | locations. 90 | points: torch.tensor 91 | A BxQx3 PyTorch tensor that contains the query point 92 | locations. 93 | Returns 94 | ------- 95 | distances: torch.tensor 96 | A BxQ tensor with the *squared* distances to the closest 97 | point 98 | closest_points: torch.tensor 99 | A BxQx3 tensor with the closest points on the 3D mesh 100 | closest_faces: torch.tensor 101 | A BxQ tensor that contains the index of the closest 102 | triangle of each queyr point 103 | closest_bcs: torch.tensor 104 | A BxQx3 tensor with the barycentric coordinates of the 105 | closest point 106 | 107 | ''' 108 | 109 | output = BVHFunction.apply( 110 | triangles, points) 111 | distances, closest_points, closest_faces, closest_bcs = output 112 | 113 | return distances, closest_points, closest_faces, closest_bcs 114 | -------------------------------------------------------------------------------- /bvh-distance-queries/bvh_distance_queries/mesh_distance.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is 4 | # holder of all proprietary rights on this computer program. 5 | # You can only use this computer program if you have closed 6 | # a license agreement with MPG or you get the right to use the computer 7 | # program from someone who is authorized to grant you that right. 8 | # Any use of the computer program without a valid license is prohibited and 9 | # liable to prosecution. 10 | # 11 | # Copyright©2019 Max-Planck-Gesellschaft zur Förderung 12 | # der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute 13 | # for Intelligent Systems. All rights reserved. 14 | # 15 | # @author Vasileios Choutas 16 | # Contact: vassilis.choutas@tuebingen.mpg.de 17 | # Contact: ps-license@tuebingen.mpg.de 18 | 19 | from typing import Tuple, NewType 20 | 21 | import torch 22 | import torch.nn as nn 23 | 24 | from .bvh_search_tree import BVH 25 | 26 | Tensor = NewType('Tensor', torch.Tensor) 27 | 28 | 29 | class PointToMeshResidual(nn.Module): 30 | 31 | def __init__(self, 32 | sort_points_by_morton: bool = True, 33 | queue_size: int = 128) -> None: 34 | ''' Constructor for the point to mesh residual module 35 | 36 | Parameters 37 | ---------- 38 | sort_points_by_morton: bool, optional 39 | Sort input points by their morton code. Helps improve query 40 | speed. Default is true 41 | queue_size: int, optional 42 | The size of the data structure used to store intermediate 43 | distance computations 44 | ''' 45 | super(PointToMeshResidual, self).__init__() 46 | self.search_tree = BVH(sort_points_by_morton=sort_points_by_morton, 47 | queue_size=queue_size) 48 | 49 | @staticmethod 50 | def compute_bcs_result(features, 51 | closest_faces_idxs, 52 | closest_bcs, 53 | closest_faces, 54 | batch_size, 55 | num_points): 56 | 57 | closest_features_lst = [] 58 | 59 | for feature in features: 60 | closest_triangles = feature.view(-1, 3, 3)[ 61 | closest_faces_idxs + closest_faces].view( 62 | batch_size, num_points, 3, 3) 63 | 64 | closest_features = ( 65 | closest_triangles[:, :, 0] * 66 | closest_bcs[:, :, 0].unsqueeze(dim=-1) + 67 | closest_triangles[:, :, 1] * 68 | closest_bcs[:, :, 1].unsqueeze(dim=-1) + 69 | closest_triangles[:, :, 2] * 70 | closest_bcs[:, :, 2].unsqueeze(dim=-1) 71 | ) 72 | 73 | closest_features_lst.append(closest_features) 74 | 75 | return closest_features_lst 76 | 77 | def forward(self, 78 | triangles: Tensor, 79 | points: Tensor, 80 | normals: Tensor, 81 | cmaps: Tensor, 82 | faces: Tensor) -> Tuple[Tensor, Tensor, Tensor]: 83 | ''' Forward pass of the search tree 84 | 85 | Parameters 86 | ---------- 87 | triangles: torch.tensor 88 | A BxFx3x3 PyTorch tensor that contains the triangle 89 | locations. 90 | points: torch.tensor 91 | A BxQx3 PyTorch tensor that contains the query point 92 | locations. 93 | normals: torch.tensor 94 | A BxFx3x3 PyTorch tensor that contains the normal 95 | vectors. 96 | faces: torch.tensor 97 | A BxFx3 PyTorch tensor that contains the face 98 | vectors 99 | Returns 100 | ------- 101 | residuals: torch.tensor 102 | A BxQx3 tensor with the vector that points from the query 103 | to the closest point 104 | ''' 105 | output = self.search_tree(triangles, points) 106 | distances, _, closest_faces, closest_bcs = output 107 | 108 | closest_bcs = torch.clamp(closest_bcs, 0, 1) 109 | 110 | batch_size, num_triangles = triangles.shape[:2] 111 | num_points = points.shape[1] 112 | 113 | closest_faces_idxs = ( 114 | torch.arange( 115 | 0, batch_size, device=triangles.device, dtype=torch.long) * 116 | num_triangles 117 | ).view(batch_size, 1) 118 | 119 | closest_points, closest_normals, closest_cmaps = self.compute_bcs_result([triangles, normals, cmaps], 120 | closest_faces_idxs, 121 | closest_bcs, 122 | closest_faces, 123 | batch_size, 124 | num_points) 125 | residual = closest_points - points 126 | 127 | # faces [B, FN, 3] 128 | # cloesest_faces [B, CN] 129 | # cloesest_bcs [B, CN, 3] 130 | 131 | closest_fids = torch.gather(faces, 1, torch.tile(closest_faces.unsqueeze(-1),(1,1,3))) 132 | closest_idx = torch.gather(closest_fids, 2, closest_bcs.max(2)[1].unsqueeze(-1)).squeeze(-1) 133 | 134 | return residual, closest_normals, closest_cmaps, closest_idx 135 | -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/GL/freeglut.h: -------------------------------------------------------------------------------- 1 | #ifndef __FREEGLUT_H__ 2 | #define __FREEGLUT_H__ 3 | 4 | /* 5 | * freeglut.h 6 | * 7 | * The freeglut library include file 8 | * 9 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 10 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 11 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 12 | * PAWEL W. OLSZTA BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 13 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 14 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 15 | */ 16 | 17 | #include "freeglut_std.h" 18 | #include "freeglut_ext.h" 19 | 20 | /*** END OF FILE ***/ 21 | 22 | #endif /* __FREEGLUT_H__ */ 23 | -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/GL/freeglut_ext.h: -------------------------------------------------------------------------------- 1 | #ifndef __FREEGLUT_EXT_H__ 2 | #define __FREEGLUT_EXT_H__ 3 | 4 | /* 5 | * freeglut_ext.h 6 | * 7 | * The non-GLUT-compatible extensions to the freeglut library include file 8 | * 9 | * Copyright (c) 1999-2000 Pawel W. Olszta. All Rights Reserved. 10 | * Written by Pawel W. Olszta, 11 | * Creation date: Thu Dec 2 1999 12 | * 13 | * Permission is hereby granted, free of charge, to any person obtaining a 14 | * copy of this software and associated documentation files (the "Software"), 15 | * to deal in the Software without restriction, including without limitation 16 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 17 | * and/or sell copies of the Software, and to permit persons to whom the 18 | * Software is furnished to do so, subject to the following conditions: 19 | * 20 | * The above copyright notice and this permission notice shall be included 21 | * in all copies or substantial portions of the Software. 22 | * 23 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 24 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 25 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 26 | * PAWEL W. OLSZTA BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 27 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 28 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 29 | */ 30 | 31 | #ifdef __cplusplus 32 | extern "C" { 33 | #endif 34 | 35 | /* 36 | * GLUT API Extension macro definitions -- behaviour when the user clicks on an "x" to close a window 37 | */ 38 | #define GLUT_ACTION_EXIT 0 39 | #define GLUT_ACTION_GLUTMAINLOOP_RETURNS 1 40 | #define GLUT_ACTION_CONTINUE_EXECUTION 2 41 | 42 | /* 43 | * Create a new rendering context when the user opens a new window? 44 | */ 45 | #define GLUT_CREATE_NEW_CONTEXT 0 46 | #define GLUT_USE_CURRENT_CONTEXT 1 47 | 48 | /* 49 | * GLUT API Extension macro definitions -- the glutGet parameters 50 | */ 51 | #define GLUT_ACTION_ON_WINDOW_CLOSE 0x01F9 52 | 53 | #define GLUT_WINDOW_BORDER_WIDTH 0x01FA 54 | #define GLUT_WINDOW_HEADER_HEIGHT 0x01FB 55 | 56 | #define GLUT_VERSION 0x01FC 57 | 58 | #define GLUT_RENDERING_CONTEXT 0x01FD 59 | 60 | /* 61 | * Process loop function, see freeglut_main.c 62 | */ 63 | FGAPI void FGAPIENTRY glutMainLoopEvent(void); 64 | FGAPI void FGAPIENTRY glutLeaveMainLoop(void); 65 | 66 | /* 67 | * Window-specific callback functions, see freeglut_callbacks.c 68 | */ 69 | FGAPI void FGAPIENTRY glutMouseWheelFunc(void (* callback)(int, int, int, int)); 70 | FGAPI void FGAPIENTRY glutCloseFunc(void (* callback)(void)); 71 | FGAPI void FGAPIENTRY glutWMCloseFunc(void (* callback)(void)); 72 | /* A. Donev: Also a destruction callback for menus */ 73 | FGAPI void FGAPIENTRY glutMenuDestroyFunc(void (* callback)(void)); 74 | 75 | /* 76 | * State setting and retrieval functions, see freeglut_state.c 77 | */ 78 | FGAPI void FGAPIENTRY glutSetOption(GLenum option_flag, int value) ; 79 | /* A.Donev: User-data manipulation */ 80 | FGAPI void *FGAPIENTRY glutGetWindowData(void); 81 | FGAPI void FGAPIENTRY glutSetWindowData(void *data); 82 | FGAPI void *FGAPIENTRY glutGetMenuData(void); 83 | FGAPI void FGAPIENTRY glutSetMenuData(void *data); 84 | 85 | /* 86 | * Font stuff, see freeglut_font.c 87 | */ 88 | FGAPI int FGAPIENTRY glutBitmapHeight(void *font); 89 | FGAPI GLfloat FGAPIENTRY glutStrokeHeight(void *font); 90 | FGAPI void FGAPIENTRY glutBitmapString(void *font, const unsigned char *string); 91 | FGAPI void FGAPIENTRY glutStrokeString(void *font, const unsigned char *string); 92 | 93 | /* 94 | * Geometry functions, see freeglut_geometry.c 95 | */ 96 | FGAPI void FGAPIENTRY glutWireRhombicDodecahedron(void); 97 | FGAPI void FGAPIENTRY glutSolidRhombicDodecahedron(void); 98 | FGAPI void FGAPIENTRY glutWireSierpinskiSponge(int num_levels, GLdouble offset[3], GLdouble scale) ; 99 | FGAPI void FGAPIENTRY glutSolidSierpinskiSponge(int num_levels, GLdouble offset[3], GLdouble scale) ; 100 | FGAPI void FGAPIENTRY glutWireCylinder(GLdouble radius, GLdouble height, GLint slices, GLint stacks); 101 | FGAPI void FGAPIENTRY glutSolidCylinder(GLdouble radius, GLdouble height, GLint slices, GLint stacks); 102 | 103 | /* 104 | * Extension functions, see freeglut_ext.c 105 | */ 106 | FGAPI void *FGAPIENTRY glutGetProcAddress(const char *procName); 107 | 108 | 109 | #ifdef __cplusplus 110 | } 111 | #endif 112 | 113 | /*** END OF FILE ***/ 114 | 115 | #endif /* __FREEGLUT_EXT_H__ */ 116 | -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/UtilNPP/Image.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. 2 | * 3 | * Redistribution and use in source and binary forms, with or without 4 | * modification, are permitted provided that the following conditions 5 | * are met: 6 | * * Redistributions of source code must retain the above copyright 7 | * notice, this list of conditions and the following disclaimer. 8 | * * Redistributions in binary form must reproduce the above copyright 9 | * notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * * Neither the name of NVIDIA CORPORATION nor the names of its 12 | * contributors may be used to endorse or promote products derived 13 | * from this software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY 16 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 18 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 19 | * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 20 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 21 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 22 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 23 | * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #ifndef NV_UTIL_NPP_IMAGE_H 29 | #define NV_UTIL_NPP_IMAGE_H 30 | 31 | #include 32 | 33 | namespace npp 34 | { 35 | 36 | class Image 37 | { 38 | public: 39 | struct Size 40 | { 41 | unsigned int nWidth; 42 | unsigned int nHeight; 43 | 44 | Size() : nWidth(0), nHeight(0) 45 | { }; 46 | 47 | Size(unsigned int nWidthNew, unsigned nHeightNew) : nWidth(nWidthNew), nHeight(nHeightNew) 48 | { }; 49 | 50 | Size(const Size &rSize) : nWidth(rSize.nWidth), nHeight(rSize.nHeight) 51 | { }; 52 | 53 | Size & 54 | operator= (const Size &rSize) 55 | { 56 | if (&rSize == this) 57 | { 58 | return *this; 59 | } 60 | 61 | nWidth = rSize.nWidth; 62 | nHeight = rSize.nHeight; 63 | 64 | return *this; 65 | } 66 | 67 | void 68 | swap(Size &rSize) 69 | { 70 | unsigned int nTemp; 71 | nTemp = nWidth; 72 | nWidth = rSize.nWidth; 73 | rSize.nWidth = nTemp; 74 | 75 | nTemp = nHeight; 76 | nHeight = rSize.nHeight; 77 | rSize.nHeight = nTemp; 78 | } 79 | }; 80 | 81 | Image() 82 | { }; 83 | 84 | Image(unsigned int nWidth, unsigned int nHeight) : oSize_(nWidth, nHeight) 85 | { }; 86 | 87 | Image(const Image::Size &rSize) : oSize_(rSize) 88 | { }; 89 | 90 | Image(const Image &rImage) : oSize_(rImage.oSize_) 91 | { }; 92 | 93 | virtual 94 | ~Image() 95 | { }; 96 | 97 | Image & 98 | operator= (const Image &rImage) 99 | { 100 | if (&rImage == this) 101 | { 102 | return *this; 103 | } 104 | 105 | oSize_ = rImage.oSize_; 106 | return *this; 107 | }; 108 | 109 | unsigned int 110 | width() 111 | const 112 | { 113 | return oSize_.nWidth; 114 | } 115 | 116 | unsigned int 117 | height() 118 | const 119 | { 120 | return oSize_.nHeight; 121 | } 122 | 123 | Size 124 | size() 125 | const 126 | { 127 | return oSize_; 128 | } 129 | 130 | void 131 | swap(Image &rImage) 132 | { 133 | oSize_.swap(rImage.oSize_); 134 | } 135 | 136 | private: 137 | Size oSize_; 138 | }; 139 | 140 | bool 141 | operator== (const Image::Size &rFirst, const Image::Size &rSecond) 142 | { 143 | return rFirst.nWidth == rSecond.nWidth && rFirst.nHeight == rSecond.nHeight; 144 | } 145 | 146 | bool 147 | operator!= (const Image::Size &rFirst, const Image::Size &rSecond) 148 | { 149 | return rFirst.nWidth != rSecond.nWidth || rFirst.nHeight != rSecond.nHeight; 150 | } 151 | 152 | } // npp namespace 153 | 154 | 155 | #endif // NV_UTIL_NPP_IMAGE_H 156 | -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/UtilNPP/ImageAllocatorsCPU.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. 2 | * 3 | * Redistribution and use in source and binary forms, with or without 4 | * modification, are permitted provided that the following conditions 5 | * are met: 6 | * * Redistributions of source code must retain the above copyright 7 | * notice, this list of conditions and the following disclaimer. 8 | * * Redistributions in binary form must reproduce the above copyright 9 | * notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * * Neither the name of NVIDIA CORPORATION nor the names of its 12 | * contributors may be used to endorse or promote products derived 13 | * from this software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY 16 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 18 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 19 | * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 20 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 21 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 22 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 23 | * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #ifndef NV_UTIL_NPP_IMAGE_ALLOCATORS_CPU_H 29 | #define NV_UTIL_NPP_IMAGE_ALLOCATORS_CPU_H 30 | 31 | #include "Exceptions.h" 32 | 33 | namespace npp 34 | { 35 | 36 | template 37 | class ImageAllocatorCPU 38 | { 39 | public: 40 | static 41 | D * 42 | Malloc2D(unsigned int nWidth, unsigned int nHeight, unsigned int *pPitch) 43 | { 44 | NPP_ASSERT(nWidth * nHeight > 0); 45 | 46 | D *pResult = new D[nWidth * N * nHeight]; 47 | *pPitch = nWidth * sizeof(D) * N; 48 | 49 | return pResult; 50 | }; 51 | 52 | static 53 | void 54 | Free2D(D *pPixels) 55 | { 56 | delete[] pPixels; 57 | }; 58 | 59 | static 60 | void 61 | Copy2D(D *pDst, size_t nDstPitch, const D *pSrc, size_t nSrcPitch, size_t nWidth, size_t nHeight) 62 | { 63 | const void *pSrcLine = pSrc; 64 | void *pDstLine = pDst; 65 | 66 | for (size_t iLine = 0; iLine < nHeight; ++iLine) 67 | { 68 | // copy one line worth of data 69 | memcpy(pDst, pSrc, nWidth * N * sizeof(D)); 70 | // move data pointers to next line 71 | pDst += nDstPitch; 72 | pSrc += nSrcPitch; 73 | } 74 | }; 75 | 76 | }; 77 | 78 | } // npp namespace 79 | 80 | #endif // NV_UTIL_NPP_IMAGE_ALLOCATORS_CPU_H 81 | -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/UtilNPP/ImageIO.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. 2 | * 3 | * Redistribution and use in source and binary forms, with or without 4 | * modification, are permitted provided that the following conditions 5 | * are met: 6 | * * Redistributions of source code must retain the above copyright 7 | * notice, this list of conditions and the following disclaimer. 8 | * * Redistributions in binary form must reproduce the above copyright 9 | * notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * * Neither the name of NVIDIA CORPORATION nor the names of its 12 | * contributors may be used to endorse or promote products derived 13 | * from this software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY 16 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 18 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 19 | * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 20 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 21 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 22 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 23 | * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #ifndef NV_UTIL_NPP_IMAGE_IO_H 29 | #define NV_UTIL_NPP_IMAGE_IO_H 30 | 31 | #include "ImagesCPU.h" 32 | #include "ImagesNPP.h" 33 | 34 | #include "FreeImage.h" 35 | #include "Exceptions.h" 36 | 37 | #include 38 | #include "string.h" 39 | 40 | 41 | // Error handler for FreeImage library. 42 | // In case this handler is invoked, it throws an NPP exception. 43 | void 44 | FreeImageErrorHandler(FREE_IMAGE_FORMAT oFif, const char *zMessage) 45 | { 46 | throw npp::Exception(zMessage); 47 | } 48 | 49 | namespace npp 50 | { 51 | // Load a gray-scale image from disk. 52 | void 53 | loadImage(const std::string &rFileName, ImageCPU_8u_C1 &rImage) 54 | { 55 | // set your own FreeImage error handler 56 | FreeImage_SetOutputMessage(FreeImageErrorHandler); 57 | 58 | FREE_IMAGE_FORMAT eFormat = FreeImage_GetFileType(rFileName.c_str()); 59 | 60 | // no signature? try to guess the file format from the file extension 61 | if (eFormat == FIF_UNKNOWN) 62 | { 63 | eFormat = FreeImage_GetFIFFromFilename(rFileName.c_str()); 64 | } 65 | 66 | NPP_ASSERT(eFormat != FIF_UNKNOWN); 67 | // check that the plugin has reading capabilities ... 68 | FIBITMAP *pBitmap; 69 | 70 | if (FreeImage_FIFSupportsReading(eFormat)) 71 | { 72 | pBitmap = FreeImage_Load(eFormat, rFileName.c_str()); 73 | } 74 | 75 | NPP_ASSERT(pBitmap != 0); 76 | // make sure this is an 8-bit single channel image 77 | NPP_ASSERT(FreeImage_GetColorType(pBitmap) == FIC_MINISBLACK); 78 | NPP_ASSERT(FreeImage_GetBPP(pBitmap) == 8); 79 | 80 | // create an ImageCPU to receive the loaded image data 81 | ImageCPU_8u_C1 oImage(FreeImage_GetWidth(pBitmap), FreeImage_GetHeight(pBitmap)); 82 | 83 | // Copy the FreeImage data into the new ImageCPU 84 | unsigned int nSrcPitch = FreeImage_GetPitch(pBitmap); 85 | const Npp8u *pSrcLine = FreeImage_GetBits(pBitmap) + nSrcPitch * (FreeImage_GetHeight(pBitmap) -1); 86 | Npp8u *pDstLine = oImage.data(); 87 | unsigned int nDstPitch = oImage.pitch(); 88 | 89 | for (size_t iLine = 0; iLine < oImage.height(); ++iLine) 90 | { 91 | memcpy(pDstLine, pSrcLine, oImage.width() * sizeof(Npp8u)); 92 | pSrcLine -= nSrcPitch; 93 | pDstLine += nDstPitch; 94 | } 95 | 96 | // swap the user given image with our result image, effecively 97 | // moving our newly loaded image data into the user provided shell 98 | oImage.swap(rImage); 99 | } 100 | 101 | // Save an gray-scale image to disk. 102 | void 103 | saveImage(const std::string &rFileName, const ImageCPU_8u_C1 &rImage) 104 | { 105 | // create the result image storage using FreeImage so we can easily 106 | // save 107 | FIBITMAP *pResultBitmap = FreeImage_Allocate(rImage.width(), rImage.height(), 8 /* bits per pixel */); 108 | NPP_ASSERT_NOT_NULL(pResultBitmap); 109 | unsigned int nDstPitch = FreeImage_GetPitch(pResultBitmap); 110 | Npp8u *pDstLine = FreeImage_GetBits(pResultBitmap) + nDstPitch * (rImage.height()-1); 111 | const Npp8u *pSrcLine = rImage.data(); 112 | unsigned int nSrcPitch = rImage.pitch(); 113 | 114 | for (size_t iLine = 0; iLine < rImage.height(); ++iLine) 115 | { 116 | memcpy(pDstLine, pSrcLine, rImage.width() * sizeof(Npp8u)); 117 | pSrcLine += nSrcPitch; 118 | pDstLine -= nDstPitch; 119 | } 120 | 121 | // now save the result image 122 | bool bSuccess; 123 | bSuccess = FreeImage_Save(FIF_PGM, pResultBitmap, rFileName.c_str(), 0) == TRUE; 124 | NPP_ASSERT_MSG(bSuccess, "Failed to save result image."); 125 | } 126 | 127 | // Load a gray-scale image from disk. 128 | void 129 | loadImage(const std::string &rFileName, ImageNPP_8u_C1 &rImage) 130 | { 131 | ImageCPU_8u_C1 oImage; 132 | loadImage(rFileName, oImage); 133 | ImageNPP_8u_C1 oResult(oImage); 134 | rImage.swap(oResult); 135 | } 136 | 137 | // Save an gray-scale image to disk. 138 | void 139 | saveImage(const std::string &rFileName, const ImageNPP_8u_C1 &rImage) 140 | { 141 | ImageCPU_8u_C1 oHostImage(rImage.size()); 142 | // copy the device result data 143 | rImage.copyTo(oHostImage.data(), oHostImage.pitch()); 144 | saveImage(rFileName, oHostImage); 145 | } 146 | } 147 | 148 | 149 | #endif // NV_UTIL_NPP_IMAGE_IO_H 150 | -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/UtilNPP/ImagePacked.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. 2 | * 3 | * Redistribution and use in source and binary forms, with or without 4 | * modification, are permitted provided that the following conditions 5 | * are met: 6 | * * Redistributions of source code must retain the above copyright 7 | * notice, this list of conditions and the following disclaimer. 8 | * * Redistributions in binary form must reproduce the above copyright 9 | * notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * * Neither the name of NVIDIA CORPORATION nor the names of its 12 | * contributors may be used to endorse or promote products derived 13 | * from this software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY 16 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 18 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 19 | * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 20 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 21 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 22 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 23 | * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #ifndef NV_UTIL_NPP_IMAGE_PACKED_H 29 | #define NV_UTIL_NPP_IMAGE_PACKED_H 30 | 31 | #include "Image.h" 32 | #include "Pixel.h" 33 | 34 | namespace npp 35 | { 36 | template 37 | class ImagePacked: public npp::Image 38 | { 39 | public: 40 | typedef npp::Pixel tPixel; 41 | typedef D tData; 42 | static const size_t gnChannels = N; 43 | typedef npp::Image::Size tSize; 44 | 45 | ImagePacked(): aPixels_(0) 46 | , nPitch_(0) 47 | { 48 | ; 49 | } 50 | 51 | ImagePacked(unsigned int nWidth, unsigned int nHeight): Image(nWidth, nHeight) 52 | , aPixels_(0) 53 | , nPitch_(0) 54 | { 55 | aPixels_ = A::Malloc2D(width(), height(), &nPitch_); 56 | } 57 | 58 | ImagePacked(unsigned int nWidth, unsigned int nHeight, bool bTight): Image(nWidth, nHeight) 59 | , aPixels_(0) 60 | , nPitch_(0) 61 | { 62 | aPixels_ = A::Malloc2D(width(), height(), &nPitch_, bTight); 63 | } 64 | 65 | ImagePacked(const tSize &rSize): Image(rSize) 66 | , aPixels_(0) 67 | , nPitch_(0) 68 | { 69 | aPixels_ = A::Malloc2D(width(), height(), &nPitch_); 70 | } 71 | 72 | ImagePacked(const ImagePacked &rImage): Image(rImage) 73 | , aPixels_(0) 74 | , nPitch_(rImage.pitch()) 75 | { 76 | aPixels_ = A::Malloc2D(width(), height(), &nPitch_); 77 | A::Copy2D(aPixels_, nPitch_, rImage.pixels(), rImage.pitch(), width(), height()); 78 | } 79 | 80 | virtual 81 | ~ImagePacked() 82 | { 83 | A::Free2D(aPixels_); 84 | } 85 | 86 | ImagePacked & 87 | operator= (const ImagePacked &rImage) 88 | { 89 | // in case of self-assignment 90 | if (&rImage == this) 91 | { 92 | return *this; 93 | } 94 | 95 | A::Free2D(aPixels_); 96 | aPixels_ = 0; 97 | nPitch_ = 0; 98 | 99 | // assign parent class's data fields (width, height) 100 | Image::operator =(rImage); 101 | 102 | aPixels_ = A::Malloc2D(width(), height(), &nPitch_); 103 | A::Copy2D(aPixels_, nPitch_, rImage.data(), rImage.pitch(), width(), height()); 104 | 105 | return *this; 106 | } 107 | 108 | unsigned int 109 | pitch() 110 | const 111 | { 112 | return nPitch_; 113 | } 114 | 115 | /// Get a pointer to the pixel array. 116 | /// The result pointer can be offset to pixel at position (x, y) and 117 | /// even negative offsets are allowed. 118 | /// \param nX Horizontal pointer/array offset. 119 | /// \param nY Vertical pointer/array offset. 120 | /// \return Pointer to the pixel array (or first pixel in array with coordinates (nX, nY). 121 | tPixel * 122 | pixels(int nX = 0, int nY = 0) 123 | { 124 | return reinterpret_cast(reinterpret_cast(aPixels_) + nY * pitch() + nX * gnChannels * sizeof(D)); 125 | } 126 | 127 | const 128 | tPixel * 129 | pixels(int nX = 0, int nY = 0) 130 | const 131 | { 132 | return reinterpret_cast(reinterpret_cast(aPixels_) + nY * pitch() + nX * gnChannels * sizeof(D)); 133 | } 134 | 135 | D * 136 | data(int nX = 0, int nY = 0) 137 | { 138 | return reinterpret_cast(pixels(nX, nY)); 139 | } 140 | 141 | const 142 | D * 143 | data(int nX = 0, int nY = 0) 144 | const 145 | { 146 | return reinterpret_cast(pixels(nX, nY)); 147 | } 148 | 149 | void 150 | swap(ImagePacked &rImage) 151 | { 152 | Image::swap(rImage); 153 | 154 | tData *aTemp = aPixels_; 155 | aPixels_ = rImage.aPixels_; 156 | rImage.aPixels_ = aTemp; 157 | 158 | unsigned int nTemp = nPitch_; 159 | nPitch_ = rImage.nPitch_; 160 | rImage.nPitch_ = nTemp; 161 | } 162 | 163 | private: 164 | D *aPixels_; 165 | unsigned int nPitch_; 166 | }; 167 | 168 | } // npp namespace 169 | 170 | 171 | #endif // NV_IMAGE_IPP_H 172 | -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/UtilNPP/ImagesCPU.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. 2 | * 3 | * Redistribution and use in source and binary forms, with or without 4 | * modification, are permitted provided that the following conditions 5 | * are met: 6 | * * Redistributions of source code must retain the above copyright 7 | * notice, this list of conditions and the following disclaimer. 8 | * * Redistributions in binary form must reproduce the above copyright 9 | * notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * * Neither the name of NVIDIA CORPORATION nor the names of its 12 | * contributors may be used to endorse or promote products derived 13 | * from this software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY 16 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 18 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 19 | * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 20 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 21 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 22 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 23 | * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #ifndef NV_UTIL_NPP_IMAGES_CPU_H 29 | #define NV_UTIL_NPP_IMAGES_CPU_H 30 | 31 | #include "ImagePacked.h" 32 | 33 | #include "ImageAllocatorsCPU.h" 34 | #include "Exceptions.h" 35 | 36 | #include 37 | 38 | 39 | namespace npp 40 | { 41 | 42 | template 43 | class ImageCPU: public npp::ImagePacked 44 | { 45 | public: 46 | 47 | ImageCPU() 48 | { 49 | ; 50 | } 51 | 52 | ImageCPU(unsigned int nWidth, unsigned int nHeight): ImagePacked(nWidth, nHeight) 53 | { 54 | ; 55 | } 56 | 57 | explicit 58 | ImageCPU(const npp::Image::Size &rSize): ImagePacked(rSize) 59 | { 60 | ; 61 | } 62 | 63 | ImageCPU(const ImageCPU &rImage): Image(rImage) 64 | { 65 | ; 66 | } 67 | 68 | virtual 69 | ~ImageCPU() 70 | { 71 | ; 72 | } 73 | 74 | ImageCPU & 75 | operator= (const ImageCPU &rImage) 76 | { 77 | ImagePacked::operator= (rImage); 78 | 79 | return *this; 80 | } 81 | 82 | npp::Pixel & 83 | operator()(unsigned int iX, unsigned int iY) 84 | { 85 | return *ImagePacked::pixels(iX, iY); 86 | } 87 | 88 | npp::Pixel 89 | operator()(unsigned int iX, unsigned int iY) 90 | const 91 | { 92 | return *ImagePacked::pixels(iX, iY); 93 | } 94 | 95 | }; 96 | 97 | 98 | typedef ImageCPU > ImageCPU_8u_C1; 99 | typedef ImageCPU > ImageCPU_8u_C2; 100 | typedef ImageCPU > ImageCPU_8u_C3; 101 | typedef ImageCPU > ImageCPU_8u_C4; 102 | 103 | typedef ImageCPU > ImageCPU_16u_C1; 104 | typedef ImageCPU > ImageCPU_16u_C3; 105 | typedef ImageCPU > ImageCPU_16u_C4; 106 | 107 | typedef ImageCPU > ImageCPU_16s_C1; 108 | typedef ImageCPU > ImageCPU_16s_C3; 109 | typedef ImageCPU > ImageCPU_16s_C4; 110 | 111 | typedef ImageCPU > ImageCPU_32s_C1; 112 | typedef ImageCPU > ImageCPU_32s_C3; 113 | typedef ImageCPU > ImageCPU_32s_C4; 114 | 115 | typedef ImageCPU > ImageCPU_32f_C1; 116 | typedef ImageCPU > ImageCPU_32f_C3; 117 | typedef ImageCPU > ImageCPU_32f_C4; 118 | 119 | } // npp namespace 120 | 121 | #endif // NV_IMAGE_IPP_H 122 | -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/UtilNPP/Pixel.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. 2 | * 3 | * Redistribution and use in source and binary forms, with or without 4 | * modification, are permitted provided that the following conditions 5 | * are met: 6 | * * Redistributions of source code must retain the above copyright 7 | * notice, this list of conditions and the following disclaimer. 8 | * * Redistributions in binary form must reproduce the above copyright 9 | * notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * * Neither the name of NVIDIA CORPORATION nor the names of its 12 | * contributors may be used to endorse or promote products derived 13 | * from this software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY 16 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 18 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 19 | * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 20 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 21 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 22 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 23 | * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | 29 | #ifndef NV_UTIL_PIXEL_H 30 | #define NV_UTIL_PIXEL_H 31 | 32 | #include "Exceptions.h" 33 | 34 | namespace npp 35 | { 36 | template 37 | struct Pixel 38 | { }; 39 | 40 | template 41 | struct Pixel 42 | { 43 | D x; 44 | 45 | const D & 46 | operator[](size_t iChannel) 47 | const 48 | { 49 | NPP_ASSERT(iChannel < 1); 50 | return (&x)[iChannel]; 51 | } 52 | 53 | D & 54 | operator[](size_t iChannel) 55 | { 56 | NPP_ASSERT(iChannel < 1); 57 | return (&x)[iChannel]; 58 | } 59 | }; 60 | 61 | template 62 | struct Pixel 63 | { 64 | D x,y; 65 | 66 | const D & 67 | operator[](size_t iChannel) 68 | const 69 | { 70 | NPP_ASSERT(iChannel < 2); 71 | return (&x)[iChannel]; 72 | } 73 | 74 | D & 75 | operator[](size_t iChannel) 76 | { 77 | NPP_ASSERT(iChannel < 2); 78 | return (&x)[iChannel]; 79 | } 80 | }; 81 | 82 | template 83 | struct Pixel 84 | { 85 | D x,y,z; 86 | 87 | const D & 88 | operator[](size_t iChannel) 89 | const 90 | { 91 | NPP_ASSERT(iChannel < 3); 92 | return (&x)[iChannel]; 93 | } 94 | 95 | D & 96 | operator[](size_t iChannel) 97 | { 98 | NPP_ASSERT(iChannel < 3); 99 | return (&x)[iChannel]; 100 | } 101 | }; 102 | 103 | template 104 | struct Pixel 105 | { 106 | D x, y, z, w; 107 | 108 | const D & 109 | operator[](size_t iChannel) 110 | const 111 | { 112 | NPP_ASSERT(iChannel < 4); 113 | return (&x)[iChannel]; 114 | } 115 | 116 | D & 117 | operator[](size_t iChannel) 118 | { 119 | NPP_ASSERT(iChannel < 4); 120 | return (&x)[iChannel]; 121 | } 122 | }; 123 | 124 | } // npp namespace 125 | 126 | #endif // NV_UTIL_PIXEL_H 127 | -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/UtilNPP/Signal.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. 2 | * 3 | * Redistribution and use in source and binary forms, with or without 4 | * modification, are permitted provided that the following conditions 5 | * are met: 6 | * * Redistributions of source code must retain the above copyright 7 | * notice, this list of conditions and the following disclaimer. 8 | * * Redistributions in binary form must reproduce the above copyright 9 | * notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * * Neither the name of NVIDIA CORPORATION nor the names of its 12 | * contributors may be used to endorse or promote products derived 13 | * from this software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY 16 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 18 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 19 | * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 20 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 21 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 22 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 23 | * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | 29 | #ifndef NV_UTIL_NPP_SIGNAL_H 30 | #define NV_UTIL_NPP_SIGNAL_H 31 | 32 | #include 33 | 34 | namespace npp 35 | { 36 | class Signal 37 | { 38 | public: 39 | Signal() : nSize_(0) 40 | { }; 41 | 42 | explicit 43 | Signal(size_t nSize) : nSize_(nSize) 44 | { }; 45 | 46 | Signal(const Signal &rSignal) : nSize_(rSignal.nSize_) 47 | { }; 48 | 49 | virtual 50 | ~Signal() 51 | { } 52 | 53 | Signal & 54 | operator= (const Signal &rSignal) 55 | { 56 | nSize_ = rSignal.nSize_; 57 | return *this; 58 | } 59 | 60 | size_t 61 | size() 62 | const 63 | { 64 | return nSize_; 65 | } 66 | 67 | void 68 | swap(Signal &rSignal) 69 | { 70 | size_t nTemp = nSize_; 71 | nSize_ = rSignal.nSize_; 72 | rSignal.nSize_ = nTemp; 73 | } 74 | 75 | 76 | private: 77 | size_t nSize_; 78 | }; 79 | 80 | template 81 | class SignalTemplate: public Signal 82 | { 83 | public: 84 | typedef D tData; 85 | 86 | SignalTemplate(): aValues_(0) 87 | { 88 | ; 89 | } 90 | 91 | SignalTemplate(size_t nSize): Signal(nSize) 92 | , aValues_(0) 93 | { 94 | aValues_ = A::Malloc1D(size()); 95 | } 96 | 97 | SignalTemplate(const SignalTemplate &rSignal): Signal(rSignal) 98 | , aValues_(0) 99 | { 100 | aValues_ = A::Malloc1D(size()); 101 | A::Copy1D(aValues_, rSignal.values(), size()); 102 | } 103 | 104 | virtual 105 | ~SignalTemplate() 106 | { 107 | A::Free1D(aValues_); 108 | } 109 | 110 | SignalTemplate & 111 | operator= (const SignalTemplate &rSignal) 112 | { 113 | // in case of self-assignment 114 | if (&rSignal == this) 115 | { 116 | return *this; 117 | } 118 | 119 | A::Free1D(aValues_); 120 | this->aPixels_ = 0; 121 | 122 | // assign parent class's data fields (width, height) 123 | Signal::operator =(rSignal); 124 | 125 | aValues_ = A::Malloc1D(size()); 126 | A::Copy1D(aValues_, rSignal.value(), size()); 127 | 128 | return *this; 129 | } 130 | 131 | /// Get a pointer to the pixel array. 132 | /// The result pointer can be offset to pixel at position (x, y) and 133 | /// even negative offsets are allowed. 134 | /// \param nX Horizontal pointer/array offset. 135 | /// \param nY Vertical pointer/array offset. 136 | /// \return Pointer to the pixel array (or first pixel in array with coordinates (nX, nY). 137 | tData * 138 | values(int i = 0) 139 | { 140 | return aValues_ + i; 141 | } 142 | 143 | const 144 | tData * 145 | values(int i = 0) 146 | const 147 | { 148 | return aValues_ + i; 149 | } 150 | 151 | void 152 | swap(SignalTemplate &rSignal) 153 | { 154 | Signal::swap(rSignal); 155 | 156 | tData *aTemp = this->aValues_; 157 | this->aValues_ = rSignal.aValues_; 158 | rSignal.aValues_ = aTemp; 159 | } 160 | 161 | private: 162 | D *aValues_; 163 | }; 164 | 165 | } // npp namespace 166 | 167 | 168 | #endif // NV_UTIL_NPP_SIGNAL_H 169 | -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/UtilNPP/SignalAllocatorsCPU.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. 2 | * 3 | * Redistribution and use in source and binary forms, with or without 4 | * modification, are permitted provided that the following conditions 5 | * are met: 6 | * * Redistributions of source code must retain the above copyright 7 | * notice, this list of conditions and the following disclaimer. 8 | * * Redistributions in binary form must reproduce the above copyright 9 | * notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * * Neither the name of NVIDIA CORPORATION nor the names of its 12 | * contributors may be used to endorse or promote products derived 13 | * from this software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY 16 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 18 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 19 | * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 20 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 21 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 22 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 23 | * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | 29 | #ifndef NV_UTIL_NPP_SIGNAL_ALLOCATORS_CPU_H 30 | #define NV_UTIL_NPP_SIGNAL_ALLOCATORS_CPU_H 31 | 32 | #include "Exceptions.h" 33 | 34 | namespace npp 35 | { 36 | 37 | template 38 | class SignalAllocatorCPU 39 | { 40 | public: 41 | static 42 | D * 43 | Malloc1D(unsigned int nSize) 44 | { 45 | return new D[nSize];; 46 | }; 47 | 48 | static 49 | void 50 | Free1D(D *pPixels) 51 | { 52 | delete[] pPixels; 53 | }; 54 | 55 | static 56 | void 57 | Copy1D(D *pDst, const D *pSrc, size_t nSize) 58 | { 59 | memcpy(pDst, pSrc, nSize * sizeof(D)); 60 | }; 61 | 62 | }; 63 | 64 | } // npp namespace 65 | 66 | #endif // NV_UTIL_NPP_SIGNAL_ALLOCATORS_CPU_H 67 | -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/UtilNPP/SignalsCPU.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. 2 | * 3 | * Redistribution and use in source and binary forms, with or without 4 | * modification, are permitted provided that the following conditions 5 | * are met: 6 | * * Redistributions of source code must retain the above copyright 7 | * notice, this list of conditions and the following disclaimer. 8 | * * Redistributions in binary form must reproduce the above copyright 9 | * notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * * Neither the name of NVIDIA CORPORATION nor the names of its 12 | * contributors may be used to endorse or promote products derived 13 | * from this software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY 16 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 18 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 19 | * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 20 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 21 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 22 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 23 | * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | 29 | #ifndef NV_UTIL_NPP_SIGNALS_CPU_H 30 | #define NV_UTIL_NPP_SIGNALS_CPU_H 31 | 32 | #include "Signal.h" 33 | 34 | #include "SignalAllocatorsCPU.h" 35 | #include "Exceptions.h" 36 | 37 | #include 38 | 39 | 40 | namespace npp 41 | { 42 | 43 | template 44 | class SignalCPU: public npp::SignalTemplate 45 | { 46 | public: 47 | typedef typename npp::SignalTemplate::tData tData; 48 | 49 | SignalCPU() 50 | { 51 | ; 52 | } 53 | 54 | SignalCPU(size_t nSize): SignalTemplate(nSize) 55 | { 56 | ; 57 | } 58 | 59 | SignalCPU(const SignalCPU &rSignal): SignalTemplate(rSignal) 60 | { 61 | ; 62 | } 63 | 64 | virtual 65 | ~SignalCPU() 66 | { 67 | ; 68 | } 69 | 70 | SignalCPU & 71 | operator= (const SignalCPU &rSignal) 72 | { 73 | SignalTemplate::operator= (rSignal); 74 | 75 | return *this; 76 | } 77 | 78 | tData & 79 | operator [](unsigned int i) 80 | { 81 | return *SignalTemplate::values(i); 82 | } 83 | 84 | tData 85 | operator [](unsigned int i) 86 | const 87 | { 88 | return *SignalTemplate::values(i); 89 | } 90 | 91 | }; 92 | 93 | typedef SignalCPU > SignalCPU_8u; 94 | typedef SignalCPU > SignalCPU_32s; 95 | typedef SignalCPU > SignalCPU_16s; 96 | typedef SignalCPU > SignalCPU_16sc; 97 | typedef SignalCPU > SignalCPU_32sc; 98 | typedef SignalCPU > SignalCPU_32f; 99 | typedef SignalCPU > SignalCPU_32fc; 100 | typedef SignalCPU > SignalCPU_64s; 101 | typedef SignalCPU > SignalCPU_64sc; 102 | typedef SignalCPU > SignalCPU_64f; 103 | typedef SignalCPU > SignalCPU_64fc; 104 | 105 | } // npp namespace 106 | 107 | #endif // NV_UTIL_NPP_SIGNALS_CPU_H 108 | -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/UtilNPP/SignalsNPP.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. 2 | * 3 | * Redistribution and use in source and binary forms, with or without 4 | * modification, are permitted provided that the following conditions 5 | * are met: 6 | * * Redistributions of source code must retain the above copyright 7 | * notice, this list of conditions and the following disclaimer. 8 | * * Redistributions in binary form must reproduce the above copyright 9 | * notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * * Neither the name of NVIDIA CORPORATION nor the names of its 12 | * contributors may be used to endorse or promote products derived 13 | * from this software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY 16 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 18 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 19 | * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 20 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 21 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 22 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 23 | * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | 29 | #ifndef NV_UTIL_NPP_SIGNALS_NPP_H 30 | #define NV_UTIL_NPP_SIGNALS_NPP_H 31 | 32 | #include "Exceptions.h" 33 | #include "Signal.h" 34 | 35 | #include "SignalAllocatorsNPP.h" 36 | #include 37 | 38 | namespace npp 39 | { 40 | // forward declaration 41 | template class SignalCPU; 42 | 43 | template 44 | class SignalNPP: public npp::SignalTemplate > 45 | { 46 | public: 47 | SignalNPP() 48 | { 49 | ; 50 | } 51 | 52 | explicit 53 | SignalNPP(size_t nSize): SignalTemplate >(nSize) 54 | { 55 | ; 56 | } 57 | 58 | SignalNPP(const SignalNPP &rSignal): SignalTemplate >(rSignal) 59 | { 60 | ; 61 | } 62 | 63 | template 64 | explicit 65 | SignalNPP(const SignalCPU &rSignal): SignalTemplate >(rSignal.size()) 66 | { 67 | npp::SignalAllocator::HostToDeviceCopy1D(SignalTemplate >::values(), 68 | rSignal.values(), SignalTemplate >::size()); 69 | } 70 | 71 | virtual 72 | ~SignalNPP() 73 | { 74 | ; 75 | } 76 | 77 | SignalNPP & 78 | operator= (const SignalNPP &rSignal) 79 | { 80 | SignalTemplate >::operator= (rSignal); 81 | 82 | return *this; 83 | } 84 | 85 | void 86 | copyTo(D *pValues) 87 | const 88 | { 89 | npp::SignalAllocator::DeviceToHostCopy1D(pValues, SignalTemplate >::values(), SignalTemplate >::size()); 90 | } 91 | 92 | void 93 | copyFrom(D *pValues) 94 | { 95 | npp::SignalAllocator::HostToDeviceCopy1D(SignalTemplate >::values(), pValues, SignalTemplate >::size()); 96 | } 97 | }; 98 | 99 | typedef SignalNPP SignalNPP_8u; 100 | typedef SignalNPP SignalNPP_16s; 101 | typedef SignalNPP SignalNPP_16sc; 102 | typedef SignalNPP SignalNPP_32s; 103 | typedef SignalNPP SignalNPP_32sc; 104 | typedef SignalNPP SignalNPP_32f; 105 | typedef SignalNPP SignalNPP_32fc; 106 | typedef SignalNPP SignalNPP_64s; 107 | typedef SignalNPP SignalNPP_64sc; 108 | typedef SignalNPP SignalNPP_64f; 109 | typedef SignalNPP SignalNPP_64fc; 110 | 111 | } // npp namespace 112 | 113 | #endif // NV_UTIL_NPP_SIGNALS_NPP_H 114 | -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/data/CT_skull_512x512_8u.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rtlyc/antfields-demo/3743ba2a41699ceea57051162388643c8d0e33fb/bvh-distance-queries/cuda-samples/Common/data/CT_skull_512x512_8u.raw -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/data/CT_skull_512x512_8u_Gray.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rtlyc/antfields-demo/3743ba2a41699ceea57051162388643c8d0e33fb/bvh-distance-queries/cuda-samples/Common/data/CT_skull_512x512_8u_Gray.raw -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/data/PCB2_1024x683_8u.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rtlyc/antfields-demo/3743ba2a41699ceea57051162388643c8d0e33fb/bvh-distance-queries/cuda-samples/Common/data/PCB2_1024x683_8u.raw -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/data/PCB_1280x720_8u.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rtlyc/antfields-demo/3743ba2a41699ceea57051162388643c8d0e33fb/bvh-distance-queries/cuda-samples/Common/data/PCB_1280x720_8u.raw -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/data/PCB_METAL_509x335_8u.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rtlyc/antfields-demo/3743ba2a41699ceea57051162388643c8d0e33fb/bvh-distance-queries/cuda-samples/Common/data/PCB_METAL_509x335_8u.raw -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/data/Rocks_512x512_8u_Gray.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rtlyc/antfields-demo/3743ba2a41699ceea57051162388643c8d0e33fb/bvh-distance-queries/cuda-samples/Common/data/Rocks_512x512_8u_Gray.raw -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/data/teapot512.pgm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rtlyc/antfields-demo/3743ba2a41699ceea57051162388643c8d0e33fb/bvh-distance-queries/cuda-samples/Common/data/teapot512.pgm -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/data/teapot_512x512_8u.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rtlyc/antfields-demo/3743ba2a41699ceea57051162388643c8d0e33fb/bvh-distance-queries/cuda-samples/Common/data/teapot_512x512_8u.raw -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/data/teapot_512x512_8u_Gray.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rtlyc/antfields-demo/3743ba2a41699ceea57051162388643c8d0e33fb/bvh-distance-queries/cuda-samples/Common/data/teapot_512x512_8u_Gray.raw -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/dynlink_d3d11.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. 2 | * 3 | * Redistribution and use in source and binary forms, with or without 4 | * modification, are permitted provided that the following conditions 5 | * are met: 6 | * * Redistributions of source code must retain the above copyright 7 | * notice, this list of conditions and the following disclaimer. 8 | * * Redistributions in binary form must reproduce the above copyright 9 | * notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * * Neither the name of NVIDIA CORPORATION nor the names of its 12 | * contributors may be used to endorse or promote products derived 13 | * from this software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY 16 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 18 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 19 | * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 20 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 21 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 22 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 23 | * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | //-------------------------------------------------------------------------------------- 29 | // File: dynlink_d3d11.h 30 | // 31 | // Shortcut macros and functions for using DX objects 32 | // 33 | // Copyright (c) Microsoft Corporation. All rights reserved 34 | //-------------------------------------------------------------------------------------- 35 | 36 | #ifndef _DYNLINK_D3D11_H_ 37 | #define _DYNLINK_D3D11_H_ 38 | 39 | // Standard Windows includes 40 | #include 41 | #include 42 | #include 43 | #include 44 | #include 45 | #include // for InitCommonControls() 46 | #include // for ExtractIcon() 47 | #include // for placement new 48 | #include 49 | #include 50 | #include 51 | #include 52 | 53 | // CRT's memory leak detection 54 | #if defined(DEBUG) || defined(_DEBUG) 55 | #include 56 | #endif 57 | 58 | // Direct3D10 includes 59 | #include 60 | #include 61 | // #include <..\Samples\C++\Effects11\Inc\d3dx11effect.h> 62 | 63 | // XInput includes 64 | #include 65 | 66 | // strsafe.h deprecates old unsecure string functions. If you 67 | // really do not want to it to (not recommended), then uncomment the next line 68 | //#define STRSAFE_NO_DEPRECATE 69 | 70 | #ifndef STRSAFE_NO_DEPRECATE 71 | #pragma deprecated("strncpy") 72 | #pragma deprecated("wcsncpy") 73 | #pragma deprecated("_tcsncpy") 74 | #pragma deprecated("wcsncat") 75 | #pragma deprecated("strncat") 76 | #pragma deprecated("_tcsncat") 77 | #endif 78 | 79 | #pragma warning( disable : 4996 ) // disable deprecated warning 80 | #include 81 | #pragma warning( default : 4996 ) 82 | 83 | typedef HRESULT(WINAPI *LPCREATEDXGIFACTORY)(REFIID, void **); 84 | typedef HRESULT(WINAPI *LPD3D11CREATEDEVICEANDSWAPCHAIN)(__in_opt IDXGIAdapter *pAdapter, D3D_DRIVER_TYPE DriverType, HMODULE Software, UINT Flags, __in_ecount_opt(FeatureLevels) CONST D3D_FEATURE_LEVEL *pFeatureLevels, UINT FeatureLevels, UINT SDKVersion, __in_opt CONST DXGI_SWAP_CHAIN_DESC *pSwapChainDesc, __out_opt IDXGISwapChain **ppSwapChain, __out_opt ID3D11Device **ppDevice, __out_opt D3D_FEATURE_LEVEL *pFeatureLevel, __out_opt ID3D11DeviceContext **ppImmediateContext); 85 | typedef HRESULT(WINAPI *LPD3D11CREATEDEVICE)(IDXGIAdapter *, D3D_DRIVER_TYPE, HMODULE, UINT32, D3D_FEATURE_LEVEL *, UINT, UINT32, ID3D11Device **, D3D_FEATURE_LEVEL *, ID3D11DeviceContext **); 86 | 87 | static HMODULE s_hModDXGI = NULL; 88 | static LPCREATEDXGIFACTORY sFnPtr_CreateDXGIFactory = NULL; 89 | static HMODULE s_hModD3D11 = NULL; 90 | static LPD3D11CREATEDEVICE sFnPtr_D3D11CreateDevice = NULL; 91 | static LPD3D11CREATEDEVICEANDSWAPCHAIN sFnPtr_D3D11CreateDeviceAndSwapChain = NULL; 92 | 93 | // unload the D3D10 DLLs 94 | static bool dynlinkUnloadD3D11API(void) 95 | { 96 | if (s_hModDXGI) 97 | { 98 | FreeLibrary(s_hModDXGI); 99 | s_hModDXGI = NULL; 100 | } 101 | 102 | if (s_hModD3D11) 103 | { 104 | FreeLibrary(s_hModD3D11); 105 | s_hModD3D11 = NULL; 106 | } 107 | 108 | return true; 109 | } 110 | 111 | // Dynamically load the D3D11 DLLs loaded and map the function pointers 112 | static bool dynlinkLoadD3D11API(void) 113 | { 114 | // If both modules are non-NULL, this function has already been called. Note 115 | // that this doesn't guarantee that all ProcAddresses were found. 116 | if (s_hModD3D11 != NULL && s_hModDXGI != NULL) 117 | { 118 | return true; 119 | } 120 | 121 | #if 1 122 | // This may fail if Direct3D 11 isn't installed 123 | s_hModD3D11 = LoadLibrary("d3d11.dll"); 124 | 125 | if (s_hModD3D11 != NULL) 126 | { 127 | sFnPtr_D3D11CreateDevice = (LPD3D11CREATEDEVICE)GetProcAddress(s_hModD3D11, "D3D11CreateDevice"); 128 | sFnPtr_D3D11CreateDeviceAndSwapChain = (LPD3D11CREATEDEVICEANDSWAPCHAIN)GetProcAddress(s_hModD3D11, "D3D11CreateDeviceAndSwapChain"); 129 | } 130 | else 131 | { 132 | printf("\nLoad d3d11.dll failed\n"); 133 | fflush(0); 134 | } 135 | 136 | if (!sFnPtr_CreateDXGIFactory) 137 | { 138 | s_hModDXGI = LoadLibrary("dxgi.dll"); 139 | 140 | if (s_hModDXGI) 141 | { 142 | sFnPtr_CreateDXGIFactory = (LPCREATEDXGIFACTORY)GetProcAddress(s_hModDXGI, "CreateDXGIFactory1"); 143 | } 144 | 145 | return (s_hModDXGI != NULL) && (s_hModD3D11 != NULL); 146 | } 147 | 148 | return (s_hModD3D11 != NULL); 149 | #else 150 | sFnPtr_D3D11CreateDevice = (LPD3D11CREATEDEVICE)D3D11CreateDeviceAndSwapChain; 151 | sFnPtr_D3D11CreateDeviceAndSwapChain = (LPD3D11CREATEDEVICEANDSWAPCHAIN)D3D11CreateDeviceAndSwapChain; 152 | //sFnPtr_D3DX11CreateEffectFromMemory = ( LPD3DX11CREATEEFFECTFROMMEMORY )D3DX11CreateEffectFromMemory; 153 | sFnPtr_D3DX11CompileFromMemory = (LPD3DX11COMPILEFROMMEMORY)D3DX11CompileFromMemory; 154 | sFnPtr_CreateDXGIFactory = (LPCREATEDXGIFACTORY)CreateDXGIFactory; 155 | return true; 156 | #endif 157 | return true; 158 | } 159 | 160 | #endif 161 | -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/exception.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. 2 | * 3 | * Redistribution and use in source and binary forms, with or without 4 | * modification, are permitted provided that the following conditions 5 | * are met: 6 | * * Redistributions of source code must retain the above copyright 7 | * notice, this list of conditions and the following disclaimer. 8 | * * Redistributions in binary form must reproduce the above copyright 9 | * notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * * Neither the name of NVIDIA CORPORATION nor the names of its 12 | * contributors may be used to endorse or promote products derived 13 | * from this software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY 16 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 18 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 19 | * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 20 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 21 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 22 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 23 | * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | /* CUda UTility Library */ 29 | #ifndef COMMON_EXCEPTION_H_ 30 | #define COMMON_EXCEPTION_H_ 31 | 32 | // includes, system 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | 39 | //! Exception wrapper. 40 | //! @param Std_Exception Exception out of namespace std for easy typing. 41 | template 42 | class Exception : public Std_Exception { 43 | public: 44 | //! @brief Static construction interface 45 | //! @return Alwayss throws ( Located_Exception) 46 | //! @param file file in which the Exception occurs 47 | //! @param line line in which the Exception occurs 48 | //! @param detailed details on the code fragment causing the Exception 49 | static void throw_it(const char *file, const int line, 50 | const char *detailed = "-"); 51 | 52 | //! Static construction interface 53 | //! @return Alwayss throws ( Located_Exception) 54 | //! @param file file in which the Exception occurs 55 | //! @param line line in which the Exception occurs 56 | //! @param detailed details on the code fragment causing the Exception 57 | static void throw_it(const char *file, const int line, 58 | const std::string &detailed); 59 | 60 | //! Destructor 61 | virtual ~Exception() throw(); 62 | 63 | private: 64 | //! Constructor, default (private) 65 | Exception(); 66 | 67 | //! Constructor, standard 68 | //! @param str string returned by what() 69 | explicit Exception(const std::string &str); 70 | }; 71 | 72 | //////////////////////////////////////////////////////////////////////////////// 73 | //! Exception handler function for arbitrary exceptions 74 | //! @param ex exception to handle 75 | //////////////////////////////////////////////////////////////////////////////// 76 | template 77 | inline void handleException(const Exception_Typ &ex) { 78 | std::cerr << ex.what() << std::endl; 79 | 80 | exit(EXIT_FAILURE); 81 | } 82 | 83 | //! Convenience macros 84 | 85 | //! Exception caused by dynamic program behavior, e.g. file does not exist 86 | #define RUNTIME_EXCEPTION(msg) \ 87 | Exception::throw_it(__FILE__, __LINE__, msg) 88 | 89 | //! Logic exception in program, e.g. an assert failed 90 | #define LOGIC_EXCEPTION(msg) \ 91 | Exception::throw_it(__FILE__, __LINE__, msg) 92 | 93 | //! Out of range exception 94 | #define RANGE_EXCEPTION(msg) \ 95 | Exception::throw_it(__FILE__, __LINE__, msg) 96 | 97 | //////////////////////////////////////////////////////////////////////////////// 98 | //! Implementation 99 | 100 | // includes, system 101 | #include 102 | 103 | //////////////////////////////////////////////////////////////////////////////// 104 | //! Static construction interface. 105 | //! @param Exception causing code fragment (file and line) and detailed infos. 106 | //////////////////////////////////////////////////////////////////////////////// 107 | /*static*/ template 108 | void Exception::throw_it(const char *file, const int line, 109 | const char *detailed) { 110 | std::stringstream s; 111 | 112 | // Quiet heavy-weight but exceptions are not for 113 | // performance / release versions 114 | s << "Exception in file '" << file << "' in line " << line << "\n" 115 | << "Detailed description: " << detailed << "\n"; 116 | 117 | throw Exception(s.str()); 118 | } 119 | 120 | //////////////////////////////////////////////////////////////////////////////// 121 | //! Static construction interface. 122 | //! @param Exception causing code fragment (file and line) and detailed infos. 123 | //////////////////////////////////////////////////////////////////////////////// 124 | /*static*/ template 125 | void Exception::throw_it(const char *file, const int line, 126 | const std::string &msg) { 127 | throw_it(file, line, msg.c_str()); 128 | } 129 | 130 | //////////////////////////////////////////////////////////////////////////////// 131 | //! Constructor, default (private). 132 | //////////////////////////////////////////////////////////////////////////////// 133 | template 134 | Exception::Exception() : Std_Exception("Unknown Exception.\n") {} 135 | 136 | //////////////////////////////////////////////////////////////////////////////// 137 | //! Constructor, standard (private). 138 | //! String returned by what(). 139 | //////////////////////////////////////////////////////////////////////////////// 140 | template 141 | Exception::Exception(const std::string &s) : Std_Exception(s) {} 142 | 143 | //////////////////////////////////////////////////////////////////////////////// 144 | //! Destructor 145 | //////////////////////////////////////////////////////////////////////////////// 146 | template 147 | Exception::~Exception() throw() {} 148 | 149 | // functions, exported 150 | 151 | #endif // COMMON_EXCEPTION_H_ 152 | -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/helper_cusolver.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. 2 | * 3 | * Redistribution and use in source and binary forms, with or without 4 | * modification, are permitted provided that the following conditions 5 | * are met: 6 | * * Redistributions of source code must retain the above copyright 7 | * notice, this list of conditions and the following disclaimer. 8 | * * Redistributions in binary form must reproduce the above copyright 9 | * notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * * Neither the name of NVIDIA CORPORATION nor the names of its 12 | * contributors may be used to endorse or promote products derived 13 | * from this software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY 16 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 18 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 19 | * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 20 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 21 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 22 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 23 | * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #ifndef HELPER_CUSOLVER 29 | #define HELPER_CUSOLVER 30 | 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | 38 | #include "cusparse.h" 39 | 40 | #define SWITCH_CHAR '-' 41 | 42 | struct testOpts { 43 | char *sparse_mat_filename; // by switch -F 44 | const char *testFunc; // by switch -R 45 | const char *reorder; // by switch -P 46 | int lda; // by switch -lda 47 | }; 48 | 49 | double vec_norminf(int n, const double *x) { 50 | double norminf = 0; 51 | for (int j = 0; j < n; j++) { 52 | double x_abs = fabs(x[j]); 53 | norminf = (norminf > x_abs) ? norminf : x_abs; 54 | } 55 | return norminf; 56 | } 57 | 58 | /* 59 | * |A| = max { |A|*ones(m,1) } 60 | */ 61 | double mat_norminf(int m, int n, const double *A, int lda) { 62 | double norminf = 0; 63 | for (int i = 0; i < m; i++) { 64 | double sum = 0.0; 65 | for (int j = 0; j < n; j++) { 66 | double A_abs = fabs(A[i + j * lda]); 67 | sum += A_abs; 68 | } 69 | norminf = (norminf > sum) ? norminf : sum; 70 | } 71 | return norminf; 72 | } 73 | 74 | /* 75 | * |A| = max { |A|*ones(m,1) } 76 | */ 77 | double csr_mat_norminf(int m, int n, int nnzA, const cusparseMatDescr_t descrA, 78 | const double *csrValA, const int *csrRowPtrA, 79 | const int *csrColIndA) { 80 | const int baseA = 81 | (CUSPARSE_INDEX_BASE_ONE == cusparseGetMatIndexBase(descrA)) ? 1 : 0; 82 | 83 | double norminf = 0; 84 | for (int i = 0; i < m; i++) { 85 | double sum = 0.0; 86 | const int start = csrRowPtrA[i] - baseA; 87 | const int end = csrRowPtrA[i + 1] - baseA; 88 | for (int colidx = start; colidx < end; colidx++) { 89 | // const int j = csrColIndA[colidx] - baseA; 90 | double A_abs = fabs(csrValA[colidx]); 91 | sum += A_abs; 92 | } 93 | norminf = (norminf > sum) ? norminf : sum; 94 | } 95 | return norminf; 96 | } 97 | 98 | void display_matrix(int m, int n, int nnzA, const cusparseMatDescr_t descrA, 99 | const double *csrValA, const int *csrRowPtrA, 100 | const int *csrColIndA) { 101 | const int baseA = 102 | (CUSPARSE_INDEX_BASE_ONE == cusparseGetMatIndexBase(descrA)) ? 1 : 0; 103 | 104 | printf("m = %d, n = %d, nnz = %d, matlab base-1\n", m, n, nnzA); 105 | 106 | for (int row = 0; row < m; row++) { 107 | const int start = csrRowPtrA[row] - baseA; 108 | const int end = csrRowPtrA[row + 1] - baseA; 109 | for (int colidx = start; colidx < end; colidx++) { 110 | const int col = csrColIndA[colidx] - baseA; 111 | double Areg = csrValA[colidx]; 112 | printf("A(%d, %d) = %20.16E\n", row + 1, col + 1, Areg); 113 | } 114 | } 115 | } 116 | 117 | #if defined(_WIN32) 118 | #if !defined(WIN32_LEAN_AND_MEAN) 119 | #define WIN32_LEAN_AND_MEAN 120 | #endif 121 | #include 122 | double second(void) { 123 | LARGE_INTEGER t; 124 | static double oofreq; 125 | static int checkedForHighResTimer; 126 | static BOOL hasHighResTimer; 127 | 128 | if (!checkedForHighResTimer) { 129 | hasHighResTimer = QueryPerformanceFrequency(&t); 130 | oofreq = 1.0 / (double)t.QuadPart; 131 | checkedForHighResTimer = 1; 132 | } 133 | if (hasHighResTimer) { 134 | QueryPerformanceCounter(&t); 135 | return (double)t.QuadPart * oofreq; 136 | } else { 137 | return (double)GetTickCount() / 1000.0; 138 | } 139 | } 140 | 141 | #elif defined(__linux__) || defined(__QNX__) 142 | #include 143 | #include 144 | #include 145 | double second(void) { 146 | struct timeval tv; 147 | gettimeofday(&tv, NULL); 148 | return (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0; 149 | } 150 | 151 | #elif defined(__APPLE__) 152 | #include 153 | #include 154 | #include 155 | #include 156 | #include 157 | double second(void) { 158 | struct timeval tv; 159 | gettimeofday(&tv, NULL); 160 | return (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0; 161 | } 162 | #else 163 | #error unsupported platform 164 | #endif 165 | 166 | #endif 167 | -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/helper_functions.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. 2 | * 3 | * Redistribution and use in source and binary forms, with or without 4 | * modification, are permitted provided that the following conditions 5 | * are met: 6 | * * Redistributions of source code must retain the above copyright 7 | * notice, this list of conditions and the following disclaimer. 8 | * * Redistributions in binary form must reproduce the above copyright 9 | * notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * * Neither the name of NVIDIA CORPORATION nor the names of its 12 | * contributors may be used to endorse or promote products derived 13 | * from this software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY 16 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 18 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 19 | * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 20 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 21 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 22 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 23 | * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | // These are helper functions for the SDK samples (string parsing, 29 | // timers, image helpers, etc) 30 | #ifndef COMMON_HELPER_FUNCTIONS_H_ 31 | #define COMMON_HELPER_FUNCTIONS_H_ 32 | 33 | #ifdef WIN32 34 | #pragma warning(disable : 4996) 35 | #endif 36 | 37 | // includes, project 38 | #include 39 | #include 40 | #include 41 | #include 42 | #include 43 | 44 | #include 45 | #include 46 | #include 47 | #include 48 | #include 49 | 50 | // includes, timer, string parsing, image helpers 51 | #include // helper functions for image compare, dump, data comparisons 52 | #include // helper functions for string parsing 53 | #include // helper functions for timers 54 | 55 | #ifndef EXIT_WAIVED 56 | #define EXIT_WAIVED 2 57 | #endif 58 | 59 | #endif // COMMON_HELPER_FUNCTIONS_H_ 60 | -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/helper_multiprocess.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. 2 | * 3 | * Redistribution and use in source and binary forms, with or without 4 | * modification, are permitted provided that the following conditions 5 | * are met: 6 | * * Redistributions of source code must retain the above copyright 7 | * notice, this list of conditions and the following disclaimer. 8 | * * Redistributions in binary form must reproduce the above copyright 9 | * notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * * Neither the name of NVIDIA CORPORATION nor the names of its 12 | * contributors may be used to endorse or promote products derived 13 | * from this software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY 16 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 18 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 19 | * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 20 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 21 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 22 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 23 | * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #ifndef HELPER_MULTIPROCESS_H 29 | #define HELPER_MULTIPROCESS_H 30 | 31 | #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) 32 | #ifndef WIN32_LEAN_AND_MEAN 33 | #define WIN32_LEAN_AND_MEAN 34 | #endif 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | #include 42 | #include 43 | #else 44 | #include 45 | #include 46 | #include 47 | #include 48 | #include 49 | #include 50 | #include 51 | #include 52 | #include 53 | #include 54 | #endif 55 | #include 56 | 57 | typedef struct sharedMemoryInfo_st { 58 | void *addr; 59 | size_t size; 60 | #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) 61 | HANDLE shmHandle; 62 | #else 63 | int shmFd; 64 | #endif 65 | } sharedMemoryInfo; 66 | 67 | int sharedMemoryCreate(const char *name, size_t sz, sharedMemoryInfo *info); 68 | 69 | int sharedMemoryOpen(const char *name, size_t sz, sharedMemoryInfo *info); 70 | 71 | void sharedMemoryClose(sharedMemoryInfo *info); 72 | 73 | 74 | #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) 75 | typedef PROCESS_INFORMATION Process; 76 | #else 77 | typedef pid_t Process; 78 | #endif 79 | 80 | int spawnProcess(Process *process, const char *app, char * const *args); 81 | 82 | int waitProcess(Process *process); 83 | 84 | #define checkIpcErrors(ipcFuncResult) \ 85 | if (ipcFuncResult == -1) { fprintf(stderr, "Failure at %u %s\n", __LINE__, __FILE__); exit(EXIT_FAILURE); } 86 | 87 | #if defined(__linux__) 88 | struct ipcHandle_st { 89 | int socket; 90 | char *socketName; 91 | }; 92 | typedef int ShareableHandle; 93 | #elif defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) 94 | struct ipcHandle_st { 95 | std::vector hMailslot; // 1 Handle in case of child and `num children` Handles for parent. 96 | }; 97 | typedef HANDLE ShareableHandle; 98 | #endif 99 | 100 | typedef struct ipcHandle_st ipcHandle; 101 | 102 | int 103 | ipcCreateSocket(ipcHandle *&handle, const char *name, const std::vector& processes); 104 | 105 | int 106 | ipcOpenSocket(ipcHandle *&handle); 107 | 108 | int 109 | ipcCloseSocket(ipcHandle *handle); 110 | 111 | int 112 | ipcRecvShareableHandles(ipcHandle *handle, std::vector& shareableHandles); 113 | 114 | int 115 | ipcSendShareableHandles(ipcHandle *handle, const std::vector& shareableHandles, const std::vector& processes); 116 | 117 | int 118 | ipcCloseShareableHandle(ShareableHandle shHandle); 119 | 120 | #endif // HELPER_MULTIPROCESS_H 121 | -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/multithreading.cpp: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. 2 | * 3 | * Redistribution and use in source and binary forms, with or without 4 | * modification, are permitted provided that the following conditions 5 | * are met: 6 | * * Redistributions of source code must retain the above copyright 7 | * notice, this list of conditions and the following disclaimer. 8 | * * Redistributions in binary form must reproduce the above copyright 9 | * notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * * Neither the name of NVIDIA CORPORATION nor the names of its 12 | * contributors may be used to endorse or promote products derived 13 | * from this software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY 16 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 18 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 19 | * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 20 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 21 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 22 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 23 | * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #include 29 | 30 | #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) 31 | // Create thread 32 | CUTThread cutStartThread(CUT_THREADROUTINE func, void *data) { 33 | return CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)func, data, 0, NULL); 34 | } 35 | 36 | // Wait for thread to finish 37 | void cutEndThread(CUTThread thread) { 38 | WaitForSingleObject(thread, INFINITE); 39 | CloseHandle(thread); 40 | } 41 | 42 | // Destroy thread 43 | void cutDestroyThread(CUTThread thread) { 44 | TerminateThread(thread, 0); 45 | CloseHandle(thread); 46 | } 47 | 48 | // Wait for multiple threads 49 | void cutWaitForThreads(const CUTThread *threads, int num) { 50 | WaitForMultipleObjects(num, threads, true, INFINITE); 51 | 52 | for (int i = 0; i < num; i++) { 53 | CloseHandle(threads[i]); 54 | } 55 | } 56 | 57 | #else 58 | // Create thread 59 | CUTThread cutStartThread(CUT_THREADROUTINE func, void *data) { 60 | pthread_t thread; 61 | pthread_create(&thread, NULL, func, data); 62 | return thread; 63 | } 64 | 65 | // Wait for thread to finish 66 | void cutEndThread(CUTThread thread) { pthread_join(thread, NULL); } 67 | 68 | // Destroy thread 69 | void cutDestroyThread(CUTThread thread) { pthread_cancel(thread); } 70 | 71 | // Wait for multiple threads 72 | void cutWaitForThreads(const CUTThread *threads, int num) { 73 | for (int i = 0; i < num; i++) { 74 | cutEndThread(threads[i]); 75 | } 76 | } 77 | 78 | #endif 79 | -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/multithreading.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. 2 | * 3 | * Redistribution and use in source and binary forms, with or without 4 | * modification, are permitted provided that the following conditions 5 | * are met: 6 | * * Redistributions of source code must retain the above copyright 7 | * notice, this list of conditions and the following disclaimer. 8 | * * Redistributions in binary form must reproduce the above copyright 9 | * notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * * Neither the name of NVIDIA CORPORATION nor the names of its 12 | * contributors may be used to endorse or promote products derived 13 | * from this software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY 16 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 18 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 19 | * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 20 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 21 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 22 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 23 | * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #ifndef MULTITHREADING_H 29 | #define MULTITHREADING_H 30 | 31 | 32 | //Simple portable thread library. 33 | 34 | //Windows threads. 35 | #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) 36 | #include 37 | 38 | typedef HANDLE CUTThread; 39 | typedef unsigned(WINAPI *CUT_THREADROUTINE)(void *); 40 | 41 | #define CUT_THREADPROC unsigned WINAPI 42 | #define CUT_THREADEND return 0 43 | 44 | #else 45 | //POSIX threads. 46 | #include 47 | 48 | typedef pthread_t CUTThread; 49 | typedef void *(*CUT_THREADROUTINE)(void *); 50 | 51 | #define CUT_THREADPROC void 52 | #define CUT_THREADEND 53 | #endif 54 | 55 | 56 | #ifdef __cplusplus 57 | extern "C" { 58 | #endif 59 | 60 | //Create thread. 61 | CUTThread cutStartThread(CUT_THREADROUTINE, void *data); 62 | 63 | //Wait for thread to finish. 64 | void cutEndThread(CUTThread thread); 65 | 66 | //Destroy thread. 67 | void cutDestroyThread(CUTThread thread); 68 | 69 | //Wait for multiple threads. 70 | void cutWaitForThreads(const CUTThread *threads, int num); 71 | 72 | #ifdef __cplusplus 73 | } //extern "C" 74 | #endif 75 | 76 | #endif //MULTITHREADING_H 77 | -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/nvMath.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. 2 | * 3 | * Redistribution and use in source and binary forms, with or without 4 | * modification, are permitted provided that the following conditions 5 | * are met: 6 | * * Redistributions of source code must retain the above copyright 7 | * notice, this list of conditions and the following disclaimer. 8 | * * Redistributions in binary form must reproduce the above copyright 9 | * notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * * Neither the name of NVIDIA CORPORATION nor the names of its 12 | * contributors may be used to endorse or promote products derived 13 | * from this software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY 16 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 18 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 19 | * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 20 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 21 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 22 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 23 | * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | // 29 | // Template math library for common 3D functionality 30 | // 31 | // This code is in part deriver from glh, a cross platform glut helper library. 32 | // The copyright for glh follows this notice. 33 | // 34 | // Copyright (c) NVIDIA Corporation. All rights reserved. 35 | //////////////////////////////////////////////////////////////////////////////// 36 | 37 | /* 38 | Copyright (c) 2000 Cass Everitt 39 | Copyright (c) 2000 NVIDIA Corporation 40 | All rights reserved. 41 | 42 | Redistribution and use in source and binary forms, with or 43 | without modification, are permitted provided that the following 44 | conditions are met: 45 | 46 | * Redistributions of source code must retain the above 47 | copyright notice, this list of conditions and the following 48 | disclaimer. 49 | 50 | * Redistributions in binary form must reproduce the above 51 | copyright notice, this list of conditions and the following 52 | disclaimer in the documentation and/or other materials 53 | provided with the distribution. 54 | 55 | * The names of contributors to this software may not be used 56 | to endorse or promote products derived from this software 57 | without specific prior written permission. 58 | 59 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 60 | ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 61 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 62 | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 63 | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 64 | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 65 | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 66 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 67 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 68 | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 69 | ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 70 | POSSIBILITY OF SUCH DAMAGE. 71 | 72 | 73 | Cass Everitt - cass@r3.nu 74 | */ 75 | 76 | #ifndef NV_MATH_H 77 | #define NV_MATH_H 78 | 79 | #include 80 | 81 | #include 82 | #include 83 | #include 84 | 85 | #define NV_PI float(3.1415926535897932384626433832795) 86 | 87 | namespace nv 88 | { 89 | 90 | typedef vec2 vec2f; 91 | typedef vec3 vec3f; 92 | typedef vec3 vec3i; 93 | typedef vec3 vec3ui; 94 | typedef vec4 vec4f; 95 | typedef matrix4 matrix4f; 96 | typedef quaternion quaternionf; 97 | 98 | 99 | inline void applyRotation(const quaternionf &r) 100 | { 101 | float angle; 102 | vec3f axis; 103 | r.get_value(axis, angle); 104 | glRotatef(angle/3.1415926f * 180.0f, axis[0], axis[1], axis[2]); 105 | } 106 | 107 | 108 | 109 | }; 110 | 111 | #endif 112 | -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/rendercheck_d3d10.cpp: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. 2 | * 3 | * Redistribution and use in source and binary forms, with or without 4 | * modification, are permitted provided that the following conditions 5 | * are met: 6 | * * Redistributions of source code must retain the above copyright 7 | * notice, this list of conditions and the following disclaimer. 8 | * * Redistributions in binary form must reproduce the above copyright 9 | * notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * * Neither the name of NVIDIA CORPORATION nor the names of its 12 | * contributors may be used to endorse or promote products derived 13 | * from this software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY 16 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 18 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 19 | * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 20 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 21 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 22 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 23 | * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | //////////////////////////////////////////////////////////////////////////////// 29 | // 30 | // Utility funcs to wrap up saving a surface or the back buffer as a PPM file 31 | // In addition, wraps up a threshold comparision of two PPMs. 32 | // 33 | // These functions are designed to be used to implement an automated QA testing 34 | // for SDK samples. 35 | // 36 | // Author: Bryan Dudash 37 | // Email: sdkfeedback@nvidia.com 38 | // 39 | // Copyright (c) NVIDIA Corporation. All rights reserved. 40 | //////////////////////////////////////////////////////////////////////////////// 41 | 42 | #include 43 | #include 44 | 45 | HRESULT CheckRenderD3D10::ActiveRenderTargetToPPM(ID3D10Device *pDevice, 46 | const char *zFileName) { 47 | ID3D10RenderTargetView *pRTV = NULL; 48 | pDevice->OMGetRenderTargets(1, &pRTV, NULL); 49 | 50 | ID3D10Resource *pSourceResource = NULL; 51 | pRTV->GetResource(&pSourceResource); 52 | 53 | return ResourceToPPM(pDevice, pSourceResource, zFileName); 54 | } 55 | 56 | HRESULT CheckRenderD3D10::ResourceToPPM(ID3D10Device *pDevice, 57 | ID3D10Resource *pResource, 58 | const char *zFileName) { 59 | D3D10_RESOURCE_DIMENSION rType; 60 | pResource->GetType(&rType); 61 | 62 | if (rType != D3D10_RESOURCE_DIMENSION_TEXTURE2D) { 63 | printf("SurfaceToPPM: pResource is not a 2D texture! Aborting...\n"); 64 | return E_FAIL; 65 | } 66 | 67 | ID3D10Texture2D *pSourceTexture = (ID3D10Texture2D *)pResource; 68 | ID3D10Texture2D *pTargetTexture = NULL; 69 | 70 | D3D10_TEXTURE2D_DESC desc; 71 | pSourceTexture->GetDesc(&desc); 72 | desc.BindFlags = 0; 73 | desc.CPUAccessFlags = D3D10_CPU_ACCESS_READ; 74 | desc.Usage = D3D10_USAGE_STAGING; 75 | 76 | if (FAILED(pDevice->CreateTexture2D(&desc, NULL, &pTargetTexture))) { 77 | printf( 78 | "SurfaceToPPM: Unable to create target Texture resoruce! Aborting... " 79 | "\n"); 80 | return E_FAIL; 81 | } 82 | 83 | pDevice->CopyResource(pTargetTexture, pSourceTexture); 84 | 85 | D3D10_MAPPED_TEXTURE2D mappedTex2D; 86 | pTargetTexture->Map(0, D3D10_MAP_READ, 0, &mappedTex2D); 87 | 88 | // Need to convert from dx pitch to pitch=width 89 | unsigned char *pPPMData = new unsigned char[desc.Width * desc.Height * 4]; 90 | 91 | for (unsigned int iHeight = 0; iHeight < desc.Height; iHeight++) { 92 | memcpy( 93 | &(pPPMData[iHeight * desc.Width * 4]), 94 | (unsigned char *)(mappedTex2D.pData) + iHeight * mappedTex2D.RowPitch, 95 | desc.Width * 4); 96 | } 97 | 98 | pTargetTexture->Unmap(0); 99 | 100 | // Prepends the PPM header info and bumps byte data afterwards 101 | sdkSavePPM4ub(zFileName, pPPMData, desc.Width, desc.Height); 102 | 103 | delete[] pPPMData; 104 | pTargetTexture->Release(); 105 | 106 | return S_OK; 107 | } 108 | 109 | bool CheckRenderD3D10::PPMvsPPM(const char *src_file, const char *ref_file, 110 | const char *exec_path, const float epsilon, 111 | const float threshold) { 112 | char *ref_file_path = sdkFindFilePath(ref_file, exec_path); 113 | 114 | if (ref_file_path == NULL) { 115 | printf( 116 | "CheckRenderD3D10::PPMvsPPM unable to find <%s> in <%s> Aborting " 117 | "comparison!\n", 118 | ref_file, exec_path); 119 | printf(">>> Check info.xml and [project//data] folder <%s> <<<\n", 120 | ref_file); 121 | printf("Aborting comparison!\n"); 122 | printf(" FAILURE!\n"); 123 | return false; 124 | } 125 | 126 | return (sdkComparePPM(src_file, ref_file_path, epsilon, threshold, true) == 127 | true); 128 | } -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/rendercheck_d3d10.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. 2 | * 3 | * Redistribution and use in source and binary forms, with or without 4 | * modification, are permitted provided that the following conditions 5 | * are met: 6 | * * Redistributions of source code must retain the above copyright 7 | * notice, this list of conditions and the following disclaimer. 8 | * * Redistributions in binary form must reproduce the above copyright 9 | * notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * * Neither the name of NVIDIA CORPORATION nor the names of its 12 | * contributors may be used to endorse or promote products derived 13 | * from this software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY 16 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 18 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 19 | * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 20 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 21 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 22 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 23 | * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #pragma once 29 | 30 | #ifndef _RENDERCHECK_D3D10_H_ 31 | #define _RENDERCHECK_D3D10_H_ 32 | 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | 39 | class CheckRenderD3D10 { 40 | public: 41 | CheckRenderD3D10() {} 42 | 43 | static HRESULT ActiveRenderTargetToPPM(ID3D10Device *pDevice, 44 | const char *zFileName); 45 | static HRESULT ResourceToPPM(ID3D10Device *pDevice, ID3D10Resource *pResource, 46 | const char *zFileName); 47 | 48 | static bool PPMvsPPM(const char *src_file, const char *ref_file, 49 | const char *exec_path, const float epsilon, 50 | const float threshold = 0.0f); 51 | }; 52 | 53 | #endif -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/rendercheck_d3d11.cpp: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. 2 | * 3 | * Redistribution and use in source and binary forms, with or without 4 | * modification, are permitted provided that the following conditions 5 | * are met: 6 | * * Redistributions of source code must retain the above copyright 7 | * notice, this list of conditions and the following disclaimer. 8 | * * Redistributions in binary form must reproduce the above copyright 9 | * notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * * Neither the name of NVIDIA CORPORATION nor the names of its 12 | * contributors may be used to endorse or promote products derived 13 | * from this software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY 16 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 18 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 19 | * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 20 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 21 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 22 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 23 | * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | //////////////////////////////////////////////////////////////////////////////// 29 | // 30 | // Utility funcs to wrap up saving a surface or the back buffer as a PPM file 31 | // In addition, wraps up a threshold comparision of two PPMs. 32 | // 33 | // These functions are designed to be used to implement an automated QA testing for SDK samples. 34 | // 35 | // Author: Bryan Dudash 36 | // Email: sdkfeedback@nvidia.com 37 | // 38 | // Copyright (c) NVIDIA Corporation. All rights reserved. 39 | //////////////////////////////////////////////////////////////////////////////// 40 | 41 | #include 42 | #include 43 | 44 | HRESULT CheckRenderD3D11::ActiveRenderTargetToPPM(ID3D11Device *pDevice, const char *zFileName) 45 | { 46 | ID3D11DeviceContext *pDeviceCtxt; 47 | pDevice->GetImmediateContext(&pDeviceCtxt); 48 | ID3D11RenderTargetView *pRTV = NULL; 49 | pDeviceCtxt->OMGetRenderTargets(1,&pRTV,NULL); 50 | 51 | ID3D11Resource *pSourceResource = NULL; 52 | pRTV->GetResource(&pSourceResource); 53 | 54 | return ResourceToPPM(pDevice,pSourceResource,zFileName); 55 | } 56 | 57 | HRESULT CheckRenderD3D11::ResourceToPPM(ID3D11Device *pDevice, ID3D11Resource *pResource, const char *zFileName) 58 | { 59 | ID3D11DeviceContext *pDeviceCtxt; 60 | pDevice->GetImmediateContext(&pDeviceCtxt); 61 | D3D11_RESOURCE_DIMENSION rType; 62 | pResource->GetType(&rType); 63 | 64 | if (rType != D3D11_RESOURCE_DIMENSION_TEXTURE2D) 65 | { 66 | printf("SurfaceToPPM: pResource is not a 2D texture! Aborting...\n"); 67 | return E_FAIL; 68 | } 69 | 70 | ID3D11Texture2D *pSourceTexture = (ID3D11Texture2D *)pResource; 71 | ID3D11Texture2D *pTargetTexture = NULL; 72 | 73 | D3D11_TEXTURE2D_DESC desc; 74 | pSourceTexture->GetDesc(&desc); 75 | desc.BindFlags = 0; 76 | desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; 77 | desc.Usage = D3D11_USAGE_STAGING; 78 | 79 | if (FAILED(pDevice->CreateTexture2D(&desc,NULL,&pTargetTexture))) 80 | { 81 | printf("SurfaceToPPM: Unable to create target Texture resoruce! Aborting... \n"); 82 | return E_FAIL; 83 | } 84 | 85 | pDeviceCtxt->CopyResource(pTargetTexture,pSourceTexture); 86 | 87 | D3D11_MAPPED_SUBRESOURCE mappedTex2D; 88 | pDeviceCtxt->Map(pTargetTexture, 0, D3D11_MAP_READ,0,&mappedTex2D); 89 | 90 | // Need to convert from dx pitch to pitch=width 91 | unsigned char *pPPMData = new unsigned char[desc.Width*desc.Height*4]; 92 | 93 | for (unsigned int iHeight = 0; iHeightUnmap(pTargetTexture, 0); 99 | 100 | // Prepends the PPM header info and bumps byte data afterwards 101 | sdkSavePPM4ub(zFileName, pPPMData, desc.Width, desc.Height); 102 | 103 | delete [] pPPMData; 104 | pTargetTexture->Release(); 105 | 106 | return S_OK; 107 | } 108 | 109 | bool CheckRenderD3D11::PPMvsPPM(const char *src_file, const char *ref_file, const char *exec_path, 110 | const float epsilon, const float threshold) 111 | { 112 | char *ref_file_path = sdkFindFilePath(ref_file, exec_path); 113 | 114 | if (ref_file_path == NULL) 115 | { 116 | printf("CheckRenderD3D11::PPMvsPPM unable to find <%s> in <%s> Aborting comparison!\n", ref_file, exec_path); 117 | printf(">>> Check info.xml and [project//data] folder <%s> <<<\n", ref_file); 118 | printf("Aborting comparison!\n"); 119 | printf(" FAILURE!\n"); 120 | return false; 121 | } 122 | 123 | return sdkComparePPM(src_file,ref_file_path,epsilon,threshold,true) == true; 124 | } -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/rendercheck_d3d11.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. 2 | * 3 | * Redistribution and use in source and binary forms, with or without 4 | * modification, are permitted provided that the following conditions 5 | * are met: 6 | * * Redistributions of source code must retain the above copyright 7 | * notice, this list of conditions and the following disclaimer. 8 | * * Redistributions in binary form must reproduce the above copyright 9 | * notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * * Neither the name of NVIDIA CORPORATION nor the names of its 12 | * contributors may be used to endorse or promote products derived 13 | * from this software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY 16 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 18 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 19 | * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 20 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 21 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 22 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 23 | * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #pragma once 29 | 30 | #ifndef _RENDERCHECK_D3D11_H_ 31 | #define _RENDERCHECK_D3D11_H_ 32 | 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | 39 | class CheckRenderD3D11 40 | { 41 | public: 42 | 43 | CheckRenderD3D11() {} 44 | 45 | static HRESULT ActiveRenderTargetToPPM(ID3D11Device *pDevice, const char *zFileName); 46 | static HRESULT ResourceToPPM(ID3D11Device *pDevice, ID3D11Resource *pResource, const char *zFileName); 47 | 48 | static bool PPMvsPPM(const char *src_file, const char *ref_file, const char *exec_path, 49 | const float epsilon, const float threshold = 0.0f); 50 | }; 51 | 52 | #endif -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/Common/rendercheck_d3d9.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. 2 | * 3 | * Redistribution and use in source and binary forms, with or without 4 | * modification, are permitted provided that the following conditions 5 | * are met: 6 | * * Redistributions of source code must retain the above copyright 7 | * notice, this list of conditions and the following disclaimer. 8 | * * Redistributions in binary form must reproduce the above copyright 9 | * notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * * Neither the name of NVIDIA CORPORATION nor the names of its 12 | * contributors may be used to endorse or promote products derived 13 | * from this software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY 16 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 18 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 19 | * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 20 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 21 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 22 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 23 | * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | */ 27 | 28 | #pragma once 29 | 30 | #ifndef _RENDERCHECK_D3D9_H_ 31 | #define _RENDERCHECK_D3D9_H_ 32 | 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | 39 | class CheckRenderD3D9 { 40 | public: 41 | CheckRenderD3D9() {} 42 | 43 | static HRESULT BackbufferToPPM(IDirect3DDevice9 *pDevice, 44 | const char *zFileName); 45 | static HRESULT SurfaceToPPM(IDirect3DDevice9 *pDevice, 46 | IDirect3DSurface9 *pSurface, 47 | const char *zFileName); 48 | 49 | static bool PPMvsPPM(const char *src_file, const char *ref_file, 50 | const char *exec_path, const float epsilon, 51 | const float threshold = 0.0f); 52 | }; 53 | 54 | #endif -------------------------------------------------------------------------------- /bvh-distance-queries/cuda-samples/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions 5 | are met: 6 | * Redistributions of source code must retain the above copyright 7 | notice, this list of conditions and the following disclaimer. 8 | * Redistributions in binary form must reproduce the above copyright 9 | notice, this list of conditions and the following disclaimer in the 10 | documentation and/or other materials provided with the distribution. 11 | * Neither the name of NVIDIA CORPORATION nor the names of its 12 | contributors may be used to endorse or promote products derived 13 | from this software without specific prior written permission. 14 | 15 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY 16 | EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 18 | PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 19 | CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 20 | EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 21 | PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 22 | PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 23 | OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | 27 | For additional information on the license terms, see the CUDA EULA at 28 | https://docs.nvidia.com/cuda/eula/index.html 29 | -------------------------------------------------------------------------------- /bvh-distance-queries/data/test_box.ply: -------------------------------------------------------------------------------- 1 | ply 2 | format ascii 1.0 3 | element vertex 8 4 | property float x 5 | property float y 6 | property float z 7 | element face 12 8 | property list uchar int vertex_indices 9 | end_header 10 | 0.5 0.5 0.5 11 | -0.5 0.5 0.5 12 | 0.5 -0.5 0.5 13 | -0.5 -0.5 0.5 14 | 0.5 0.5 -0.5 15 | -0.5 0.5 -0.5 16 | 0.5 -0.5 -0.5 17 | -0.5 -0.5 -0.5 18 | 3 0 1 2 19 | 3 3 2 1 20 | 3 0 2 4 21 | 3 6 4 2 22 | 3 0 4 1 23 | 3 5 1 4 24 | 3 7 5 6 25 | 3 4 6 5 26 | 3 7 6 3 27 | 3 2 3 6 28 | 3 7 3 5 29 | 3 1 5 3 30 | -------------------------------------------------------------------------------- /bvh-distance-queries/examples/benchmark_time.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is 4 | # holder of all proprietary rights on this computer program. 5 | # You can only use this computer program if you have closed 6 | # a license agreement with MPG or you get the right to use the computer 7 | # program from someone who is authorized to grant you that right. 8 | # Any use of the computer program without a valid license is prohibited and 9 | # liable to prosecution. 10 | # 11 | # Copyright©2019 Max-Planck-Gesellschaft zur Förderung 12 | # der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute 13 | # for Intelligent Systems and the Max Planck Institute for Biological 14 | # Cybernetics. All rights reserved. 15 | # 16 | # Contact: ps-license@tuebingen.mpg.de 17 | 18 | from __future__ import absolute_import 19 | from __future__ import print_function 20 | from __future__ import division 21 | 22 | import sys 23 | import os 24 | import os.path as osp 25 | 26 | import time 27 | 28 | import argparse 29 | 30 | try: 31 | input = raw_input 32 | except NameError: 33 | pass 34 | 35 | import open3d as o3d 36 | import pyigl as igl 37 | from iglhelpers import p2e, e2p 38 | 39 | import yaml 40 | 41 | import torch 42 | import torch.nn as nn 43 | import torch.autograd as autograd 44 | 45 | from copy import deepcopy 46 | 47 | import numpy as np 48 | import tqdm 49 | 50 | from loguru import logger 51 | 52 | from psbody.mesh import Mesh 53 | import bvh_distance_queries 54 | 55 | 56 | if __name__ == "__main__": 57 | 58 | device = torch.device('cuda') 59 | 60 | parser = argparse.ArgumentParser() 61 | parser.add_argument('--mesh-fn', type=str, dest='mesh_fn', 62 | help='A mesh file (.obj, .ply, e.t.c.) to be checked' + 63 | ' for collisions') 64 | parser.add_argument('--timings-fn', type=str, dest='timings_fn', 65 | default='timings.yaml', 66 | help='File where the timings will be saved') 67 | parser.add_argument('--num-query-points', type=int, default=1, 68 | nargs='+', 69 | dest='num_query_points_lst', 70 | help='Number of random query points') 71 | parser.add_argument('--timing-iters', type=int, default=1000, 72 | dest='timing_iters') 73 | parser.add_argument('--run-igl', dest='run_igl', 74 | type=lambda arg: arg.lower() in ['true'], 75 | default=False) 76 | 77 | args, _ = parser.parse_known_args() 78 | 79 | mesh_fn = args.mesh_fn 80 | num_query_points_lst = args.num_query_points_lst 81 | timing_iters = args.timing_iters 82 | timings_fn = args.timings_fn 83 | run_igl = args.run_igl 84 | 85 | input_mesh = Mesh(filename=mesh_fn) 86 | 87 | torch.manual_seed(0) 88 | 89 | logger.info(f'Number of triangles = {input_mesh.f.shape[0]}') 90 | 91 | v = input_mesh.v 92 | v -= v.mean(keepdims=True, axis=0) 93 | 94 | vertices = torch.tensor(v, dtype=torch.float32, device=device) 95 | faces = torch.tensor(input_mesh.f.astype(np.int64), 96 | dtype=torch.long, 97 | device=device) 98 | 99 | if osp.exists(timings_fn): 100 | with open(timings_fn, 'r') as f: 101 | output_dict = yaml.load(f) 102 | else: 103 | output_dict = {} 104 | 105 | for num_query_points in num_query_points_lst: 106 | query_points = torch.rand([1, num_query_points, 3], dtype=torch.float32, 107 | device=device) * 2 - 1 108 | query_points_np = query_points.detach().cpu().numpy().squeeze( 109 | axis=0).astype(np.float32).reshape(num_query_points, 3) 110 | 111 | batch_size = 1 112 | triangles = vertices[faces].unsqueeze(dim=0) 113 | 114 | m = bvh_distance_queries.BVH() 115 | 116 | elapsed = 0 117 | for n in tqdm.tqdm(range(timing_iters)): 118 | torch.cuda.synchronize() 119 | torch.cuda.synchronize() 120 | start = time.perf_counter() 121 | distances, closest_points, closest_faces = m( 122 | triangles, query_points) 123 | torch.cuda.synchronize() 124 | elapsed += (time.perf_counter() - start) 125 | 126 | cuda_elapsed = elapsed / timing_iters 127 | logger.info( 128 | f'CUDA Points = {num_query_points}: elapsed time {cuda_elapsed}') 129 | distances = distances.detach().cpu().numpy() 130 | closest_points = closest_points.detach().cpu().numpy().squeeze() 131 | output_dict[num_query_points]['cuda'] = cuda_elapsed 132 | 133 | if run_igl: 134 | elapsed = 0 135 | for n in tqdm.tqdm(range(timing_iters)): 136 | sqrD = igl.eigen.MatrixXd() 137 | closest_faces = igl.eigen.MatrixXi() 138 | closest_points_eig = igl.eigen.MatrixXd() 139 | query_points_eigen = p2e(query_points_np) 140 | v_eig = p2e(v) 141 | f_eig = p2e(input_mesh.f.astype(np.int64)) 142 | 143 | start = time.perf_counter() 144 | # Find the closest points on the SMPL-X mesh 145 | igl.point_mesh_squared_distance( 146 | query_points_eigen, 147 | v_eig, f_eig, 148 | sqrD, closest_faces, closest_points_eig) 149 | elapsed += (time.perf_counter() - start) 150 | 151 | igl_elapsed = elapsed / timing_iters 152 | logger.info( 153 | f'LibIGL Points = {num_query_points}: elapsed time {igl_elapsed}') 154 | output_dict[num_query_points]['igl'] = igl_elapsed 155 | 156 | with open(timings_fn, 'w') as f: 157 | yaml.dump(output_dict, f) 158 | -------------------------------------------------------------------------------- /bvh-distance-queries/examples/fit_cube_to_cube.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is 4 | # holder of all proprietary rights on this computer program. 5 | # You can only use this computer program if you have closed 6 | # a license agreement with MPG or you get the right to use the computer 7 | # program from someone who is authorized to grant you that right. 8 | # Any use of the computer program without a valid license is prohibited and 9 | # liable to prosecution. 10 | # 11 | # Copyright©2019 Max-Planck-Gesellschaft zur Förderung 12 | # der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute 13 | # for Intelligent Systems. All rights reserved. 14 | # 15 | # Author: Vasileios Choutas 16 | # Contact: vassilis.choutas@tuebingen.mpg.de 17 | # Contact: ps-license@tuebingen.mpg.de 18 | 19 | import sys 20 | import os 21 | 22 | import time 23 | 24 | import argparse 25 | 26 | import torch 27 | import torch.nn as nn 28 | import torch.optim as optim 29 | 30 | from copy import deepcopy 31 | 32 | import numpy as np 33 | 34 | from loguru import logger 35 | 36 | from psbody.mesh import Mesh 37 | from psbody.mesh.meshviewer import MeshViewer 38 | import kornia 39 | 40 | import bvh_distance_queries 41 | 42 | 43 | if __name__ == "__main__": 44 | 45 | device = torch.device('cuda') 46 | 47 | parser = argparse.ArgumentParser( 48 | formatter_class=argparse.ArgumentDefaultsHelpFormatter) 49 | 50 | parser.add_argument('--pause', type=float, default=None, 51 | help='Pause duration for the viewer') 52 | 53 | args, _ = parser.parse_known_args() 54 | pause = args.pause 55 | 56 | batch_size = 1 57 | m = bvh_distance_queries.PointToMeshResidual() 58 | 59 | template = Mesh(filename='data/test_box.ply') 60 | 61 | template_v = torch.tensor( 62 | template.v, dtype=torch.float32, device=device).reshape(1, -1, 3) 63 | template_f = torch.tensor( 64 | template.f.astype(np.int64), 65 | dtype=torch.long, device=device).reshape(-1, 3) 66 | 67 | template_translation = torch.tensor( 68 | [3, 2, 1], dtype=torch.float32, 69 | device=device).reshape(1, 3) 70 | template_rotation = torch.tensor([1, 2, 3], dtype=torch.float32, 71 | device=device).reshape(1, 3) 72 | template_rotation.requires_grad_(True) 73 | template_translation.requires_grad_(True) 74 | 75 | scan_points = torch.tensor( 76 | template.v, dtype=torch.float32, device=device).reshape(1, -1, 3) 77 | 78 | optimizer = optim.LBFGS([template_translation, template_rotation], 79 | lr=1, line_search_fn='strong_wolfe', 80 | max_iter=20) 81 | 82 | scan = deepcopy(template) 83 | scan.vc = np.ones_like(scan.v) * [0.3, 0.3, 0.3] 84 | 85 | mv = MeshViewer() 86 | 87 | def closure(visualize=False, backward=True): 88 | if backward: 89 | optimizer.zero_grad() 90 | 91 | rot_mat = kornia.angle_axis_to_rotation_matrix(template_rotation) 92 | 93 | vertices = torch.einsum( 94 | 'bij,bmj->bmi', 95 | [rot_mat, template_v]) + template_translation.unsqueeze(dim=1) 96 | 97 | triangles = vertices[:, template_f].contiguous() 98 | 99 | residual, _ = m(triangles, scan_points) 100 | loss = residual.pow(2).sum(dim=-1).mean() 101 | 102 | if backward: 103 | loss.backward() 104 | 105 | if visualize: 106 | template.v = vertices.detach().cpu().numpy().squeeze() 107 | mv.set_static_meshes([template, scan]) 108 | if pause is not None: 109 | time.sleep(pause) 110 | else: 111 | logger.info('Press escape to exit ...') 112 | logger.info('Waiting for key ...') 113 | key = mv.get_keypress() 114 | if key == b'\x1b': 115 | logger.warning('Exiting!') 116 | sys.exit(0) 117 | 118 | return loss 119 | 120 | closure(visualize=True, backward=False) 121 | N = 1000 122 | for n in range(N): 123 | curr_loss = optimizer.step(closure) 124 | closure(visualize=True, backward=False) 125 | 126 | verts_dist = np.sqrt(np.power( 127 | scan_points.detach().cpu().numpy().squeeze() - template.v, 128 | 2).sum(axis=-1)).mean() 129 | logger.info(f'[{n:03d}]: {curr_loss.item():.4f}') 130 | logger.info(f'[{n:03d}]: Vertex-to-vertex distance: {verts_dist} (m)') 131 | -------------------------------------------------------------------------------- /bvh-distance-queries/examples/fit_cube_to_random_points.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is 4 | # holder of all proprietary rights on this computer program. 5 | # You can only use this computer program if you have closed 6 | # a license agreement with MPG or you get the right to use the computer 7 | # program from someone who is authorized to grant you that right. 8 | # Any use of the computer program without a valid license is prohibited and 9 | # liable to prosecution. 10 | # 11 | # Copyright©2019 Max-Planck-Gesellschaft zur Förderung 12 | # der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute 13 | # for Intelligent Systems. All rights reserved. 14 | # 15 | # Author: Vasileios Choutas 16 | # Contact: vassilis.choutas@tuebingen.mpg.de 17 | # Contact: ps-license@tuebingen.mpg.de 18 | 19 | import sys 20 | import os 21 | 22 | import time 23 | 24 | import argparse 25 | 26 | import torch 27 | import torch.nn as nn 28 | import torch.optim as optim 29 | 30 | from copy import deepcopy 31 | 32 | import numpy as np 33 | from scipy.spatial import ConvexHull 34 | 35 | from loguru import logger 36 | 37 | from psbody.mesh import Mesh 38 | from psbody.mesh.meshviewer import MeshViewer 39 | import kornia 40 | 41 | import bvh_distance_queries 42 | 43 | 44 | if __name__ == "__main__": 45 | 46 | device = torch.device('cuda') 47 | 48 | parser = argparse.ArgumentParser( 49 | formatter_class=argparse.ArgumentDefaultsHelpFormatter) 50 | parser.add_argument('--num-query-points', type=int, default=1, 51 | dest='num_query_points', 52 | help='Number of random query points') 53 | parser.add_argument('--seed', type=int, default=None, 54 | help='If given then set the seed') 55 | parser.add_argument('--pause', type=float, default=None, 56 | help='Pause duration for the viewer') 57 | 58 | args, _ = parser.parse_known_args() 59 | 60 | num_query_points = args.num_query_points 61 | seed = args.seed 62 | pause = args.pause 63 | 64 | batch_size = 1 65 | 66 | m = bvh_distance_queries.PointToMeshResidual() 67 | 68 | template = Mesh(filename='data/test_box.ply') 69 | 70 | template_v = torch.tensor( 71 | template.v, dtype=torch.float32, device=device).reshape(1, -1, 3) 72 | template_f = torch.tensor( 73 | template.f.astype(np.int64), 74 | dtype=torch.long, device=device).reshape(-1, 3) 75 | 76 | template_translation = torch.tensor( 77 | [3, 2, 1], dtype=torch.float32, 78 | device=device).reshape(1, 3) 79 | template_rotation = torch.tensor([1, 2, 3], dtype=torch.float32, 80 | device=device).reshape(1, 3) 81 | template_rotation.requires_grad_(True) 82 | template_translation.requires_grad_(True) 83 | 84 | if seed is not None: 85 | np.random.seed(seed) 86 | 87 | v = np.random.rand(9000).reshape((-1, 3)) 88 | f = ConvexHull(v).simplices 89 | scan = Mesh(v=v, f=f, vc=v * 0 + 0.5) 90 | 91 | scan_points = torch.tensor( 92 | scan.v, dtype=torch.float32, device=device).reshape(1, -1, 3) 93 | 94 | optimizer = optim.LBFGS([template_translation, template_rotation], 95 | lr=1, line_search_fn='strong_wolfe', 96 | max_iter=20) 97 | 98 | mv = MeshViewer() 99 | mv.set_static_meshes([template, scan]) 100 | 101 | def closure(visualize=False, backward=True): 102 | if backward: 103 | optimizer.zero_grad() 104 | 105 | rot_mat = kornia.angle_axis_to_rotation_matrix(template_rotation) 106 | 107 | vertices = torch.einsum( 108 | 'bij,bmj->bmi', 109 | [rot_mat, template_v]) + template_translation.unsqueeze(dim=1) 110 | 111 | triangles = vertices[:, template_f].contiguous() 112 | 113 | residual,_ = m(triangles, scan_points) 114 | loss = residual.pow(2).sum(dim=-1).mean() 115 | 116 | if backward: 117 | loss.backward() 118 | 119 | if visualize: 120 | template.v = vertices.detach().cpu().numpy().squeeze() 121 | mv.set_static_meshes([template, scan]) 122 | if pause is not None: 123 | time.sleep(pause) 124 | else: 125 | logger.info('Press escape to exit ...') 126 | logger.info('Waiting for key ...') 127 | key = mv.get_keypress() 128 | if key == b'\x1b': 129 | logger.warning('Exiting!') 130 | sys.exit(0) 131 | return loss 132 | 133 | closure(visualize=True, backward=False) 134 | N = 1000 135 | for n in range(N): 136 | curr_loss = optimizer.step(closure) 137 | logger.info(f'[{n:03d}]: {curr_loss.item():.4f}') 138 | closure(visualize=True, backward=False) 139 | -------------------------------------------------------------------------------- /bvh-distance-queries/examples/random_points_to_surface.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is 4 | # holder of all proprietary rights on this computer program. 5 | # You can only use this computer program if you have closed 6 | # a license agreement with MPG or you get the right to use the computer 7 | # program from someone who is authorized to grant you that right. 8 | # Any use of the computer program without a valid license is prohibited and 9 | # liable to prosecution. 10 | # 11 | # Copyright©2019 Max-Planck-Gesellschaft zur Förderung 12 | # der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute 13 | # for Intelligent Systems. All rights reserved. 14 | # 15 | # Author: Vasileios Choutas 16 | # Contact: vassilis.choutas@tuebingen.mpg.de 17 | # Contact: ps-license@tuebingen.mpg.de 18 | 19 | from __future__ import absolute_import 20 | from __future__ import print_function 21 | from __future__ import division 22 | 23 | import sys 24 | import os 25 | 26 | import time 27 | 28 | import argparse 29 | 30 | try: 31 | input = raw_input 32 | except NameError: 33 | pass 34 | 35 | import open3d as o3d 36 | 37 | import torch 38 | import torch.nn as nn 39 | import torch.autograd as autograd 40 | 41 | from copy import deepcopy 42 | 43 | import numpy as np 44 | import tqdm 45 | 46 | from loguru import logger 47 | 48 | from psbody.mesh import Mesh 49 | import bvh_distance_queries 50 | 51 | 52 | if __name__ == "__main__": 53 | 54 | device = torch.device('cuda') 55 | 56 | parser = argparse.ArgumentParser( 57 | formatter_class=argparse.ArgumentDefaultsHelpFormatter) 58 | parser.add_argument('--mesh-fn', type=str, dest='mesh_fn', 59 | help='A mesh file (.obj, .ply, e.t.c.) to be checked' + 60 | ' for collisions') 61 | parser.add_argument('--num-query-points', type=int, default=1, 62 | dest='num_query_points', 63 | help='Number of random query points') 64 | parser.add_argument('--seed', type=int, default=None, 65 | help='If given then set the seed') 66 | 67 | args, _ = parser.parse_known_args() 68 | 69 | mesh_fn = args.mesh_fn 70 | num_query_points = args.num_query_points 71 | seed = args.seed 72 | 73 | input_mesh = Mesh(filename=mesh_fn) 74 | 75 | if seed is not None: 76 | torch.manual_seed(seed) 77 | 78 | logger.info(f'Number of triangles = {input_mesh.f.shape[0]}') 79 | 80 | v = input_mesh.v 81 | 82 | vertices = torch.tensor(v, dtype=torch.float32, device=device) 83 | faces = torch.tensor(input_mesh.f.astype(np.int64), 84 | dtype=torch.long, 85 | device=device) 86 | 87 | min_vals, _ = torch.min(vertices, dim=0, keepdim=True) 88 | max_vals, _ = torch.max(vertices, dim=0, keepdim=True) 89 | 90 | query_points = torch.rand([1, num_query_points, 3], dtype=torch.float32, 91 | device=device) * (max_vals - min_vals) + min_vals 92 | query_points_np = query_points.detach().cpu().numpy().squeeze( 93 | axis=0).astype(np.float32).reshape(num_query_points, 3) 94 | 95 | batch_size = 1 96 | triangles = vertices[faces].unsqueeze(dim=0) 97 | 98 | m = bvh_distance_queries.BVH() 99 | 100 | torch.cuda.synchronize() 101 | start = time.perf_counter() 102 | distances, closest_points, closest_faces, closest_bcs = m( 103 | triangles, query_points) 104 | torch.cuda.synchronize() 105 | logger.info(f'CUDA Elapsed time {time.perf_counter() - start}') 106 | distances = distances.detach().cpu().numpy() 107 | closest_points = closest_points.detach().cpu().numpy().squeeze() 108 | 109 | mesh = o3d.geometry.TriangleMesh() 110 | mesh.vertices = o3d.utility.Vector3dVector(v) 111 | mesh.triangles = o3d.utility.Vector3iVector(input_mesh.f.astype(np.int64)) 112 | mesh.compute_vertex_normals() 113 | mesh.paint_uniform_color([0.3, 0.3, 0.3]) 114 | 115 | query_pcl = o3d.geometry.PointCloud() 116 | query_pcl.points = o3d.utility.Vector3dVector( 117 | query_points.detach().cpu().numpy().squeeze(axis=0).reshape(-1, 3)) 118 | query_pcl.paint_uniform_color([0.9, 0.3, 0.3]) 119 | 120 | closest_points_pcl = o3d.geometry.PointCloud() 121 | closest_points_pcl.points = o3d.utility.Vector3dVector( 122 | closest_points.reshape(-1, 3)) 123 | closest_points_pcl.paint_uniform_color([0.3, 0.3, 0.9]) 124 | 125 | o3d.visualization.draw_geometries([ 126 | mesh, 127 | query_pcl, 128 | closest_points_pcl, 129 | ]) 130 | -------------------------------------------------------------------------------- /bvh-distance-queries/include/aabb.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is 3 | * holder of all proprietary rights on this computer program. 4 | * You can only use this computer program if you have closed 5 | * a license agreement with MPG or you get the right to use the computer 6 | * program from someone who is authorized to grant you that right. 7 | * Any use of the computer program without a valid license is prohibited and 8 | * liable to prosecution. 9 | * 10 | * Copyright©2019 Max-Planck-Gesellschaft zur Förderung 11 | * der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute 12 | * for Intelligent Systems. All rights reserved. 13 | * 14 | * @author Vasileios Choutas 15 | * Contact: vassilis.choutas@tuebingen.mpg.de 16 | * Contact: ps-license@tuebingen.mpg.de 17 | * 18 | */ 19 | 20 | #ifndef AABB_H 21 | #define AABB_H 22 | 23 | #include 24 | #include "device_launch_parameters.h" 25 | #include 26 | 27 | #include "defs.hpp" 28 | #include "math_utils.hpp" 29 | #include "double_vec_ops.h" 30 | #include "helper_math.h" 31 | 32 | 33 | template 34 | __align__(32) 35 | struct AABB { 36 | public: 37 | __host__ __device__ AABB() { 38 | min_t.x = std::is_same::value ? FLT_MAX : DBL_MAX; 39 | min_t.y = std::is_same::value ? FLT_MAX : DBL_MAX; 40 | min_t.z = std::is_same::value ? FLT_MAX : DBL_MAX; 41 | 42 | max_t.x = std::is_same::value ? -FLT_MAX : -DBL_MAX; 43 | max_t.y = std::is_same::value ? -FLT_MAX : -DBL_MAX; 44 | max_t.z = std::is_same::value ? -FLT_MAX : -DBL_MAX; 45 | }; 46 | 47 | __host__ __device__ AABB(const vec3 &min_t, const vec3 &max_t) 48 | : min_t(min_t), max_t(max_t){}; 49 | __host__ __device__ ~AABB(){}; 50 | 51 | __host__ __device__ AABB(T min_t_x, T min_t_y, T min_t_z, T max_t_x, 52 | T max_t_y, T max_t_z) { 53 | min_t.x = min_t_x; 54 | min_t.y = min_t_y; 55 | min_t.z = min_t_z; 56 | max_t.x = max_t_x; 57 | max_t.y = max_t_y; 58 | max_t.z = max_t_z; 59 | } 60 | 61 | __host__ __device__ AABB operator+(const AABB &bbox2) const { 62 | return AABB( 63 | min(this->min_t.x, bbox2.min_t.x), min(this->min_t.y, bbox2.min_t.y), 64 | min(this->min_t.z, bbox2.min_t.z), max(this->max_t.x, bbox2.max_t.x), 65 | max(this->max_t.y, bbox2.max_t.y), max(this->max_t.z, bbox2.max_t.z)); 66 | }; 67 | 68 | __host__ __device__ T distance(const vec3 point) const { 69 | }; 70 | 71 | __host__ __device__ T operator*(const AABB &bbox2) const { 72 | return (min(this->max_t.x, bbox2.max_t.x) - 73 | max(this->min_t.x, bbox2.min_t.x)) * 74 | (min(this->max_t.y, bbox2.max_t.y) - 75 | max(this->min_t.y, bbox2.min_t.y)) * 76 | (min(this->max_t.z, bbox2.max_t.z) - 77 | max(this->min_t.z, bbox2.min_t.z)); 78 | }; 79 | 80 | vec3 min_t; 81 | vec3 max_t; 82 | }; 83 | 84 | template 85 | std::ostream &operator<<(std::ostream &os, const AABB &x) { 86 | os << x.min_t << std::endl; 87 | os << x.max_t << std::endl; 88 | return os; 89 | } 90 | 91 | template struct MergeAABB { 92 | 93 | public: 94 | __host__ __device__ MergeAABB(){}; 95 | 96 | // Create an operator Struct that will be used by thrust::reduce 97 | // to calculate the bounding box of the scene. 98 | __host__ __device__ AABB operator()(const AABB &bbox1, 99 | const AABB &bbox2) { 100 | return bbox1 + bbox2; 101 | }; 102 | }; 103 | 104 | 105 | 106 | template 107 | __forceinline__ 108 | __host__ __device__ T pointToAABBDistance(vec3 point, const AABB& bbox ) { 109 | T diff_x = point.x - clamp(point.x, bbox.min_t.x, bbox.max_t.x); 110 | T diff_y = point.y - clamp(point.y, bbox.min_t.y, bbox.max_t.y); 111 | T diff_z = point.z - clamp(point.z, bbox.min_t.z, bbox.max_t.z); 112 | 113 | return diff_x * diff_x + diff_y * diff_y + diff_z * diff_z; 114 | } 115 | 116 | 117 | #endif // ifndef AABB_H 118 | -------------------------------------------------------------------------------- /bvh-distance-queries/include/defs.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is 3 | * holder of all proprietary rights on this computer program. 4 | * You can only use this computer program if you have closed 5 | * a license agreement with MPG or you get the right to use the computer 6 | * program from someone who is authorized to grant you that right. 7 | * Any use of the computer program without a valid license is prohibited and 8 | * liable to prosecution. 9 | * 10 | * Copyright©2019 Max-Planck-Gesellschaft zur Förderung 11 | * der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute 12 | * for Intelligent Systems. All rights reserved. 13 | * 14 | * @author Vasileios Choutas 15 | * Contact: vassilis.choutas@tuebingen.mpg.de 16 | * Contact: ps-license@tuebingen.mpg.de 17 | * 18 | */ 19 | 20 | #ifndef DEFINITIONS_H 21 | #define DEFINITIONS_H 22 | 23 | #include 24 | #include "device_launch_parameters.h" 25 | #include 26 | 27 | template 28 | using vec3 = typename std::conditional::value, float3, 29 | double3>::type; 30 | 31 | template 32 | using vec2 = typename std::conditional::value, float2, 33 | double2>::type; 34 | 35 | float3 make_float3(double3 vec) { 36 | return make_float3(vec.x, vec.y, vec.z); 37 | } 38 | 39 | float3 make_float3(double x, double y, double z) { 40 | return make_float3(x, y, z); 41 | } 42 | 43 | double3 make_double3(float3 vec) { 44 | return make_double3(vec.x, vec.y, vec.z); 45 | } 46 | 47 | double3 make_double3(float x, float y, float z) { 48 | return make_double3(x, y, z); 49 | } 50 | 51 | template 52 | __host__ __device__ 53 | vec3 make_vec3(T x, T y, T z) { 54 | } 55 | 56 | template <> 57 | __host__ __device__ 58 | vec3 make_vec3(float x, float y, float z) { 59 | return make_float3(static_cast(x), static_cast(y), static_cast(z)); 60 | } 61 | 62 | template <> 63 | __host__ __device__ 64 | vec3 make_vec3(double x, double y, double z) { 65 | return make_double3(static_cast(x), static_cast(y), static_cast(z)); 66 | } 67 | 68 | #endif // ifndef DEFINITIONS_H 69 | -------------------------------------------------------------------------------- /bvh-distance-queries/include/double_vec_ops.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is 3 | * holder of all proprietary rights on this computer program. 4 | * You can only use this computer program if you have closed 5 | * a license agreement with MPG or you get the right to use the computer 6 | * program from someone who is authorized to grant you that right. 7 | * Any use of the computer program without a valid license is prohibited and 8 | * liable to prosecution. 9 | * 10 | * Copyright©2019 Max-Planck-Gesellschaft zur Förderung 11 | * der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute 12 | * for Intelligent Systems. All rights reserved. 13 | * 14 | * @author Vasileios Choutas 15 | * Contact: vassilis.choutas@tuebingen.mpg.de 16 | * Contact: ps-license@tuebingen.mpg.de 17 | * 18 | */ 19 | 20 | 21 | #ifndef DOUBLE_VEC_OPS_H 22 | #define DOUBLE_VEC_OPS_H 23 | 24 | #include "cuda_runtime.h" 25 | 26 | inline __host__ __device__ double2 operator+(double2 a, double2 b) { 27 | return make_double2(a.x + b.x, a.y + b.y); 28 | } 29 | 30 | 31 | inline __host__ __device__ double3 operator+(double3 a, double3 b) { 32 | return make_double3(a.x + b.x, a.y + b.y, a.z + b.z); 33 | } 34 | 35 | inline __host__ __device__ void operator/=(double2 &a, double2 b) { 36 | a.x /= b.x; 37 | a.y /= b.y; 38 | } 39 | 40 | inline __host__ __device__ double2 operator/(double2 a, double b) { 41 | return make_double2(a.x / b, a.y / b); 42 | } 43 | 44 | inline __host__ __device__ double3 operator/(double3 a, double3 b) { 45 | return make_double3(a.x / b.x, a.y / b.y, a.z / b.z); 46 | } 47 | 48 | 49 | inline __host__ __device__ double3 operator*(double a, double3 b) { 50 | return make_double3(a * b.x, a * b.y, a * b.z); 51 | } 52 | 53 | inline __host__ __device__ double3 operator*(double3 a, double3 b) { 54 | return make_double3(a.x * b.x, a.y * b.y, a.z * b.z); 55 | } 56 | 57 | inline __host__ __device__ void operator/=(double3 &a, double3 b) { 58 | a.x /= b.x; 59 | a.y /= b.y; 60 | a.z /= b.z; 61 | } 62 | 63 | inline __host__ __device__ double3 operator/(double3 a, double b) { 64 | return make_double3(a.x / b, a.y / b, a.z / b); 65 | } 66 | 67 | inline __host__ __device__ double dot(double2 a, double2 b) { 68 | return a.x * b.x + a.y * b.y; 69 | } 70 | 71 | inline __host__ __device__ double dot(double3 a, double3 b) { 72 | return a.x * b.x + a.y * b.y + a.z * b.z; 73 | } 74 | 75 | inline __host__ __device__ double3 cross(double3 a, double3 b) 76 | { 77 | return make_double3(a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x); 78 | } 79 | 80 | inline __host__ __device__ double2 operator-(double2 a, double2 b) 81 | { 82 | return make_double2(a.x - b.x, a.y - b.y); 83 | } 84 | inline __host__ __device__ void operator-=(double2 &a, double2 b) 85 | { 86 | a.x -= b.x; 87 | a.y -= b.y; 88 | } 89 | inline __host__ __device__ double2 operator-(double2 a, double b) 90 | { 91 | return make_double2(a.x - b, a.y - b); 92 | } 93 | inline __host__ __device__ double2 operator-(double b, double2 a) 94 | { 95 | return make_double2(b - a.x, b - a.y); 96 | } 97 | 98 | inline __host__ __device__ double3 operator-(double3 a, double3 b) 99 | { 100 | return make_double3(a.x - b.x, a.y - b.y, a.z - b.z); 101 | } 102 | inline __host__ __device__ void operator-=(double3 &a, double3 b) 103 | { 104 | a.x -= b.x; 105 | a.y -= b.y; 106 | a.z -= b.z; 107 | } 108 | inline __host__ __device__ double3 operator-(double3 a, double b) 109 | { 110 | return make_double3(a.x - b, a.y - b, a.z - b); 111 | } 112 | inline __host__ __device__ double3 operator-(double b, double3 a) 113 | { 114 | return make_double3(b - a.x, b - a.y, b - a.z); 115 | } 116 | 117 | #endif // ifndef DOUBLE_VEC_OPS_H 118 | -------------------------------------------------------------------------------- /bvh-distance-queries/include/math_utils.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is 3 | * holder of all proprietary rights on this computer program. 4 | * You can only use this computer program if you have closed 5 | * a license agreement with MPG or you get the right to use the computer 6 | * program from someone who is authorized to grant you that right. 7 | * Any use of the computer program without a valid license is prohibited and 8 | * liable to prosecution. 9 | * 10 | * Copyright©2019 Max-Planck-Gesellschaft zur Förderung 11 | * der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute 12 | * for Intelligent Systems. All rights reserved. 13 | * 14 | * @author Vasileios Choutas 15 | * Contact: vassilis.choutas@tuebingen.mpg.de 16 | * Contact: ps-license@tuebingen.mpg.de 17 | * 18 | */ 19 | 20 | #ifndef MATH_UTILS_H 21 | #define MATH_UTILS_H 22 | 23 | #include 24 | #include "device_launch_parameters.h" 25 | #include 26 | 27 | #include "defs.hpp" 28 | #include "double_vec_ops.h" 29 | #include "helper_math.h" 30 | 31 | 32 | template 33 | __host__ __device__ T sign(T x) { 34 | return x > 0 ? 1 : (x < 0 ? -1 : 0); 35 | } 36 | 37 | 38 | template 39 | __host__ __device__ __forceinline__ float vec_abs_diff(const vec3 &vec1, 40 | const vec3 &vec2) { 41 | return fabs(vec1.x - vec2.x) + fabs(vec1.y - vec2.y) + fabs(vec1.z - vec2.z); 42 | } 43 | 44 | template 45 | __host__ __device__ __forceinline__ float vec_sq_diff(const vec3 &vec1, 46 | const vec3 &vec2) { 47 | return dot(vec1 - vec2, vec1 - vec2); 48 | } 49 | 50 | template 51 | __host__ __device__ __forceinline__ T clamp(T value, T min_value, T max_value) { 52 | return min(max(value, min_value), max_value); 53 | } 54 | 55 | template __host__ __device__ T dot2(vec3 v) { 56 | return dot(v, v); 57 | } 58 | #endif // ifndef MATH_UTILS_H 59 | -------------------------------------------------------------------------------- /bvh-distance-queries/include/priority_queue.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is 3 | * holder of all proprietary rights on this computer program. 4 | * You can only use this computer program if you have closed 5 | * a license agreement with MPG or you get the right to use the computer 6 | * program from someone who is authorized to grant you that right. 7 | * Any use of the computer program without a valid license is prohibited and 8 | * liable to prosecution. 9 | * 10 | * Copyright©2019 Max-Planck-Gesellschaft zur Förderung 11 | * der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute 12 | * for Intelligent Systems. All rights reserved. 13 | * 14 | * @author Vasileios Choutas 15 | * Contact: vassilis.choutas@tuebingen.mpg.de 16 | * Contact: ps-license@tuebingen.mpg.de 17 | * 18 | */ 19 | 20 | #ifndef PRIORITY_QUEUE_H 21 | #define PRIORITY_QUEUE_H 22 | 23 | #include 24 | #include 25 | #include 26 | 27 | #include 28 | #include "device_launch_parameters.h" 29 | #include 30 | 31 | template 32 | __host__ __device__ 33 | void swap_array_els(T* array, int i, int j) { 34 | T tmp = array[i]; 35 | array[i] = array[j]; 36 | array[j] = tmp; 37 | } 38 | 39 | template 40 | class PriorityQueue { 41 | public: 42 | __host__ __device__ 43 | PriorityQueue() : heap_size(0) {} 44 | 45 | inline 46 | __host__ __device__ 47 | int get_size() { 48 | return heap_size; 49 | } 50 | 51 | inline 52 | __host__ __device__ 53 | int parent(int i) { 54 | return (i - 1) / 2; 55 | } 56 | 57 | inline 58 | __host__ __device__ 59 | int left_child(int i) { 60 | return 2 * i + 1; 61 | } 62 | 63 | inline 64 | __host__ __device__ 65 | int right_child(int i) { 66 | return 2 * i + 2; 67 | } 68 | 69 | __host__ __device__ 70 | std::pair get_min() { 71 | if (heap_size > 0) { 72 | return std::pair(priority_heap[0], obj_heap[0]); 73 | } 74 | else { 75 | return std::pair( 76 | std::is_same::value ? FLT_MAX : DBL_MAX, nullptr); 77 | } 78 | } 79 | 80 | __host__ __device__ 81 | void min_heapify(int index) { 82 | if (recursive) { 83 | int left = left_child(index); 84 | int right = right_child(index); 85 | int smallest = index; 86 | if (left < heap_size && priority_heap[left] < priority_heap[index]) 87 | smallest = left; 88 | if (right < heap_size && priority_heap[right] < priority_heap[index]) 89 | smallest = right; 90 | if (smallest != index) { 91 | swap_array_els(priority_heap, index, smallest); 92 | swap_array_els(obj_heap, index, smallest); 93 | min_heapify(smallest); 94 | } 95 | } else { 96 | int ii = index; 97 | int smallest; 98 | while (true) { 99 | int left = left_child(ii); 100 | int right = right_child(ii); 101 | smallest = ii; 102 | 103 | if (left < heap_size && priority_heap[left] < priority_heap[ii]) 104 | smallest = left; 105 | if (right < heap_size && priority_heap[right] < priority_heap[ii]) 106 | smallest = right; 107 | 108 | if (smallest != ii) { 109 | swap_array_els(priority_heap, ii, smallest); 110 | swap_array_els(obj_heap, ii, smallest); 111 | ii = smallest; 112 | } 113 | else 114 | break; 115 | } 116 | } 117 | } 118 | 119 | __host__ __device__ 120 | void insert_key(T key, Obj obj) { 121 | if (heap_size == QueueSize) { 122 | printf("The queue has exceed its maximum size\n"); 123 | return; 124 | } 125 | heap_size++; 126 | int ii = heap_size - 1; 127 | priority_heap[ii] = key; 128 | obj_heap[ii] = obj; 129 | 130 | // Fix the min heap property if it is violated 131 | min_heapify(0); 132 | // while (ii != 0 && priority_heap[parent(ii)] > priority_heap[ii]) { 133 | // swap_array_els(priority_heap, ii, parent(ii)); 134 | // swap_array_els(obj_heap, ii, parent(ii)); 135 | // ii = parent(ii); 136 | // } 137 | } 138 | 139 | // void print() { 140 | // for (int i = 0; i < heap_size; i++) { 141 | // std::cout << i << ": " << heap[i] << std::endl; 142 | // } 143 | // } 144 | 145 | __host__ __device__ 146 | std::pair extract() { 147 | if (heap_size <= 0) 148 | return std::pair( 149 | std::is_same::value ? FLT_MAX : DBL_MAX, nullptr); 150 | 151 | T root_prio = priority_heap[0]; 152 | Obj root_obj = obj_heap[0]; 153 | // Replace the root with the last element 154 | priority_heap[0] = priority_heap[heap_size - 1]; 155 | obj_heap[0] = obj_heap[heap_size - 1]; 156 | // Decrease the size of the heap 157 | heap_size--; 158 | 159 | min_heapify(0); 160 | return std::pair(root_prio, root_obj); 161 | } 162 | 163 | private: 164 | T priority_heap[QueueSize]; 165 | Obj obj_heap[QueueSize]; 166 | int heap_size; 167 | }; 168 | 169 | #endif // #ifndef PRIORITY_QUEUE_H 170 | -------------------------------------------------------------------------------- /bvh-distance-queries/include/triangle.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is 3 | * holder of all proprietary rights on this computer program. 4 | * You can only use this computer program if you have closed 5 | * a license agreement with MPG or you get the right to use the computer 6 | * program from someone who is authorized to grant you that right. 7 | * Any use of the computer program without a valid license is prohibited and 8 | * liable to prosecution. 9 | * 10 | * Copyright©2019 Max-Planck-Gesellschaft zur Förderung 11 | * der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute 12 | * for Intelligent Systems. All rights reserved. 13 | * 14 | * @author Vasileios Choutas 15 | * Contact: vassilis.choutas@tuebingen.mpg.de 16 | * Contact: ps-license@tuebingen.mpg.de 17 | * 18 | */ 19 | 20 | #ifndef TRIANGLE_H 21 | #define TRIANGLE_H 22 | 23 | #include "defs.hpp" 24 | #include "double_vec_ops.h" 25 | #include "helper_math.h" 26 | 27 | #include "math_utils.hpp" 28 | #include 29 | #include 30 | #include 31 | 32 | template 33 | __align__(48) 34 | struct Triangle { 35 | public: 36 | vec3 v0; 37 | vec3 v1; 38 | vec3 v2; 39 | 40 | __host__ __device__ Triangle() {} 41 | __host__ __device__ Triangle(vec3 vertex0, vec3 vertex1, 42 | vec3 vertex2) 43 | : v0(vertex0), v1(vertex1), v2(vertex2){}; 44 | __host__ __device__ Triangle(const vec3 &vertex0, const vec3 &vertex1, 45 | const vec3 &vertex2) 46 | : v0(vertex0), v1(vertex1), v2(vertex2){}; 47 | 48 | __host__ __device__ AABB ComputeBBox() { 49 | return AABB(min(v0.x, min(v1.x, v2.x)), min(v0.y, min(v1.y, v2.y)), 50 | min(v0.z, min(v1.z, v2.z)), max(v0.x, max(v1.x, v2.x)), 51 | max(v0.y, max(v1.y, v2.y)), max(v0.z, max(v1.z, v2.z))); 52 | } 53 | }; 54 | 55 | template using TrianglePtr = Triangle *; 56 | 57 | template 58 | std::ostream &operator<<(std::ostream &os, const Triangle &x) { 59 | os << x.v0 << std::endl; 60 | os << x.v1 << std::endl; 61 | os << x.v2 << std::endl; 62 | return os; 63 | } 64 | 65 | 66 | #endif // TRIANGLE_H 67 | -------------------------------------------------------------------------------- /bvh-distance-queries/optional-requirements.txt: -------------------------------------------------------------------------------- 1 | open3d>=0.8.0.0 2 | -------------------------------------------------------------------------------- /bvh-distance-queries/requirements.txt: -------------------------------------------------------------------------------- 1 | numpy>=1.16.2 2 | torch>=1.0 3 | loguru 4 | kornia 5 | -------------------------------------------------------------------------------- /bvh-distance-queries/setup.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is 4 | # holder of all proprietary rights on this computer program. 5 | # You can only use this computer program if you have closed 6 | # a license agreement with MPG or you get the right to use the computer 7 | # program from someone who is authorized to grant you that right. 8 | # Any use of the computer program without a valid license is prohibited and 9 | # liable to prosecution. 10 | # 11 | # Copyright©2019 Max-Planck-Gesellschaft zur Förderung 12 | # der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute 13 | # for Intelligent Systems and the Max Planck Institute for Biological 14 | # Cybernetics. All rights reserved. 15 | # 16 | # Contact: ps-license@tuebingen.mpg.deimport io 17 | 18 | import io 19 | import os 20 | import os.path as osp 21 | 22 | from setuptools import find_packages, setup 23 | 24 | import torch 25 | from torch.utils.cpp_extension import BuildExtension, CUDAExtension 26 | 27 | # Package meta-data. 28 | NAME = 'bvh_distance_queries' 29 | DESCRIPTION = 'PyTorch module for Mesh self intersection detection' 30 | URL = '' 31 | EMAIL = 'vassilis.choutas@tuebingen.mpg.de' 32 | AUTHOR = 'Vassilis Choutas' 33 | REQUIRES_PYTHON = '>=3.6.0' 34 | VERSION = '0.1.0' 35 | 36 | here = os.path.abspath(os.path.dirname(__file__)) 37 | 38 | try: 39 | FileNotFoundError 40 | except NameError: 41 | FileNotFoundError = IOError 42 | # Import the README and use it as the long-description. 43 | # Note: this will only work if 'README.md' is present in your MANIFEST.in file! 44 | try: 45 | with io.open(os.path.join(here, 'README.md'), encoding='utf-8') as f: 46 | long_description = '\n' + f.read() 47 | except FileNotFoundError: 48 | long_description = DESCRIPTION 49 | 50 | # Load the package's __version__.py module as a dictionary. 51 | about = {} 52 | if not VERSION: 53 | with open(os.path.join(here, NAME, '__version__.py')) as f: 54 | exec(f.read(), about) 55 | else: 56 | about['__version__'] = VERSION 57 | 58 | bvh_src_files = ['src/bvh.cpp', 'src/bvh_cuda_op.cu'] 59 | bvh_include_dirs = torch.utils.cpp_extension.include_paths() + [ 60 | 'include', 61 | osp.expandvars('cuda-samples/Common')] 62 | 63 | bvh_extra_compile_args = {'nvcc': ['-DPRINT_TIMINGS=0', 64 | '-DDEBUG_PRINT=0', 65 | '-DERROR_CHECKING=1', 66 | '-DNUM_THREADS=256', 67 | '-DBVH_PROFILING=0', 68 | ], 69 | 'cxx': []} 70 | bvh_extension = CUDAExtension('bvh_distance_queries_cuda', 71 | bvh_src_files, 72 | include_dirs=bvh_include_dirs, 73 | extra_compile_args=bvh_extra_compile_args) 74 | 75 | setup(name=NAME, 76 | version=about['__version__'], 77 | description=DESCRIPTION, 78 | long_description=long_description, 79 | long_description_content_type='text/markdown', 80 | author=AUTHOR, 81 | author_email=EMAIL, 82 | python_requires=REQUIRES_PYTHON, 83 | url=URL, 84 | packages=find_packages(), 85 | ext_modules=[bvh_extension], 86 | classifiers=[ 87 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", 88 | "Environment :: Console", 89 | "Programming Language :: Python", 90 | "Programming Language :: Python :: 3.6", 91 | "Programming Language :: Python :: 3.7"], 92 | install_requires=[ 93 | 'torch>=1.0.1', 94 | ], 95 | cmdclass={'build_ext': BuildExtension}) 96 | -------------------------------------------------------------------------------- /bvh-distance-queries/src/aabb.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is 3 | * holder of all proprietary rights on this computer program. 4 | * You can only use this computer program if you have closed 5 | * a license agreement with MPG or you get the right to use the computer 6 | * program from someone who is authorized to grant you that right. 7 | * Any use of the computer program without a valid license is prohibited and 8 | * liable to prosecution. 9 | * 10 | * Copyright©2019 Max-Planck-Gesellschaft zur Förderung 11 | * der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute 12 | * for Intelligent Systems. All rights reserved. 13 | * 14 | * @author Vasileios Choutas 15 | * Contact: vassilis.choutas@tuebingen.mpg.de 16 | * Contact: ps-license@tuebingen.mpg.de 17 | * 18 | */ 19 | 20 | #ifndef AABB_H 21 | #define AABB_H 22 | 23 | #include 24 | #include "device_launch_parameters.h" 25 | #include 26 | 27 | #include "defs.hpp" 28 | #include "math_utils.hpp" 29 | #include "double_vec_ops.h" 30 | #include "helper_math.h" 31 | 32 | 33 | template 34 | __align__(32) 35 | struct AABB { 36 | public: 37 | __host__ __device__ AABB() { 38 | min_t.x = std::is_same::value ? FLT_MAX : DBL_MAX; 39 | min_t.y = std::is_same::value ? FLT_MAX : DBL_MAX; 40 | min_t.z = std::is_same::value ? FLT_MAX : DBL_MAX; 41 | 42 | max_t.x = std::is_same::value ? -FLT_MAX : -DBL_MAX; 43 | max_t.y = std::is_same::value ? -FLT_MAX : -DBL_MAX; 44 | max_t.z = std::is_same::value ? -FLT_MAX : -DBL_MAX; 45 | }; 46 | 47 | __host__ __device__ AABB(const vec3 &min_t, const vec3 &max_t) 48 | : min_t(min_t), max_t(max_t){}; 49 | __host__ __device__ ~AABB(){}; 50 | 51 | __host__ __device__ AABB(T min_t_x, T min_t_y, T min_t_z, T max_t_x, 52 | T max_t_y, T max_t_z) { 53 | min_t.x = min_t_x; 54 | min_t.y = min_t_y; 55 | min_t.z = min_t_z; 56 | max_t.x = max_t_x; 57 | max_t.y = max_t_y; 58 | max_t.z = max_t_z; 59 | } 60 | 61 | __host__ __device__ AABB operator+(const AABB &bbox2) const { 62 | return AABB( 63 | min(this->min_t.x, bbox2.min_t.x), min(this->min_t.y, bbox2.min_t.y), 64 | min(this->min_t.z, bbox2.min_t.z), max(this->max_t.x, bbox2.max_t.x), 65 | max(this->max_t.y, bbox2.max_t.y), max(this->max_t.z, bbox2.max_t.z)); 66 | }; 67 | 68 | __host__ __device__ T distance(const vec3 point) const { 69 | }; 70 | 71 | __host__ __device__ T operator*(const AABB &bbox2) const { 72 | return (min(this->max_t.x, bbox2.max_t.x) - 73 | max(this->min_t.x, bbox2.min_t.x)) * 74 | (min(this->max_t.y, bbox2.max_t.y) - 75 | max(this->min_t.y, bbox2.min_t.y)) * 76 | (min(this->max_t.z, bbox2.max_t.z) - 77 | max(this->min_t.z, bbox2.min_t.z)); 78 | }; 79 | 80 | vec3 min_t; 81 | vec3 max_t; 82 | }; 83 | 84 | template 85 | std::ostream &operator<<(std::ostream &os, const AABB &x) { 86 | os << x.min_t << std::endl; 87 | os << x.max_t << std::endl; 88 | return os; 89 | } 90 | 91 | template struct MergeAABB { 92 | 93 | public: 94 | __host__ __device__ MergeAABB(){}; 95 | 96 | // Create an operator Struct that will be used by thrust::reduce 97 | // to calculate the bounding box of the scene. 98 | __host__ __device__ AABB operator()(const AABB &bbox1, 99 | const AABB &bbox2) { 100 | return bbox1 + bbox2; 101 | }; 102 | }; 103 | 104 | 105 | 106 | template 107 | __forceinline__ 108 | __host__ __device__ T pointToAABBDistance(vec3 point, const AABB& bbox ) { 109 | T diff_x = point.x - clamp(point.x, bbox.min_t.x, bbox.max_t.x); 110 | T diff_y = point.y - clamp(point.y, bbox.min_t.y, bbox.max_t.y); 111 | T diff_z = point.z - clamp(point.z, bbox.min_t.z, bbox.max_t.z); 112 | 113 | return diff_x * diff_x + diff_y * diff_y + diff_z * diff_z; 114 | } 115 | 116 | 117 | #endif // ifndef AABB_H 118 | -------------------------------------------------------------------------------- /bvh-distance-queries/src/bvh.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is 3 | * holder of all proprietary rights on this computer program. 4 | * You can only use this computer program if you have closed 5 | * a license agreement with MPG or you get the right to use the computer 6 | * program from someone who is authorized to grant you that right. 7 | * Any use of the computer program without a valid license is prohibited and 8 | * liable to prosecution. 9 | * 10 | * Copyright©2019 Max-Planck-Gesellschaft zur Förderung 11 | * der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute 12 | * for Intelligent Systems. All rights reserved. 13 | * 14 | * @author Vasileios Choutas 15 | * Contact: vassilis.choutas@tuebingen.mpg.de 16 | * Contact: ps-license@tuebingen.mpg.de 17 | * 18 | */ 19 | 20 | 21 | 22 | #include 23 | #include 24 | #include 25 | 26 | #include 27 | 28 | 29 | void bvh_distance_queries_kernel(const torch::Tensor& triangles, 30 | const torch::Tensor& points, 31 | torch::Tensor* distances, 32 | torch::Tensor* closest_points, 33 | torch::Tensor* closest_faces, 34 | torch::Tensor* closest_bcs, 35 | int queue_size=128, 36 | bool sort_points_by_morton=true 37 | ); 38 | 39 | // void bvh_self_distance_queries_kernel(torch::Tensor triangles, 40 | // torch::Tensor* distances, 41 | // torch::Tensor* closest_points 42 | // ); 43 | 44 | #define CHECK_CUDA(x) TORCH_CHECK(x.type().is_cuda(), #x " must be a CUDA tensor") 45 | #define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous") 46 | #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) 47 | 48 | std::vector bvh_distance_queries(torch::Tensor triangles, 49 | torch::Tensor points, 50 | int queue_size=128, 51 | bool sort_points_by_morton=true) { 52 | CHECK_INPUT(triangles); 53 | CHECK_INPUT(points); 54 | 55 | auto options = torch::TensorOptions() 56 | .dtype(triangles.dtype()) 57 | .layout(triangles.layout()) 58 | .device(triangles.device()); 59 | 60 | torch::Tensor distances = torch::full({ 61 | triangles.size(0), points.size(1)}, 62 | -1, options); 63 | torch::Tensor closest_points = torch::full({ 64 | triangles.size(0), points.size(1), 3}, 65 | -1, options); 66 | torch::Tensor closest_bcs = torch::full({ 67 | triangles.size(0), points.size(1), 3}, 0, 68 | options); 69 | torch::Tensor closest_faces = torch::full({ 70 | triangles.size(0), points.size(1)}, 71 | -1, torch::TensorOptions() 72 | .dtype(torch::kLong) 73 | .layout(triangles.layout()) 74 | .device(triangles.device())); 75 | 76 | bvh_distance_queries_kernel(triangles, 77 | points, &distances, &closest_points, &closest_faces, 78 | &closest_bcs, 79 | queue_size, sort_points_by_morton); 80 | 81 | return {distances, closest_points, closest_faces, closest_bcs}; 82 | } 83 | 84 | // std::vector bvh_self_distance_queries(torch::Tensor triangles) { 85 | // CHECK_INPUT(triangles); 86 | 87 | // torch::Tensor distances = torch::full({ 88 | // triangles.size(0), triangles.size(1)}, 89 | // -1, torch::device(triangles.device()).dtype(triangles.dtype())); 90 | // torch::Tensor closest_points = torch::full({ 91 | // triangles.size(0), triangles.size(1), 3}, 92 | // -1, torch::device(triangles.device()).dtype(triangles.dtype())); 93 | 94 | // return {distances, closest_points}; 95 | // } 96 | 97 | PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { 98 | m.def("distance_queries", &bvh_distance_queries, "BVH distance queries forward (CUDA)", 99 | py::arg("triangles"), py::arg("points"), 100 | py::arg("queue_size") = 128, 101 | py::arg("sort_points_by_morton") = true 102 | ); 103 | // m.def("self_distance_queries", &bvh_self_distance_queries, "BVH self distance queries forward (CUDA)", 104 | // py::arg("triangles")); 105 | } 106 | -------------------------------------------------------------------------------- /bvh-distance-queries/src/defs.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is 3 | * holder of all proprietary rights on this computer program. 4 | * You can only use this computer program if you have closed 5 | * a license agreement with MPG or you get the right to use the computer 6 | * program from someone who is authorized to grant you that right. 7 | * Any use of the computer program without a valid license is prohibited and 8 | * liable to prosecution. 9 | * 10 | * Copyright©2019 Max-Planck-Gesellschaft zur Förderung 11 | * der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute 12 | * for Intelligent Systems. All rights reserved. 13 | * 14 | * @author Vasileios Choutas 15 | * Contact: vassilis.choutas@tuebingen.mpg.de 16 | * Contact: ps-license@tuebingen.mpg.de 17 | * 18 | */ 19 | 20 | #ifndef DEFINITIONS_H 21 | #define DEFINITIONS_H 22 | 23 | #include 24 | #include "device_launch_parameters.h" 25 | #include 26 | 27 | template 28 | using vec3 = typename std::conditional::value, float3, 29 | double3>::type; 30 | 31 | template 32 | using vec2 = typename std::conditional::value, float2, 33 | double2>::type; 34 | 35 | float3 make_float3(double3 vec) { 36 | return make_float3(vec.x, vec.y, vec.z); 37 | } 38 | 39 | float3 make_float3(double x, double y, double z) { 40 | return make_float3(x, y, z); 41 | } 42 | 43 | double3 make_double3(float3 vec) { 44 | return make_double3(vec.x, vec.y, vec.z); 45 | } 46 | 47 | double3 make_double3(float x, float y, float z) { 48 | return make_double3(x, y, z); 49 | } 50 | 51 | template 52 | __host__ __device__ 53 | vec3 make_vec3(T x, T y, T z) { 54 | } 55 | 56 | template <> 57 | __host__ __device__ 58 | vec3 make_vec3(float x, float y, float z) { 59 | return make_float3(static_cast(x), static_cast(y), static_cast(z)); 60 | } 61 | 62 | template <> 63 | __host__ __device__ 64 | vec3 make_vec3(double x, double y, double z) { 65 | return make_double3(static_cast(x), static_cast(y), static_cast(z)); 66 | } 67 | 68 | #endif // ifndef DEFINITIONS_H 69 | -------------------------------------------------------------------------------- /bvh-distance-queries/src/double_vec_ops.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is 3 | * holder of all proprietary rights on this computer program. 4 | * You can only use this computer program if you have closed 5 | * a license agreement with MPG or you get the right to use the computer 6 | * program from someone who is authorized to grant you that right. 7 | * Any use of the computer program without a valid license is prohibited and 8 | * liable to prosecution. 9 | * 10 | * Copyright©2019 Max-Planck-Gesellschaft zur Förderung 11 | * der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute 12 | * for Intelligent Systems. All rights reserved. 13 | * 14 | * @author Vasileios Choutas 15 | * Contact: vassilis.choutas@tuebingen.mpg.de 16 | * Contact: ps-license@tuebingen.mpg.de 17 | * 18 | */ 19 | 20 | 21 | #ifndef DOUBLE_VEC_OPS_H 22 | #define DOUBLE_VEC_OPS_H 23 | 24 | #include "cuda_runtime.h" 25 | 26 | inline __host__ __device__ double2 operator+(double2 a, double2 b) { 27 | return make_double2(a.x + b.x, a.y + b.y); 28 | } 29 | 30 | 31 | inline __host__ __device__ double3 operator+(double3 a, double3 b) { 32 | return make_double3(a.x + b.x, a.y + b.y, a.z + b.z); 33 | } 34 | 35 | inline __host__ __device__ void operator/=(double2 &a, double2 b) { 36 | a.x /= b.x; 37 | a.y /= b.y; 38 | } 39 | 40 | inline __host__ __device__ double2 operator/(double2 a, double b) { 41 | return make_double2(a.x / b, a.y / b); 42 | } 43 | 44 | inline __host__ __device__ double3 operator/(double3 a, double3 b) { 45 | return make_double3(a.x / b.x, a.y / b.y, a.z / b.z); 46 | } 47 | 48 | 49 | inline __host__ __device__ double3 operator*(double a, double3 b) { 50 | return make_double3(a * b.x, a * b.y, a * b.z); 51 | } 52 | 53 | inline __host__ __device__ double3 operator*(double3 a, double3 b) { 54 | return make_double3(a.x * b.x, a.y * b.y, a.z * b.z); 55 | } 56 | 57 | inline __host__ __device__ void operator/=(double3 &a, double3 b) { 58 | a.x /= b.x; 59 | a.y /= b.y; 60 | a.z /= b.z; 61 | } 62 | 63 | inline __host__ __device__ double3 operator/(double3 a, double b) { 64 | return make_double3(a.x / b, a.y / b, a.z / b); 65 | } 66 | 67 | inline __host__ __device__ double dot(double2 a, double2 b) { 68 | return a.x * b.x + a.y * b.y; 69 | } 70 | 71 | inline __host__ __device__ double dot(double3 a, double3 b) { 72 | return a.x * b.x + a.y * b.y + a.z * b.z; 73 | } 74 | 75 | inline __host__ __device__ double3 cross(double3 a, double3 b) 76 | { 77 | return make_double3(a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x); 78 | } 79 | 80 | inline __host__ __device__ double2 operator-(double2 a, double2 b) 81 | { 82 | return make_double2(a.x - b.x, a.y - b.y); 83 | } 84 | inline __host__ __device__ void operator-=(double2 &a, double2 b) 85 | { 86 | a.x -= b.x; 87 | a.y -= b.y; 88 | } 89 | inline __host__ __device__ double2 operator-(double2 a, double b) 90 | { 91 | return make_double2(a.x - b, a.y - b); 92 | } 93 | inline __host__ __device__ double2 operator-(double b, double2 a) 94 | { 95 | return make_double2(b - a.x, b - a.y); 96 | } 97 | 98 | inline __host__ __device__ double3 operator-(double3 a, double3 b) 99 | { 100 | return make_double3(a.x - b.x, a.y - b.y, a.z - b.z); 101 | } 102 | inline __host__ __device__ void operator-=(double3 &a, double3 b) 103 | { 104 | a.x -= b.x; 105 | a.y -= b.y; 106 | a.z -= b.z; 107 | } 108 | inline __host__ __device__ double3 operator-(double3 a, double b) 109 | { 110 | return make_double3(a.x - b, a.y - b, a.z - b); 111 | } 112 | inline __host__ __device__ double3 operator-(double b, double3 a) 113 | { 114 | return make_double3(b - a.x, b - a.y, b - a.z); 115 | } 116 | 117 | #endif // ifndef DOUBLE_VEC_OPS_H 118 | -------------------------------------------------------------------------------- /bvh-distance-queries/src/math_utils.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is 3 | * holder of all proprietary rights on this computer program. 4 | * You can only use this computer program if you have closed 5 | * a license agreement with MPG or you get the right to use the computer 6 | * program from someone who is authorized to grant you that right. 7 | * Any use of the computer program without a valid license is prohibited and 8 | * liable to prosecution. 9 | * 10 | * Copyright©2019 Max-Planck-Gesellschaft zur Förderung 11 | * der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute 12 | * for Intelligent Systems. All rights reserved. 13 | * 14 | * @author Vasileios Choutas 15 | * Contact: vassilis.choutas@tuebingen.mpg.de 16 | * Contact: ps-license@tuebingen.mpg.de 17 | * 18 | */ 19 | 20 | #ifndef MATH_UTILS_H 21 | #define MATH_UTILS_H 22 | 23 | #include 24 | #include "device_launch_parameters.h" 25 | #include 26 | 27 | #include "defs.hpp" 28 | #include "double_vec_ops.h" 29 | #include "helper_math.h" 30 | 31 | 32 | template 33 | __host__ __device__ T sign(T x) { 34 | return x > 0 ? 1 : (x < 0 ? -1 : 0); 35 | } 36 | 37 | 38 | template 39 | __host__ __device__ __forceinline__ float vec_abs_diff(const vec3 &vec1, 40 | const vec3 &vec2) { 41 | return fabs(vec1.x - vec2.x) + fabs(vec1.y - vec2.y) + fabs(vec1.z - vec2.z); 42 | } 43 | 44 | template 45 | __host__ __device__ __forceinline__ float vec_sq_diff(const vec3 &vec1, 46 | const vec3 &vec2) { 47 | return dot(vec1 - vec2, vec1 - vec2); 48 | } 49 | 50 | template 51 | __host__ __device__ __forceinline__ T clamp(T value, T min_value, T max_value) { 52 | return min(max(value, min_value), max_value); 53 | } 54 | 55 | template __host__ __device__ T dot2(vec3 v) { 56 | return dot(v, v); 57 | } 58 | #endif // ifndef MATH_UTILS_H 59 | -------------------------------------------------------------------------------- /bvh-distance-queries/src/priority_queue.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is 3 | * holder of all proprietary rights on this computer program. 4 | * You can only use this computer program if you have closed 5 | * a license agreement with MPG or you get the right to use the computer 6 | * program from someone who is authorized to grant you that right. 7 | * Any use of the computer program without a valid license is prohibited and 8 | * liable to prosecution. 9 | * 10 | * Copyright©2019 Max-Planck-Gesellschaft zur Förderung 11 | * der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute 12 | * for Intelligent Systems. All rights reserved. 13 | * 14 | * @author Vasileios Choutas 15 | * Contact: vassilis.choutas@tuebingen.mpg.de 16 | * Contact: ps-license@tuebingen.mpg.de 17 | * 18 | */ 19 | 20 | #ifndef PRIORITY_QUEUE_H 21 | #define PRIORITY_QUEUE_H 22 | 23 | #include 24 | #include 25 | #include 26 | 27 | #include 28 | #include "device_launch_parameters.h" 29 | #include 30 | 31 | template 32 | __host__ __device__ 33 | void swap_array_els(T* array, int i, int j) { 34 | T tmp = array[i]; 35 | array[i] = array[j]; 36 | array[j] = tmp; 37 | } 38 | 39 | template 40 | class PriorityQueue { 41 | public: 42 | __host__ __device__ 43 | PriorityQueue() : heap_size(0) {} 44 | 45 | inline 46 | __host__ __device__ 47 | int get_size() { 48 | return heap_size; 49 | } 50 | 51 | inline 52 | __host__ __device__ 53 | int parent(int i) { 54 | return (i - 1) / 2; 55 | } 56 | 57 | inline 58 | __host__ __device__ 59 | int left_child(int i) { 60 | return 2 * i + 1; 61 | } 62 | 63 | inline 64 | __host__ __device__ 65 | int right_child(int i) { 66 | return 2 * i + 2; 67 | } 68 | 69 | __host__ __device__ 70 | std::pair get_min() { 71 | if (heap_size > 0) { 72 | return std::pair(priority_heap[0], obj_heap[0]); 73 | } 74 | else { 75 | return std::pair( 76 | std::is_same::value ? FLT_MAX : DBL_MAX, nullptr); 77 | } 78 | } 79 | 80 | __host__ __device__ 81 | void min_heapify(int index) { 82 | if (recursive) { 83 | int left = left_child(index); 84 | int right = right_child(index); 85 | int smallest = index; 86 | if (left < heap_size && priority_heap[left] < priority_heap[index]) 87 | smallest = left; 88 | if (right < heap_size && priority_heap[right] < priority_heap[index]) 89 | smallest = right; 90 | if (smallest != index) { 91 | swap_array_els(priority_heap, index, smallest); 92 | swap_array_els(obj_heap, index, smallest); 93 | min_heapify(smallest); 94 | } 95 | } else { 96 | int ii = index; 97 | int smallest; 98 | while (true) { 99 | int left = left_child(ii); 100 | int right = right_child(ii); 101 | smallest = ii; 102 | 103 | if (left < heap_size && priority_heap[left] < priority_heap[ii]) 104 | smallest = left; 105 | if (right < heap_size && priority_heap[right] < priority_heap[ii]) 106 | smallest = right; 107 | 108 | if (smallest != ii) { 109 | swap_array_els(priority_heap, ii, smallest); 110 | swap_array_els(obj_heap, ii, smallest); 111 | ii = smallest; 112 | } 113 | else 114 | break; 115 | } 116 | } 117 | } 118 | 119 | __host__ __device__ 120 | void insert_key(T key, Obj obj) { 121 | if (heap_size == QueueSize) { 122 | printf("The queue has exceed its maximum size\n"); 123 | return; 124 | } 125 | heap_size++; 126 | int ii = heap_size - 1; 127 | priority_heap[ii] = key; 128 | obj_heap[ii] = obj; 129 | 130 | // Fix the min heap property if it is violated 131 | min_heapify(0); 132 | // while (ii != 0 && priority_heap[parent(ii)] > priority_heap[ii]) { 133 | // swap_array_els(priority_heap, ii, parent(ii)); 134 | // swap_array_els(obj_heap, ii, parent(ii)); 135 | // ii = parent(ii); 136 | // } 137 | } 138 | 139 | // void print() { 140 | // for (int i = 0; i < heap_size; i++) { 141 | // std::cout << i << ": " << heap[i] << std::endl; 142 | // } 143 | // } 144 | 145 | __host__ __device__ 146 | std::pair extract() { 147 | if (heap_size <= 0) 148 | return std::pair( 149 | std::is_same::value ? FLT_MAX : DBL_MAX, nullptr); 150 | 151 | T root_prio = priority_heap[0]; 152 | Obj root_obj = obj_heap[0]; 153 | // Replace the root with the last element 154 | priority_heap[0] = priority_heap[heap_size - 1]; 155 | obj_heap[0] = obj_heap[heap_size - 1]; 156 | // Decrease the size of the heap 157 | heap_size--; 158 | 159 | min_heapify(0); 160 | return std::pair(root_prio, root_obj); 161 | } 162 | 163 | private: 164 | T priority_heap[QueueSize]; 165 | Obj obj_heap[QueueSize]; 166 | int heap_size; 167 | }; 168 | 169 | #endif // #ifndef PRIORITY_QUEUE_H 170 | -------------------------------------------------------------------------------- /bvh-distance-queries/src/triangle.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is 3 | * holder of all proprietary rights on this computer program. 4 | * You can only use this computer program if you have closed 5 | * a license agreement with MPG or you get the right to use the computer 6 | * program from someone who is authorized to grant you that right. 7 | * Any use of the computer program without a valid license is prohibited and 8 | * liable to prosecution. 9 | * 10 | * Copyright©2019 Max-Planck-Gesellschaft zur Förderung 11 | * der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute 12 | * for Intelligent Systems. All rights reserved. 13 | * 14 | * @author Vasileios Choutas 15 | * Contact: vassilis.choutas@tuebingen.mpg.de 16 | * Contact: ps-license@tuebingen.mpg.de 17 | * 18 | */ 19 | 20 | #ifndef TRIANGLE_H 21 | #define TRIANGLE_H 22 | 23 | #include "defs.hpp" 24 | #include "double_vec_ops.h" 25 | #include "helper_math.h" 26 | 27 | #include "math_utils.hpp" 28 | #include 29 | #include 30 | #include 31 | 32 | template 33 | __align__(48) 34 | struct Triangle { 35 | public: 36 | vec3 v0; 37 | vec3 v1; 38 | vec3 v2; 39 | 40 | __host__ __device__ Triangle() {} 41 | __host__ __device__ Triangle(vec3 vertex0, vec3 vertex1, 42 | vec3 vertex2) 43 | : v0(vertex0), v1(vertex1), v2(vertex2){}; 44 | __host__ __device__ Triangle(const vec3 &vertex0, const vec3 &vertex1, 45 | const vec3 &vertex2) 46 | : v0(vertex0), v1(vertex1), v2(vertex2){}; 47 | 48 | __host__ __device__ AABB ComputeBBox() { 49 | return AABB(min(v0.x, min(v1.x, v2.x)), min(v0.y, min(v1.y, v2.y)), 50 | min(v0.z, min(v1.z, v2.z)), max(v0.x, max(v1.x, v2.x)), 51 | max(v0.y, max(v1.y, v2.y)), max(v0.z, max(v1.z, v2.z))); 52 | } 53 | }; 54 | 55 | template using TrianglePtr = Triangle *; 56 | 57 | template 58 | std::ostream &operator<<(std::ostream &os, const Triangle &x) { 59 | os << x.v0 << std::endl; 60 | os << x.v1 << std::endl; 61 | os << x.v2 << std::endl; 62 | return os; 63 | } 64 | 65 | 66 | #endif // TRIANGLE_H 67 | -------------------------------------------------------------------------------- /dataprocessing/eval_points_speeds.py: -------------------------------------------------------------------------------- 1 | import trimesh 2 | import numpy as np 3 | import torch 4 | import bvh_distance_queries 5 | import igl 6 | 7 | 8 | def point_obstacle_distance(query_points, triangles_obs): 9 | query_points = query_points.unsqueeze(dim=0) 10 | #print(query_points.shape) 11 | bvh = bvh_distance_queries.BVH() 12 | torch.cuda.synchronize() 13 | torch.cuda.synchronize() 14 | distances, closest_points, closest_faces, closest_bcs= bvh(triangles_obs, query_points) 15 | torch.cuda.synchronize() 16 | unsigned_distance = torch.sqrt(distances).squeeze() 17 | #print(closest_points.shape) 18 | return unsigned_distance 19 | 20 | def point_append_list(X_list,Y_list, 21 | triangles_obs, numsamples, dim, offset, margin): 22 | 23 | OutsideSize = numsamples + 2 24 | WholeSize = 0 25 | 26 | while OutsideSize > 0: 27 | P = torch.rand((8*numsamples,dim),dtype=torch.float32, device='cuda')-0.5 28 | dP = torch.rand((8*numsamples,dim),dtype=torch.float32, device='cuda')-0.5 29 | rL = (torch.rand((8*numsamples,1),dtype=torch.float32, device='cuda'))*np.sqrt(dim) 30 | nP = P + torch.nn.functional.normalize(dP,dim=1)*rL 31 | #nP = torch.rand((8*numsamples,dim),dtype=torch.float32, device='cuda')-0.5 32 | 33 | PointsInside = torch.all((nP <= 0.5),dim=1) & torch.all((nP >= -0.5),dim=1) 34 | 35 | 36 | x0 = P[PointsInside,:] 37 | x1 = nP[PointsInside,:] 38 | 39 | #print(x0.shape[0]) 40 | if(x0.shape[0]<=1): 41 | continue 42 | #print(len(PointsOutside)) 43 | 44 | 45 | obs_distance0 = point_obstacle_distance(x0, triangles_obs) 46 | where_d = (obs_distance0 > offset) & (obs_distance0 < margin) 47 | x0 = x0[where_d] 48 | x1 = x1[where_d] 49 | y0 = obs_distance0[where_d] 50 | 51 | obs_distance1 = point_obstacle_distance(x1, triangles_obs) 52 | 53 | y1 = obs_distance1 54 | 55 | print(x0.shape) 56 | #print(x1.shape) 57 | #print(y0.shape) 58 | #print(y1.shape) 59 | 60 | x = torch.cat((x0,x1),1) 61 | y = torch.cat((y0.unsqueeze(1),y1.unsqueeze(1)),1) 62 | 63 | X_list.append(x) 64 | Y_list.append(y) 65 | 66 | OutsideSize = OutsideSize - x.shape[0] 67 | WholeSize = WholeSize + x.shape[0] 68 | 69 | if(WholeSize > numsamples): 70 | break 71 | return X_list, Y_list 72 | 73 | def sample_points_and_speeds(meshpath, numsamples, dim, minimum, maximum): 74 | offset = minimum 75 | margin = maximum 76 | v_obs, f_obs = igl.read_triangle_mesh(meshpath) 77 | v_obs = torch.tensor(v_obs, dtype=torch.float32, device='cuda') 78 | f_obs = torch.tensor(f_obs, dtype=torch.long, device='cuda') 79 | t_obs = v_obs[f_obs].unsqueeze(dim=0) 80 | 81 | X_list = [] 82 | Y_list = [] 83 | #N_list = [] 84 | 85 | X_list, Y_list = point_append_list(X_list,Y_list, t_obs, numsamples, dim, offset, margin) 86 | 87 | X = torch.cat(X_list,0)[:numsamples] 88 | Y = torch.cat(Y_list,0)[:numsamples] 89 | 90 | sampled_points = X.detach().cpu().numpy() 91 | distance = Y.detach().cpu().numpy() 92 | #normal = N.detach().cpu().numpy() 93 | 94 | distance0 = distance[:,0] 95 | distance1 = distance[:,1] 96 | speed = np.zeros((distance.shape[0],2)) 97 | speed[:,0] = np.clip(distance0 , a_min = offset, a_max = margin)/margin 98 | speed[:,1] = np.clip(distance1 , a_min = offset, a_max = margin)/margin 99 | 100 | if False: 101 | # visualize(meshpath, sampled_points[:, :3], speed[:, 0]) 102 | visualize(meshpath, sampled_points[:, 3:6], speed[:, 1]) 103 | 104 | if True: 105 | np.save("sampled_points.npy", sampled_points) 106 | np.save("speed.npy", speed) 107 | 108 | 109 | 110 | 111 | 112 | def visualize(meshpath, points, speeds): 113 | mesh = trimesh.load(meshpath) 114 | 115 | # point cloud 116 | pc = trimesh.PointCloud(points) 117 | 118 | # colors 119 | colors = trimesh.visual.interpolate(speeds, 'viridis') 120 | pc.colors = colors 121 | 122 | # scene 123 | scene = trimesh.Scene([mesh, pc]) 124 | 125 | # show 126 | scene.show() 127 | 128 | if __name__ == '__main__': 129 | meshpath = "mesh_scaled_11_29_15.obj" 130 | 131 | if False: 132 | points = np.random.rand(100, 3) 133 | speeds = np.random.rand(100) 134 | 135 | points = np.load("sampled_points.npy")[:10000, :3] 136 | speeds = np.load("speed.npy")[:10000, 0] 137 | 138 | visualize(meshpath, points, speeds) 139 | 140 | if True: 141 | maximum = 0.05 142 | minimum = 0.005 143 | sample_points_and_speeds(meshpath, 500000, 3, minimum, maximum) 144 | -------------------------------------------------------------------------------- /eval.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import torch 3 | import bvh_distance_queries 4 | import igl 5 | 6 | from models import model_igibson as md 7 | import time 8 | 9 | def check_collision(query_points, triangles, scale=1): 10 | query_points /= scale 11 | query_points = torch.tensor(query_points, dtype=torch.float32, device='cuda') 12 | 13 | #! interpolate points 14 | new_query_points = [] 15 | interpolation_steps = 10 16 | for i in range(len(query_points) - 1): 17 | start_point = query_points[i] 18 | end_point = query_points[i+1] 19 | for t in range(interpolation_steps): 20 | alpha = t/interpolation_steps 21 | interpolated_point = (1-alpha)*start_point + alpha*end_point 22 | new_query_points.append(interpolated_point) 23 | new_query_points = torch.vstack(new_query_points) 24 | query_points = new_query_points 25 | 26 | query_points = query_points.unsqueeze(dim=0) 27 | #print(query_points.shape) 28 | bvh = bvh_distance_queries.BVH() 29 | torch.cuda.synchronize() 30 | torch.cuda.synchronize() 31 | distances, closest_points, closest_faces, closest_bcs= bvh(triangles, query_points) 32 | torch.cuda.synchronize() 33 | #unsigned_distance = abs() 34 | #print(distances.shape) 35 | unsigned_distance = torch.sqrt(distances).squeeze() 36 | unsigned_distance = unsigned_distance.detach().cpu().numpy() 37 | 38 | if np.min(unsigned_distance)<=0.001: 39 | return False 40 | else: 41 | return True 42 | 43 | def calculate_trajectory_lengths(trajectories): 44 | # This function calculates the length of each trajectory. 45 | # trajectories: a numpy array of shape (N, 64, 3) 46 | nt = trajectories.shape[0] 47 | lengths = np.zeros(nt) 48 | 49 | for i in range(nt): 50 | for j in range(1, trajectories.shape[1]): 51 | lengths[i] += np.linalg.norm(trajectories[i, j, :] - trajectories[i, j-1, :]) 52 | 53 | return lengths 54 | 55 | 56 | def our_method_eval(meshpath, modelPath, datapath): 57 | v, f = igl.read_triangle_mesh(meshpath) 58 | vertices=v 59 | faces=f 60 | 61 | vertices = torch.tensor(vertices, dtype=torch.float32, device='cuda') 62 | faces = torch.tensor(faces, dtype=torch.long, device='cuda') 63 | triangles = vertices[faces].unsqueeze(dim=0) 64 | 65 | 66 | # Load the data 67 | scale_factor = 10 68 | mode = 1 69 | renderer = None 70 | model = md.Model('./Experiments', 3, scale_factor, mode, renderer, device='cuda:0') 71 | model.load(modelPath) 72 | 73 | # write start and goal random samples 74 | explored_data = np.load(datapath, allow_pickle=True).reshape(-1, 8) 75 | potential_points = explored_data[:, 3:6] 76 | valid_mask = explored_data[:, 7] > 0.995 77 | valid_points = potential_points[valid_mask] 78 | N = 100 79 | rand_idx = np.random.choice(len(valid_points), 2*N) 80 | start_points = valid_points[rand_idx][:N] 81 | end_points = valid_points[rand_idx][N:] 82 | 83 | 84 | evalant_times = [] 85 | fail_trajs = [] 86 | succ_trajs = [] 87 | succ_lens = [] 88 | for i in range(N): 89 | src = start_points[i] 90 | tar = end_points[i] 91 | start_time = time.time() 92 | cur_trajectory = model.predict_trajectory(src, tar, step_size=0.03, tol=0.03) 93 | end_time = time.time() 94 | 95 | if check_collision(cur_trajectory, triangles): 96 | evalant_times.append(end_time - start_time) 97 | lengths = calculate_trajectory_lengths(cur_trajectory[None,]) 98 | succ_lens.append(lengths[0]) 99 | succ_trajs.append(cur_trajectory) 100 | else: 101 | fail_trajs.append(cur_trajectory) 102 | 103 | success_lens = np.array(succ_lens) 104 | success_rate = len(success_lens) / N 105 | evalant_times = np.array(evalant_times) 106 | 107 | print('Success rate: ', success_rate) 108 | print('Average time: ', np.mean(evalant_times)) 109 | print('Average trajectory length: ', np.mean(success_lens)) 110 | 111 | #! vis 112 | if False: 113 | import trimesh 114 | mesh = trimesh.load_mesh(meshpath) 115 | M = 5 116 | trajs = fail_trajs 117 | r = np.random.choice(len(trajs), M) 118 | for i in range(M): 119 | scene = trimesh.Scene(mesh) 120 | pc = trimesh.PointCloud(trajs[r[i]]) 121 | scene.add_geometry([pc]) 122 | scene.show() 123 | 124 | # return trajectories, fail_trajs 125 | 126 | if __name__ == '__main__': 127 | random_seed = 0 128 | np.random.seed(random_seed) 129 | 130 | meshpath = './data/mesh.obj' 131 | modelpath = './Experiments/10_12_11_23/Model_Epoch_04650_ValLoss_2.591095e-02.pt' 132 | datapath = './data/explored_data.npy' 133 | 134 | our_method_eval(meshpath, modelpath, datapath) 135 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import argparse 3 | from models import model_igibson as md 4 | 5 | # Define modes 6 | EXPLORATION = 1 7 | READ_FROM_COOKED_DATA = 2 8 | 9 | 10 | # Define the model path 11 | scale_factor = 10 12 | modelPath = './Experiments' 13 | 14 | def main(): 15 | parser = argparse.ArgumentParser(description='Train the model with or without exploration.') 16 | parser.add_argument('--no_explore', action='store_true', help='Disable exploration mode.') 17 | 18 | args = parser.parse_args() 19 | 20 | # Set the mode based on the --no_explore flag 21 | if args.no_explore: 22 | mode = READ_FROM_COOKED_DATA 23 | else: 24 | mode = EXPLORATION # Default to exploration mode 25 | 26 | renderer = None 27 | if mode in [EXPLORATION]: 28 | from igibson.render.mesh_renderer.mesh_renderer_cpu import MeshRenderer 29 | meshpath = "data/mesh.obj" 30 | 31 | renderer = MeshRenderer(width=1200, height=680) 32 | renderer.load_object(meshpath, scale=np.array([1, 1, 1]) * scale_factor) 33 | renderer.add_instance_group([0]) 34 | camera_pose = np.array([0, 0, 1]) 35 | view_direction = np.array([1, 0, 0]) 36 | renderer.set_camera(camera_pose, camera_pose + view_direction, [0, 0, 0]) 37 | renderer.set_fov(90) 38 | 39 | # Initialize and train the model 40 | model = md.Model(modelPath, 3, scale_factor, mode, renderer, device='cuda:0') 41 | model.train() 42 | 43 | if __name__ == '__main__': 44 | main() 45 | --------------------------------------------------------------------------------