thewhole commited on
Commit
2fa4776
1 Parent(s): 3c558e1

Upload 245 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .editorconfig +15 -0
  2. .gitattributes +5 -0
  3. .gitignore +191 -0
  4. .pre-commit-config.yaml +34 -0
  5. .pylintrc +7 -0
  6. app.py +57 -0
  7. configs/gaussiandreamer-sd.yaml +64 -0
  8. example/Viking_axe,_fantasy,_weapon,_blender,_8k,_HD.mp4 +0 -0
  9. example/a_fox.mp4 +0 -0
  10. example/ferrari_convertible,_trending_on_artstation,_ultra_realistic,_4k,_HD.mp4 +0 -0
  11. example/flamethrower,_with_fire,_scifi,_cyberpunk,_photorealistic,_8K,_HD.mp4 +0 -0
  12. example/fries_and_a_hamburger.mp4 +0 -0
  13. gaussiansplatting/.gitignore +8 -0
  14. gaussiansplatting/.gitmodules +9 -0
  15. gaussiansplatting/LICENSE.md +83 -0
  16. gaussiansplatting/README.md +488 -0
  17. gaussiansplatting/arguments/__init__.py +111 -0
  18. gaussiansplatting/assets/better.png +0 -0
  19. gaussiansplatting/assets/logo_graphdeco.png +0 -0
  20. gaussiansplatting/assets/logo_inria.png +0 -0
  21. gaussiansplatting/assets/logo_mpi.png +0 -0
  22. gaussiansplatting/assets/logo_mpi.svg +488 -0
  23. gaussiansplatting/assets/logo_uca.png +0 -0
  24. gaussiansplatting/assets/select.png +0 -0
  25. gaussiansplatting/assets/teaser.png +0 -0
  26. gaussiansplatting/assets/worse.png +0 -0
  27. gaussiansplatting/convert.py +124 -0
  28. gaussiansplatting/environment.yml +17 -0
  29. gaussiansplatting/full_eval.py +75 -0
  30. gaussiansplatting/gaussian_renderer/__init__.py +101 -0
  31. gaussiansplatting/gaussian_renderer/network_gui.py +86 -0
  32. gaussiansplatting/lpipsPyTorch/__init__.py +21 -0
  33. gaussiansplatting/lpipsPyTorch/modules/lpips.py +36 -0
  34. gaussiansplatting/lpipsPyTorch/modules/networks.py +96 -0
  35. gaussiansplatting/lpipsPyTorch/modules/utils.py +30 -0
  36. gaussiansplatting/metrics.py +103 -0
  37. gaussiansplatting/render.py +66 -0
  38. gaussiansplatting/scene/__init__.py +93 -0
  39. gaussiansplatting/scene/cameras.py +68 -0
  40. gaussiansplatting/scene/colmap_loader.py +282 -0
  41. gaussiansplatting/scene/dataset_readers.py +255 -0
  42. gaussiansplatting/scene/gaussian_model.py +419 -0
  43. gaussiansplatting/submodules/diff-gaussian-rasterization/.gitignore +3 -0
  44. gaussiansplatting/submodules/diff-gaussian-rasterization/.gitmodules +3 -0
  45. gaussiansplatting/submodules/diff-gaussian-rasterization/CMakeLists.txt +36 -0
  46. gaussiansplatting/submodules/diff-gaussian-rasterization/LICENSE.md +83 -0
  47. gaussiansplatting/submodules/diff-gaussian-rasterization/README.md +24 -0
  48. gaussiansplatting/submodules/diff-gaussian-rasterization/cuda_rasterizer/auxiliary.h +175 -0
  49. gaussiansplatting/submodules/diff-gaussian-rasterization/cuda_rasterizer/backward.cu +657 -0
  50. gaussiansplatting/submodules/diff-gaussian-rasterization/cuda_rasterizer/backward.h +65 -0
.editorconfig ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ root = true
2
+
3
+ [*.py]
4
+ charset = utf-8
5
+ trim_trailing_whitespace = true
6
+ end_of_line = lf
7
+ insert_final_newline = true
8
+ indent_style = space
9
+ indent_size = 4
10
+
11
+ [*.md]
12
+ trim_trailing_whitespace = false
13
+
14
+ [*.yaml]
15
+ indent_size = 2
.gitattributes CHANGED
@@ -33,3 +33,8 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ images/output_ax.gif filter=lfs diff=lfs merge=lfs -text
37
+ images/output_gs.gif filter=lfs diff=lfs merge=lfs -text
38
+ images/title.gif filter=lfs diff=lfs merge=lfs -text
39
+ images/unity.gif filter=lfs diff=lfs merge=lfs -text
40
+ load/lights/mud_road_puresky_1k.hdr filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Created by https://www.toptal.com/developers/gitignore/api/python
2
+ # Edit at https://www.toptal.com/developers/gitignore?templates=python
3
+
4
+ ### Python ###
5
+ # Byte-compiled / optimized / DLL files
6
+ __pycache__/
7
+ *.py[cod]
8
+ *$py.class
9
+
10
+ # C extensions
11
+ *.so
12
+
13
+ # Distribution / packaging
14
+ .Python
15
+ build/
16
+ develop-eggs/
17
+ dist/
18
+ downloads/
19
+ eggs/
20
+ .eggs/
21
+ lib/
22
+ lib64/
23
+ parts/
24
+ sdist/
25
+ var/
26
+ wheels/
27
+ share/python-wheels/
28
+ *.egg-info/
29
+ .installed.cfg
30
+ *.egg
31
+ MANIFEST
32
+
33
+ # PyInstaller
34
+ # Usually these files are written by a python script from a template
35
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
36
+ *.manifest
37
+ *.spec
38
+
39
+ # Installer logs
40
+ pip-log.txt
41
+ pip-delete-this-directory.txt
42
+
43
+ # Unit test / coverage reports
44
+ htmlcov/
45
+ .tox/
46
+ .nox/
47
+ .coverage
48
+ .coverage.*
49
+ .cache
50
+ nosetests.xml
51
+ coverage.xml
52
+ *.cover
53
+ *.py,cover
54
+ .hypothesis/
55
+ .pytest_cache/
56
+ cover/
57
+
58
+ # Translations
59
+ *.mo
60
+ *.pot
61
+
62
+ # Django stuff:
63
+ *.log
64
+ local_settings.py
65
+ db.sqlite3
66
+ db.sqlite3-journal
67
+
68
+ # Flask stuff:
69
+ instance/
70
+ .webassets-cache
71
+
72
+ # Scrapy stuff:
73
+ .scrapy
74
+
75
+ # Sphinx documentation
76
+ docs/_build/
77
+
78
+ # PyBuilder
79
+ .pybuilder/
80
+ target/
81
+
82
+ # Jupyter Notebook
83
+ .ipynb_checkpoints
84
+
85
+ # IPython
86
+ profile_default/
87
+ ipython_config.py
88
+
89
+ # pyenv
90
+ # For a library or package, you might want to ignore these files since the code is
91
+ # intended to run in multiple environments; otherwise, check them in:
92
+ # .python-version
93
+
94
+ # pipenv
95
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
96
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
97
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
98
+ # install all needed dependencies.
99
+ #Pipfile.lock
100
+
101
+ # poetry
102
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
103
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
104
+ # commonly ignored for libraries.
105
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
106
+ #poetry.lock
107
+
108
+ # pdm
109
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
110
+ #pdm.lock
111
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
112
+ # in version control.
113
+ # https://pdm.fming.dev/#use-with-ide
114
+ .pdm.toml
115
+
116
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
117
+ __pypackages__/
118
+
119
+ # Celery stuff
120
+ celerybeat-schedule
121
+ celerybeat.pid
122
+
123
+ # SageMath parsed files
124
+ *.sage.py
125
+
126
+ # Environments
127
+ .env
128
+ .venv
129
+ env/
130
+ venv/
131
+ ENV/
132
+ env.bak/
133
+ venv.bak/
134
+
135
+ # Spyder project settings
136
+ .spyderproject
137
+ .spyproject
138
+
139
+ # Rope project settings
140
+ .ropeproject
141
+
142
+ # mkdocs documentation
143
+ /site
144
+
145
+ # mypy
146
+ .mypy_cache/
147
+ .dmypy.json
148
+ dmypy.json
149
+
150
+ # Pyre type checker
151
+ .pyre/
152
+
153
+ # pytype static type analyzer
154
+ .pytype/
155
+
156
+ # Cython debug symbols
157
+ cython_debug/
158
+
159
+ # PyCharm
160
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
161
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
162
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
163
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
164
+ #.idea/
165
+
166
+ ### Python Patch ###
167
+ # Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
168
+ poetry.toml
169
+
170
+ # ruff
171
+ .ruff_cache/
172
+
173
+ # LSP config files
174
+ pyrightconfig.json
175
+
176
+ # End of https://www.toptal.com/developers/gitignore/api/python
177
+
178
+ .vscode/
179
+ .threestudio_cache/
180
+ outputs/
181
+ outputs-gradio/
182
+
183
+ # pretrained model weights
184
+ *.ckpt
185
+ *.pt
186
+ *.pth
187
+
188
+ # wandb
189
+ wandb/
190
+ outputs/
191
+ load/
.pre-commit-config.yaml ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ default_language_version:
2
+ python: python3
3
+
4
+ repos:
5
+ - repo: https://github.com/pre-commit/pre-commit-hooks
6
+ rev: v4.4.0
7
+ hooks:
8
+ - id: trailing-whitespace
9
+ - id: check-ast
10
+ - id: check-merge-conflict
11
+ - id: check-yaml
12
+ - id: end-of-file-fixer
13
+ - id: trailing-whitespace
14
+ args: [--markdown-linebreak-ext=md]
15
+
16
+ - repo: https://github.com/psf/black
17
+ rev: 23.3.0
18
+ hooks:
19
+ - id: black
20
+ language_version: python3.8
21
+
22
+ - repo: https://github.com/pycqa/isort
23
+ rev: 5.12.0
24
+ hooks:
25
+ - id: isort
26
+ exclude: README.md
27
+ args: ["--profile", "black"]
28
+
29
+ # temporarily disable static type checking
30
+ # - repo: https://github.com/pre-commit/mirrors-mypy
31
+ # rev: v1.2.0
32
+ # hooks:
33
+ # - id: mypy
34
+ # args: ["--ignore-missing-imports", "--scripts-are-modules", "--pretty"]
.pylintrc ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ disable=R,C
2
+
3
+ [TYPECHECK]
4
+ # List of members which are set dynamically and missed by pylint inference
5
+ # system, and so shouldn't trigger E1101 when accessed. Python regular
6
+ # expressions are accepted.
7
+ generated-members=numpy.*,torch.*,cv2.*
app.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import os
4
+ import subprocess
5
+ from datetime import datetime
6
+
7
+ os.system('pip install ./gaussiansplatting/submodules/diff-gaussian-rasterization')
8
+ os.system('pip install ./gaussiansplatting/submodules/simple-knn')
9
+
10
+ example_inputs = [[
11
+ "A fox."
12
+ ], [
13
+ "fries and a hamburger."
14
+ ], [
15
+ "Viking axe, fantasy, weapon, blender, 8k, HD."
16
+ ], [
17
+ "ferrari convertible, trending on artstation, ultra realistic, 4k, HD"
18
+ ], [
19
+ "flamethrower, with fire, scifi, cyberpunk, photorealistic, 8K, HD"
20
+ ]]
21
+ example_outputs_1 = [
22
+ gr.Video(value=os.path.join(os.path.dirname(__file__), 'example/a_fox.mp4'), autoplay=True),
23
+ gr.Video(value=os.path.join(os.path.dirname(__file__), 'example/fries_and_a_hamburger.mp4'), autoplay=True),
24
+ gr.Video(value=os.path.join(os.path.dirname(__file__), 'example/Viking_axe,_fantasy,_weapon,_blender,_8k,_HD.mp4'), autoplay=True),
25
+ gr.Video(value=os.path.join(os.path.dirname(__file__), 'example/ferrari_convertible,_trending_on_artstation,_ultra_realistic,_4k,_HD.mp4'), autoplay=True),
26
+ gr.Video(value=os.path.join(os.path.dirname(__file__), 'example/flamethrower,_with_fire,_scifi,_cyberpunk,_photorealistic,_8K,_HD.mp4'), autoplay=True)
27
+ ]
28
+
29
+
30
+
31
+ def main(prompt, CFG, seed):
32
+ if [prompt] in example_inputs:
33
+ return example_outputs_1[example_inputs.index([prompt])]
34
+ seed = int(seed)
35
+ print('==> User Prompt:', prompt)
36
+ timestamp = datetime.now().strftime("@%Y%m%d-%H%M%S")
37
+ subprocess.run([
38
+ f'python launch.py --config configs/gaussiandreamer-sd.yaml --train --gpu 0 system.prompt_processor.prompt="{prompt}" seed={seed} system.guidance.guidance_scale={CFG} use_timestamp=False timestamp="{timestamp}" '],
39
+ shell=True)
40
+ path= os.path.join("./outputs/gaussiandreamer-sd",f'{prompt.replace(" ","_")}{timestamp}',"save/it1200-test.mp4")
41
+ print('==> Save path:', path)
42
+ return gr.Video(value=path, autoplay=True)
43
+
44
+ with gr.Blocks() as demo:
45
+ gr.Markdown("# <center>LucidDreamer: Towards High-Fidelity Text-to-3D Generation via Interval Score Matching</center>")
46
+ gr.Markdown("This live demo allows you to generate high-quality 3D content using text prompts. The outputs are 360° rendered 3d gaussian video and training progress visualization.<br> \
47
+ It is based on Stable Diffusion 2.1. Please check out our <strong><a href=https://github.com/EnVision-Research/LucidDreamer>Project Page</a> / <a href=https://arxiv.org/abs/2311.11284>Paper</a> / <a href=https://github.com/EnVision-Research/LucidDreamer>Code</a></strong> if you want to learn more about our method!<br> \
48
+ Note that this demo is running on A10G, the running time might be longer than the reported 35 minutes (5000 iterations) on A100.<br> \
49
+ &copy; This Gradio space was developed by Haodong LI.")
50
+ gr.Interface(fn=main, inputs=[gr.Textbox(lines=2, value="A portrait of IRONMAN, white hair, head, photorealistic, 8K, HDR.", label="Your prompt"),
51
+ gr.Slider(80, 200, value=100, label="CFG"),
52
+ gr.Number(value=0, label="Seed")],
53
+ outputs=["playable_video"],
54
+ examples=example_inputs,
55
+ cache_examples=True,
56
+ concurrency_limit=1)
57
+ demo.launch()
configs/gaussiandreamer-sd.yaml ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: "gaussiandreamer-sd"
2
+ tag: "${rmspace:${system.prompt_processor.prompt},_}"
3
+ exp_root_dir: "outputs"
4
+ seed: 0
5
+
6
+ data_type: "random-camera-datamodule"
7
+ data:
8
+ batch_size: 4
9
+ eval_camera_distance: 4.0
10
+ camera_distance_range: [1.5, 4.0]
11
+ light_sample_strategy: "dreamfusion3dgs"
12
+ height: 1024
13
+ width: 1024
14
+ eval_height: 1024
15
+ eval_width: 1024
16
+ # elevation_range: [-10 , 80]
17
+ system_type: "gaussiandreamer-system"
18
+ system:
19
+ radius: ${data.eval_camera_distance}
20
+ sh_degree: 0
21
+ prompt_processor_type: "stable-diffusion-prompt-processor"
22
+ prompt_processor:
23
+ pretrained_model_name_or_path: "stabilityai/stable-diffusion-2-1-base"
24
+ prompt: ???
25
+ negative_prompt: "ugly, bad anatomy, blurry, pixelated obscure, unnatural colors, poor lighting, dull, and unclear, cropped, lowres, low quality, artifacts, duplicate, morbid, mutilated, poorly drawn face, deformed, dehydrated, bad proportions, unfocused"
26
+
27
+ guidance_type: "stable-diffusion-guidance"
28
+ guidance:
29
+ pretrained_model_name_or_path: "stabilityai/stable-diffusion-2-1-base"
30
+ guidance_scale: 100.
31
+ weighting_strategy: sds
32
+ min_step_percent: 0.02
33
+ max_step_percent: 0.98
34
+ grad_clip: [0,1.5,2.0,1000]
35
+
36
+ loggers:
37
+ wandb:
38
+ enable: false
39
+ project: 'threestudio'
40
+ name: None
41
+
42
+ loss:
43
+ lambda_sds: 1.
44
+ lambda_sparsity: 1.
45
+ lambda_opaque: 0.0
46
+ optimizer:
47
+ name: Adam
48
+ args:
49
+ lr: 0.001
50
+ betas: [0.9, 0.99]
51
+ eps: 1.e-15
52
+
53
+ trainer:
54
+ max_steps: 1200
55
+ log_every_n_steps: 1
56
+ num_sanity_val_steps: 0
57
+ val_check_interval: 100
58
+ enable_progress_bar: true
59
+ precision: 16-mixed
60
+
61
+ checkpoint:
62
+ save_last: true # save at each validation time
63
+ save_top_k: -1
64
+ every_n_train_steps: ${trainer.max_steps}
example/Viking_axe,_fantasy,_weapon,_blender,_8k,_HD.mp4 ADDED
Binary file (270 kB). View file
 
example/a_fox.mp4 ADDED
Binary file (312 kB). View file
 
example/ferrari_convertible,_trending_on_artstation,_ultra_realistic,_4k,_HD.mp4 ADDED
Binary file (328 kB). View file
 
example/flamethrower,_with_fire,_scifi,_cyberpunk,_photorealistic,_8K,_HD.mp4 ADDED
Binary file (234 kB). View file
 
example/fries_and_a_hamburger.mp4 ADDED
Binary file (527 kB). View file
 
gaussiansplatting/.gitignore ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ *.pyc
2
+ .vscode
3
+ output
4
+ build
5
+ diff_rasterization/diff_rast.egg-info
6
+ diff_rasterization/dist
7
+ tensorboard_3d
8
+ screenshots
gaussiansplatting/.gitmodules ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ [submodule "submodules/simple-knn"]
2
+ path = submodules/simple-knn
3
+ url = https://gitlab.inria.fr/bkerbl/simple-knn.git
4
+ [submodule "submodules/diff-gaussian-rasterization"]
5
+ path = submodules/diff-gaussian-rasterization
6
+ url = https://github.com/graphdeco-inria/diff-gaussian-rasterization
7
+ [submodule "SIBR_viewers"]
8
+ path = SIBR_viewers
9
+ url = https://gitlab.inria.fr/sibr/sibr_core
gaussiansplatting/LICENSE.md ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Gaussian-Splatting License
2
+ ===========================
3
+
4
+ **Inria** and **the Max Planck Institut for Informatik (MPII)** hold all the ownership rights on the *Software* named **gaussian-splatting**.
5
+ The *Software* is in the process of being registered with the Agence pour la Protection des
6
+ Programmes (APP).
7
+
8
+ The *Software* is still being developed by the *Licensor*.
9
+
10
+ *Licensor*'s goal is to allow the research community to use, test and evaluate
11
+ the *Software*.
12
+
13
+ ## 1. Definitions
14
+
15
+ *Licensee* means any person or entity that uses the *Software* and distributes
16
+ its *Work*.
17
+
18
+ *Licensor* means the owners of the *Software*, i.e Inria and MPII
19
+
20
+ *Software* means the original work of authorship made available under this
21
+ License ie gaussian-splatting.
22
+
23
+ *Work* means the *Software* and any additions to or derivative works of the
24
+ *Software* that are made available under this License.
25
+
26
+
27
+ ## 2. Purpose
28
+ This license is intended to define the rights granted to the *Licensee* by
29
+ Licensors under the *Software*.
30
+
31
+ ## 3. Rights granted
32
+
33
+ For the above reasons Licensors have decided to distribute the *Software*.
34
+ Licensors grant non-exclusive rights to use the *Software* for research purposes
35
+ to research users (both academic and industrial), free of charge, without right
36
+ to sublicense.. The *Software* may be used "non-commercially", i.e., for research
37
+ and/or evaluation purposes only.
38
+
39
+ Subject to the terms and conditions of this License, you are granted a
40
+ non-exclusive, royalty-free, license to reproduce, prepare derivative works of,
41
+ publicly display, publicly perform and distribute its *Work* and any resulting
42
+ derivative works in any form.
43
+
44
+ ## 4. Limitations
45
+
46
+ **4.1 Redistribution.** You may reproduce or distribute the *Work* only if (a) you do
47
+ so under this License, (b) you include a complete copy of this License with
48
+ your distribution, and (c) you retain without modification any copyright,
49
+ patent, trademark, or attribution notices that are present in the *Work*.
50
+
51
+ **4.2 Derivative Works.** You may specify that additional or different terms apply
52
+ to the use, reproduction, and distribution of your derivative works of the *Work*
53
+ ("Your Terms") only if (a) Your Terms provide that the use limitation in
54
+ Section 2 applies to your derivative works, and (b) you identify the specific
55
+ derivative works that are subject to Your Terms. Notwithstanding Your Terms,
56
+ this License (including the redistribution requirements in Section 3.1) will
57
+ continue to apply to the *Work* itself.
58
+
59
+ **4.3** Any other use without of prior consent of Licensors is prohibited. Research
60
+ users explicitly acknowledge having received from Licensors all information
61
+ allowing to appreciate the adequacy between of the *Software* and their needs and
62
+ to undertake all necessary precautions for its execution and use.
63
+
64
+ **4.4** The *Software* is provided both as a compiled library file and as source
65
+ code. In case of using the *Software* for a publication or other results obtained
66
+ through the use of the *Software*, users are strongly encouraged to cite the
67
+ corresponding publications as explained in the documentation of the *Software*.
68
+
69
+ ## 5. Disclaimer
70
+
71
+ THE USER CANNOT USE, EXPLOIT OR DISTRIBUTE THE *SOFTWARE* FOR COMMERCIAL PURPOSES
72
+ WITHOUT PRIOR AND EXPLICIT CONSENT OF LICENSORS. YOU MUST CONTACT INRIA FOR ANY
73
+ UNAUTHORIZED USE: stip-sophia.transfert@inria.fr . ANY SUCH ACTION WILL
74
+ CONSTITUTE A FORGERY. THIS *SOFTWARE* IS PROVIDED "AS IS" WITHOUT ANY WARRANTIES
75
+ OF ANY NATURE AND ANY EXPRESS OR IMPLIED WARRANTIES, WITH REGARDS TO COMMERCIAL
76
+ USE, PROFESSIONNAL USE, LEGAL OR NOT, OR OTHER, OR COMMERCIALISATION OR
77
+ ADAPTATION. UNLESS EXPLICITLY PROVIDED BY LAW, IN NO EVENT, SHALL INRIA OR THE
78
+ AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
79
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
80
+ GOODS OR SERVICES, LOSS OF USE, DATA, OR PROFITS OR BUSINESS INTERRUPTION)
81
+ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
82
+ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING FROM, OUT OF OR
83
+ IN CONNECTION WITH THE *SOFTWARE* OR THE USE OR OTHER DEALINGS IN THE *SOFTWARE*.
gaussiansplatting/README.md ADDED
@@ -0,0 +1,488 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 3D Gaussian Splatting for Real-Time Radiance Field Rendering
2
+ Bernhard Kerbl*, Georgios Kopanas*, Thomas Leimkühler, George Drettakis (* indicates equal contribution)<br>
3
+ | [Webpage](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/) | [Full Paper](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/3d_gaussian_splatting_high.pdf) |
4
+ [Video](https://youtu.be/T_kXY43VZnk) | [Other GRAPHDECO Publications](http://www-sop.inria.fr/reves/publis/gdindex.php) | [FUNGRAPH project page](https://fungraph.inria.fr) |
5
+
6
+ | [T&T+DB COLMAP (650MB)](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/datasets/input/tandt_db.zip) | [Pre-trained Models (14 GB)](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/datasets/pretrained/models.zip) | [Viewers for Windows (60MB)](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/binaries/viewers.zip) | [Evaluation Images (7 GB)](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/evaluation/images.zip) | <br>
7
+ ![Teaser image](assets/teaser.png)
8
+
9
+ This repository contains the official authors implementation associated with the paper "3D Gaussian Splatting for Real-Time Radiance Field Rendering", which can be found [here](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/). We further provide the reference images used to create the error metrics reported in the paper, as well as recently created, pre-trained models.
10
+
11
+ <a href="https://www.inria.fr/"><img height="100" src="assets/logo_inria.png"> </a>
12
+ <a href="https://univ-cotedazur.eu/"><img height="100" src="assets/logo_uca.png"> </a>
13
+ <a href="https://www.mpi-inf.mpg.de"><img height="100" src="assets/logo_mpi.png"> </a>
14
+ <a href="https://team.inria.fr/graphdeco/"> <img style="width:100%;" src="assets/logo_graphdeco.png"></a>
15
+
16
+ Abstract: *Radiance Field methods have recently revolutionized novel-view synthesis of scenes captured with multiple photos or videos. However, achieving high visual quality still requires neural networks that are costly to train and render, while recent faster methods inevitably trade off speed for quality. For unbounded and complete scenes (rather than isolated objects) and 1080p resolution rendering, no current method can achieve real-time display rates. We introduce three key elements that allow us to achieve state-of-the-art visual quality while maintaining competitive training times and importantly allow high-quality real-time (≥ 30 fps) novel-view synthesis at 1080p resolution. First, starting from sparse points produced during camera calibration, we represent the scene with 3D Gaussians that preserve desirable properties of continuous volumetric radiance fields for scene optimization while avoiding unnecessary computation in empty space; Second, we perform interleaved optimization/density control of the 3D Gaussians, notably optimizing anisotropic covariance to achieve an accurate representation of the scene; Third, we develop a fast visibility-aware rendering algorithm that supports anisotropic splatting and both accelerates training and allows realtime rendering. We demonstrate state-of-the-art visual quality and real-time rendering on several established datasets.*
17
+
18
+ <section class="section" id="BibTeX">
19
+ <div class="container is-max-desktop content">
20
+ <h2 class="title">BibTeX</h2>
21
+ <pre><code>@Article{kerbl3Dgaussians,
22
+ author = {Kerbl, Bernhard and Kopanas, Georgios and Leimk{\"u}hler, Thomas and Drettakis, George},
23
+ title = {3D Gaussian Splatting for Real-Time Radiance Field Rendering},
24
+ journal = {ACM Transactions on Graphics},
25
+ number = {4},
26
+ volume = {42},
27
+ month = {July},
28
+ year = {2023},
29
+ url = {https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/}
30
+ }</code></pre>
31
+ </div>
32
+ </section>
33
+
34
+
35
+ ## Funding and Acknowledgments
36
+
37
+ This research was funded by the ERC Advanced grant FUNGRAPH No 788065. The authors are grateful to Adobe for generous donations, the OPAL infrastructure from Université Côte d’Azur and for the HPC resources from GENCI–IDRIS (Grant 2022-AD011013409). The authors thank the anonymous reviewers for their valuable feedback, P. Hedman and A. Tewari for proofreading earlier drafts also T. Müller, A. Yu and S. Fridovich-Keil for helping with the comparisons.
38
+
39
+ ## Cloning the Repository
40
+
41
+ The repository contains submodules, thus please check it out with
42
+ ```shell
43
+ # SSH
44
+ git clone git@github.com:graphdeco-inria/gaussian-splatting.git --recursive
45
+ ```
46
+ or
47
+ ```shell
48
+ # HTTPS
49
+ git clone https://github.com/graphdeco-inria/gaussian-splatting --recursive
50
+ ```
51
+
52
+ ## Overview
53
+
54
+ The codebase has 4 main components:
55
+ - A PyTorch-based optimizer to produce a 3D Gaussian model from SfM inputs
56
+ - A network viewer that allows to connect to and visualize the optimization process
57
+ - An OpenGL-based real-time viewer to render trained models in real-time.
58
+ - A script to help you turn your own images into optimization-ready SfM data sets
59
+
60
+ The components have different requirements w.r.t. both hardware and software. They have been tested on Windows 10 and Ubuntu Linux 22.04. Instructions for setting up and running each of them are found in the sections below.
61
+
62
+ ## Optimizer
63
+
64
+ The optimizer uses PyTorch and CUDA extensions in a Python environment to produce trained models.
65
+
66
+ ### Hardware Requirements
67
+
68
+ - CUDA-ready GPU with Compute Capability 7.0+
69
+ - 24 GB VRAM (to train to paper evaluation quality)
70
+ - Please see FAQ for smaller VRAM configurations
71
+
72
+ ### Software Requirements
73
+ - Conda (recommended for easy setup)
74
+ - C++ Compiler for PyTorch extensions (we used Visual Studio 2019 for Windows)
75
+ - CUDA SDK 11 for PyTorch extensions (we used 11.8, **known issues with 11.6**)
76
+ - C++ Compiler and CUDA SDK must be compatible
77
+
78
+ ### Setup
79
+
80
+ Our provided install method is based on Conda package and environment management:
81
+ ```shell
82
+ SET DISTUTILS_USE_SDK=1 # Windows only
83
+ conda env create --file environment.yml
84
+ conda activate gaussian_splatting
85
+ ```
86
+ Please note that this process assumes that you have CUDA SDK **11** installed, not **12**. For modifications, see below.
87
+
88
+ Tip: Downloading packages and creating a new environment with Conda can require a significant amount of disk space. By default, Conda will use the main system hard drive. You can avoid this by specifying a different package download location and an environment on a different drive:
89
+
90
+ ```shell
91
+ conda config --add pkgs_dirs <Drive>/<pkg_path>
92
+ conda env create --file environment.yml --prefix <Drive>/<env_path>/gaussian_splatting
93
+ conda activate <Drive>/<env_path>/gaussian_splatting
94
+ ```
95
+
96
+ #### Modifications
97
+
98
+ If you can afford the disk space, we recommend using our environment files for setting up a training environment identical to ours. If you want to make modifications, please note that major version changes might affect the results of our method. However, our (limited) experiments suggest that the codebase works just fine inside a more up-to-date environment (Python 3.8, PyTorch 2.0.0, CUDA 12). Make sure to create an environment where PyTorch and its CUDA runtime version match and the installed CUDA SDK has no major version difference with PyTorch's CUDA version.
99
+
100
+ ### Running
101
+
102
+ To run the optimizer, simply use
103
+
104
+ ```shell
105
+ python train.py -s <path to COLMAP or NeRF Synthetic dataset>
106
+ ```
107
+
108
+ <details>
109
+ <summary><span style="font-weight: bold;">Command Line Arguments for train.py</span></summary>
110
+
111
+ #### --source_path / -s
112
+ Path to the source directory containing a COLMAP or Synthetic NeRF data set.
113
+ #### --model_path / -m
114
+ Path where the trained model should be stored (```output/<random>``` by default).
115
+ #### --images / -i
116
+ Alternative subdirectory for COLMAP images (```images``` by default).
117
+ #### --eval
118
+ Add this flag to use a MipNeRF360-style training/test split for evaluation.
119
+ #### --resolution / -r
120
+ Specifies resolution of the loaded images before training. If provided ```1, 2, 4``` or ```8```, uses original, 1/2, 1/4 or 1/8 resolution, respectively. For all other values, rescales the width to the given number while maintaining image aspect. **If not set and input image width exceeds 1.6K pixels, inputs are automatically rescaled to this target.**
121
+ #### --data_device
122
+ Specifies where to put the source image data, ```cuda``` by default, recommended to use ```cpu``` if training on large/high-resolution dataset, will reduce VRAM consumption, but slightly slow down training.
123
+ #### --white_background / -w
124
+ Add this flag to use white background instead of black (default), e.g., for evaluation of NeRF Synthetic dataset.
125
+ #### --sh_degree
126
+ Order of spherical harmonics to be used (no larger than 3). ```3``` by default.
127
+ #### --convert_SHs_python
128
+ Flag to make pipeline compute forward and backward of SHs with PyTorch instead of ours.
129
+ #### --convert_cov3D_python
130
+ Flag to make pipeline compute forward and backward of the 3D covariance with PyTorch instead of ours.
131
+ #### --debug
132
+ Enables debug mode if you experience erros. If the rasterizer fails, a ```dump``` file is created that you may forward to us in an issue so we can take a look.
133
+ #### --debug_from
134
+ Debugging is **slow**. You may specify an iteration (starting from 0) after which the above debugging becomes active.
135
+ #### --iterations
136
+ Number of total iterations to train for, ```30_000``` by default.
137
+ #### --ip
138
+ IP to start GUI server on, ```127.0.0.1``` by default.
139
+ #### --port
140
+ Port to use for GUI server, ```6009``` by default.
141
+ #### --test_iterations
142
+ Space-separated iterations at which the training script computes L1 and PSNR over test set, ```7000 30000``` by default.
143
+ #### --save_iterations
144
+ Space-separated iterations at which the training script saves the Gaussian model, ```7000 30000 <iterations>``` by default.
145
+ #### --checkpoint_iterations
146
+ Space-separated iterations at which to store a checkpoint for continuing later, saved in the model directory.
147
+ #### --start_checkpoint
148
+ Path to a saved checkpoint to continue training from.
149
+ #### --quiet
150
+ Flag to omit any text written to standard out pipe.
151
+ #### --feature_lr
152
+ Spherical harmonics features learning rate, ```0.0025``` by default.
153
+ #### --opacity_lr
154
+ Opacity learning rate, ```0.05``` by default.
155
+ #### --scaling_lr
156
+ Scaling learning rate, ```0.005``` by default.
157
+ #### --rotation_lr
158
+ Rotation learning rate, ```0.001``` by default.
159
+ #### --position_lr_max_steps
160
+ Number of steps (from 0) where position learning rate goes from ```initial``` to ```final```. ```30_000``` by default.
161
+ #### --position_lr_init
162
+ Initial 3D position learning rate, ```0.00016``` by default.
163
+ #### --position_lr_final
164
+ Final 3D position learning rate, ```0.0000016``` by default.
165
+ #### --position_lr_delay_mult
166
+ Position learning rate multiplier (cf. Plenoxels), ```0.01``` by default.
167
+ #### --densify_from_iter
168
+ Iteration where densification starts, ```500``` by default.
169
+ #### --densify_until_iter
170
+ Iteration where densification stops, ```15_000``` by default.
171
+ #### --densify_grad_threshold
172
+ Limit that decides if points should be densified based on 2D position gradient, ```0.0002``` by default.
173
+ #### --densification_interal
174
+ How frequently to densify, ```100``` (every 100 iterations) by default.
175
+ #### --opacity_reset_interval
176
+ How frequently to reset opacity, ```3_000``` by default.
177
+ #### --lambda_dssim
178
+ Influence of SSIM on total loss from 0 to 1, ```0.2``` by default.
179
+ #### --percent_dense
180
+ Percentage of scene extent (0--1) a point must exceed to be forcibly densified, ```0.01``` by default.
181
+
182
+ </details>
183
+ <br>
184
+
185
+ Note that similar to MipNeRF360, we target images at resolutions in the 1-1.6K pixel range. For convenience, arbitrary-size inputs can be passed and will be automatically resized if their width exceeds 1600 pixels. We recommend to keep this behavior, but you may force training to use your higher-resolution images by setting ```-r 1```.
186
+
187
+ The MipNeRF360 scenes are hosted by the paper authors [here](https://jonbarron.info/mipnerf360/). You can find our SfM data sets for Tanks&Temples and Deep Blending [here](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/datasets/input/tandt_db.zip). If you do not provide an output model directory (```-m```), trained models are written to folders with randomized unique names inside the ```output``` directory. At this point, the trained models may be viewed with the real-time viewer (see further below).
188
+
189
+ ### Evaluation
190
+ By default, the trained models use all available images in the dataset. To train them while withholding a test set for evaluation, use the ```--eval``` flag. This way, you can render training/test sets and produce error metrics as follows:
191
+ ```shell
192
+ python train.py -s <path to COLMAP or NeRF Synthetic dataset> --eval # Train with train/test split
193
+ python render.py -m <path to trained model> # Generate renderings
194
+ python metrics.py -m <path to trained model> # Compute error metrics on renderings
195
+ ```
196
+
197
+ If you want to evaluate our [pre-trained models](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/datasets/pretrained/models.zip), you will have to download the corresponding source data sets and indicate their location to ```render.py``` with an additional ```--source_path/-s``` flag. Note: The pre-trained models were created with the release codebase. This code base has been cleaned up and includes bugfixes, hence the metrics you get from evaluating them will differ from those in the paper.
198
+ ```shell
199
+ python render.py -m <path to pre-trained model> -s <path to COLMAP dataset>
200
+ python metrics.py -m <path to pre-trained model>
201
+ ```
202
+
203
+ <details>
204
+ <summary><span style="font-weight: bold;">Command Line Arguments for render.py</span></summary>
205
+
206
+ #### --model_path / -m
207
+ Path to the trained model directory you want to create renderings for.
208
+ #### --skip_train
209
+ Flag to skip rendering the training set.
210
+ #### --skip_test
211
+ Flag to skip rendering the test set.
212
+ #### --quiet
213
+ Flag to omit any text written to standard out pipe.
214
+
215
+ **The below parameters will be read automatically from the model path, based on what was used for training. However, you may override them by providing them explicitly on the command line.**
216
+
217
+ #### --source_path / -s
218
+ Path to the source directory containing a COLMAP or Synthetic NeRF data set.
219
+ #### --images / -i
220
+ Alternative subdirectory for COLMAP images (```images``` by default).
221
+ #### --eval
222
+ Add this flag to use a MipNeRF360-style training/test split for evaluation.
223
+ #### --resolution / -r
224
+ Changes the resolution of the loaded images before training. If provided ```1, 2, 4``` or ```8```, uses original, 1/2, 1/4 or 1/8 resolution, respectively. For all other values, rescales the width to the given number while maintaining image aspect. ```1``` by default.
225
+ #### --white_background / -w
226
+ Add this flag to use white background instead of black (default), e.g., for evaluation of NeRF Synthetic dataset.
227
+ #### --convert_SHs_python
228
+ Flag to make pipeline render with computed SHs from PyTorch instead of ours.
229
+ #### --convert_cov3D_python
230
+ Flag to make pipeline render with computed 3D covariance from PyTorch instead of ours.
231
+
232
+ </details>
233
+
234
+ <details>
235
+ <summary><span style="font-weight: bold;">Command Line Arguments for metrics.py</span></summary>
236
+
237
+ #### --model_paths / -m
238
+ Space-separated list of model paths for which metrics should be computed.
239
+ </details>
240
+ <br>
241
+
242
+ We further provide the ```full_eval.py``` script. This script specifies the routine used in our evaluation and demonstrates the use of some additional parameters, e.g., ```--images (-i)``` to define alternative image directories within COLMAP data sets. If you have downloaded and extracted all the training data, you can run it like this:
243
+ ```shell
244
+ python full_eval.py -m360 <mipnerf360 folder> -tat <tanks and temples folder> -db <deep blending folder>
245
+ ```
246
+ In the current version, this process takes about 7h on our reference machine containing an A6000. If you want to do the full evaluation on our pre-trained models, you can specify their download location and skip training.
247
+ ```shell
248
+ python full_eval.py -o <directory with pretrained models> --skip_training -m360 <mipnerf360 folder> -tat <tanks and temples folder> -db <deep blending folder>
249
+ ```
250
+
251
+ If you want to compute the metrics on our paper's [evaluation images](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/evaluation/images.zip), you can also skip rendering. In this case it is not necessary to provide the source datasets. You can compute metrics for multiple image sets at a time.
252
+ ```shell
253
+ python full_eval.py -m <directory with evaluation images>/garden ... --skip_training --skip_rendering
254
+ ```
255
+
256
+ <details>
257
+ <summary><span style="font-weight: bold;">Command Line Arguments for full_eval.py</span></summary>
258
+
259
+ #### --skip_training
260
+ Flag to skip training stage.
261
+ #### --skip_rendering
262
+ Flag to skip rendering stage.
263
+ #### --skip_metrics
264
+ Flag to skip metrics calculation stage.
265
+ #### --output_path
266
+ Directory to put renderings and results in, ```./eval``` by default, set to pre-trained model location if evaluating them.
267
+ #### --mipnerf360 / -m360
268
+ Path to MipNeRF360 source datasets, required if training or rendering.
269
+ #### --tanksandtemples / -tat
270
+ Path to Tanks&Temples source datasets, required if training or rendering.
271
+ #### --deepblending / -db
272
+ Path to Deep Blending source datasets, required if training or rendering.
273
+ </details>
274
+ <br>
275
+
276
+ ## Interactive Viewers
277
+ We provide two interactive viewers for our method: remote and real-time. Our viewing solutions are based on the [SIBR](https://sibr.gitlabpages.inria.fr/) framework, developed by the GRAPHDECO group for several novel-view synthesis projects.
278
+
279
+ ### Hardware Requirements
280
+ - OpenGL 4.5-ready GPU and drivers (or latest MESA software)
281
+ - 4 GB VRAM recommended
282
+ - CUDA-ready GPU with Compute Capability 7.0+ (only for Real-Time Viewer)
283
+
284
+ ### Software Requirements
285
+ - Visual Studio or g++, **not Clang** (we used Visual Studio 2019 for Windows)
286
+ - CUDA SDK 11 (we used 11.8)
287
+ - CMake (recent version, we used 3.24)
288
+ - 7zip (only on Windows)
289
+
290
+ ### Pre-built Windows Binaries
291
+ We provide pre-built binaries for Windows [here](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/binaries/viewers.zip). We recommend using them on Windows for an efficient setup, since the building of SIBR involves several external dependencies that must be downloaded and compiled on-the-fly.
292
+
293
+ ### Installation from Source
294
+ If you cloned with submodules (e.g., using ```--recursive```), the source code for the viewers is found in ```SIBR_viewers```. The network viewer runs within the SIBR framework for Image-based Rendering applications.
295
+
296
+ #### Windows
297
+ CMake should take care of your dependencies.
298
+ ```shell
299
+ cd SIBR_viewers
300
+ cmake -Bbuild .
301
+ cmake --build build --target install --config RelWithDebInfo
302
+ ```
303
+ You may specify a different configuration, e.g. ```Debug``` if you need more control during development.
304
+
305
+ #### Ubuntu 22.04
306
+ You will need to install a few dependencies before running the project setup.
307
+ ```shell
308
+ # Dependencies
309
+ sudo apt install -y libglew-dev libassimp-dev libboost-all-dev libgtk-3-dev libopencv-dev libglfw3-dev libavdevice-dev libavcodec-dev libeigen3-dev libxxf86vm-dev libembree-dev
310
+ # Project setup
311
+ cd SIBR_viewers
312
+ cmake -Bbuild . -DCMAKE_BUILD_TYPE=Release # add -G Ninja to build faster
313
+ cmake --build build -j24 --target install
314
+ ```
315
+
316
+ #### Ubuntu 20.04
317
+ Backwards compatibility with Focal Fossa is not fully tested, but building SIBR with CMake should still work after invoking
318
+ ```shell
319
+ git checkout fossa_compatibility
320
+ ```
321
+
322
+ ### Navigation in SIBR Viewers
323
+ The SIBR interface provides several methods of navigating the scene. By default, you will be started with an FPS navigator, which you can control with ```W, A, S, D, Q, E``` for camera translation and ```I, K, J, L, U, O``` for rotation. Alternatively, you may want to use a Trackball-style navigator (select from the floating menu). You can also snap to a camera from the data set with the ```Snap to``` button or find the closest camera with ```Snap to closest```. The floating menues also allow you to change the navigation speed. You can use the ```Scaling Modifier``` to control the size of the displayed Gaussians, or show the initial point cloud.
324
+
325
+ ### Running the Network Viewer
326
+
327
+
328
+
329
+ https://github.com/graphdeco-inria/gaussian-splatting/assets/40643808/90a2e4d3-cf2e-4633-b35f-bfe284e28ff7
330
+
331
+
332
+
333
+ After extracting or installing the viewers, you may run the compiled ```SIBR_remoteGaussian_app[_config]``` app in ```<SIBR install dir>/bin```, e.g.:
334
+ ```shell
335
+ ./<SIBR install dir>/bin/SIBR_remoteGaussian_app
336
+ ```
337
+ The network viewer allows you to connect to a running training process on the same or a different machine. If you are training on the same machine and OS, no command line parameters should be required: the optimizer communicates the location of the training data to the network viewer. By default, optimizer and network viewer will try to establish a connection on **localhost** on port **6009**. You can change this behavior by providing matching ```--ip``` and ```--port``` parameters to both the optimizer and the network viewer. If for some reason the path used by the optimizer to find the training data is not reachable by the network viewer (e.g., due to them running on different (virtual) machines), you may specify an override location to the viewer by using ```-s <source path>```.
338
+
339
+ <details>
340
+ <summary><span style="font-weight: bold;">Primary Command Line Arguments for Network Viewer</span></summary>
341
+
342
+ #### --path / -s
343
+ Argument to override model's path to source dataset.
344
+ #### --ip
345
+ IP to use for connection to a running training script.
346
+ #### --port
347
+ Port to use for connection to a running training script.
348
+ #### --rendering-size
349
+ Takes two space separated numbers to define the resolution at which network rendering occurs, ```1200``` width by default.
350
+ Note that to enforce an aspect that differs from the input images, you need ```--force-aspect-ratio``` too.
351
+ #### --load_images
352
+ Flag to load source dataset images to be displayed in the top view for each camera.
353
+ </details>
354
+ <br>
355
+
356
+ ### Running the Real-Time Viewer
357
+
358
+
359
+
360
+
361
+ https://github.com/graphdeco-inria/gaussian-splatting/assets/40643808/0940547f-1d82-4c2f-a616-44eabbf0f816
362
+
363
+
364
+
365
+
366
+ After extracting or installing the viewers, you may run the compiled ```SIBR_gaussianViewer_app[_config]``` app in ```<SIBR install dir>/bin```, e.g.:
367
+ ```shell
368
+ ./<SIBR install dir>/bin/SIBR_gaussianViewer_app -m <path to trained model>
369
+ ```
370
+
371
+ It should suffice to provide the ```-m``` parameter pointing to a trained model directory. Alternatively, you can specify an override location for training input data using ```-s```. To use a specific resolution other than the auto-chosen one, specify ```--rendering-size <width> <height>```. Combine it with ```--force-aspect-ratio``` if you want the exact resolution and don't mind image distortion.
372
+
373
+ **To unlock the full frame rate, please disable V-Sync on your machine and also in the application (Menu &rarr; Display). In a multi-GPU system (e.g., laptop) your OpenGL/Display GPU should be the same as your CUDA GPU (e.g., by setting the application's GPU preference on Windows, see below) for maximum performance.**
374
+
375
+ ![Teaser image](assets/select.png)
376
+
377
+ In addition to the intial point cloud and the splats, you also have the option to visualize the Gaussians by rendering them as ellipsoids from the floating menu.
378
+ SIBR has many other functionalities, please see the [documentation](https://sibr.gitlabpages.inria.fr/) for more details on the viewer, navigation options etc. There is also a Top View (available from the menu) that shows the placement of the input cameras and the original SfM point cloud; please note that Top View slows rendering when enabled. The real-time viewer also uses slightly more aggressive, fast culling, which can be toggled in the floating menu. If you ever encounter an issue that can be solved by turning fast culling off, please let us know.
379
+
380
+ <details>
381
+ <summary><span style="font-weight: bold;">Primary Command Line Arguments for Real-Time Viewer</span></summary>
382
+
383
+ #### --model-path / -m
384
+ Path to trained model.
385
+ #### --iteration
386
+ Specifies which of state to load if multiple are available. Defaults to latest available iteration.
387
+ #### --path / -s
388
+ Argument to override model's path to source dataset.
389
+ #### --rendering-size
390
+ Takes two space separated numbers to define the resolution at which real-time rendering occurs, ```1200``` width by default. Note that to enforce an aspect that differs from the input images, you need ```--force-aspect-ratio``` too.
391
+ #### --load_images
392
+ Flag to load source dataset images to be displayed in the top view for each camera.
393
+ #### --device
394
+ Index of CUDA device to use for rasterization if multiple are available, ```0``` by default.
395
+ #### --no_interop
396
+ Disables CUDA/GL interop forcibly. Use on systems that may not behave according to spec (e.g., WSL2 with MESA GL 4.5 software rendering).
397
+ </details>
398
+ <br>
399
+
400
+ ## Processing your own Scenes
401
+
402
+ Our COLMAP loaders expect the following dataset structure in the source path location:
403
+
404
+ ```
405
+ <location>
406
+ |---images
407
+ | |---<image 0>
408
+ | |---<image 1>
409
+ | |---...
410
+ |---sparse
411
+ |---0
412
+ |---cameras.bin
413
+ |---images.bin
414
+ |---points3D.bin
415
+ ```
416
+
417
+ For rasterization, the camera models must be either a SIMPLE_PINHOLE or PINHOLE camera. We provide a converter script ```convert.py```, to extract undistorted images and SfM information from input images. Optionally, you can use ImageMagick to resize the undistorted images. This rescaling is similar to MipNeRF360, i.e., it creates images with 1/2, 1/4 and 1/8 the original resolution in corresponding folders. To use them, please first install a recent version of COLMAP (ideally CUDA-powered) and ImageMagick. Put the images you want to use in a directory ```<location>/input```.
418
+ ```
419
+ <location>
420
+ |---input
421
+ |---<image 0>
422
+ |---<image 1>
423
+ |---...
424
+ ```
425
+ If you have COLMAP and ImageMagick on your system path, you can simply run
426
+ ```shell
427
+ python convert.py -s <location> [--resize] #If not resizing, ImageMagick is not needed
428
+ ```
429
+ Alternatively, you can use the optional parameters ```--colmap_executable``` and ```--magick_executable``` to point to the respective paths. Please note that on Windows, the executable should point to the COLMAP ```.bat``` file that takes care of setting the execution environment. Once done, ```<location>``` will contain the expected COLMAP data set structure with undistorted, resized input images, in addition to your original images and some temporary (distorted) data in the directory ```distorted```.
430
+
431
+ If you have your own COLMAP dataset without undistortion (e.g., using ```OPENCV``` camera), you can try to just run the last part of the script: Put the images in ```input``` and the COLMAP info in a subdirectory ```distorted```:
432
+ ```
433
+ <location>
434
+ |---input
435
+ | |---<image 0>
436
+ | |---<image 1>
437
+ | |---...
438
+ |---distorted
439
+ |---database.db
440
+ |---sparse
441
+ |---0
442
+ |---...
443
+ ```
444
+ Then run
445
+ ```shell
446
+ python convert.py -s <location> --skip_matching [--resize] #If not resizing, ImageMagick is not needed
447
+ ```
448
+
449
+ <details>
450
+ <summary><span style="font-weight: bold;">Command Line Arguments for convert.py</span></summary>
451
+
452
+ #### --no_gpu
453
+ Flag to avoid using GPU in COLMAP.
454
+ #### --skip_matching
455
+ Flag to indicate that COLMAP info is available for images.
456
+ #### --source_path / -s
457
+ Location of the inputs.
458
+ #### --camera
459
+ Which camera model to use for the early matching steps, ```OPENCV``` by default.
460
+ #### --resize
461
+ Flag for creating resized versions of input images.
462
+ #### --colmap_executable
463
+ Path to the COLMAP executable (```.bat``` on Windows).
464
+ #### --magick_executable
465
+ Path to the ImageMagick executable.
466
+ </details>
467
+ <br>
468
+
469
+ ## FAQ
470
+ - *Where do I get data sets, e.g., those referenced in ```full_eval.py```?* The MipNeRF360 data set is provided by the authors of the original paper on the project site. Note that two of the data sets cannot be openly shared and require you to consult the authors directly. For Tanks&Temples and Deep Blending, please use the download links provided at the top of the page.
471
+
472
+
473
+ - *How can I use this for a much larger dataset, like a city district?* The current method was not designed for these, but given enough memory, it should work out. However, the approach can struggle in multi-scale detail scenes (extreme close-ups, mixed with far-away shots). This is usually the case in, e.g., driving data sets (cars close up, buildings far away). For such scenes, you can lower the ```--position_lr_init```, ```--position_lr_final``` and ```--scaling_lr``` (x0.3, x0.1, ...). The more extensive the scene, the lower these values should be. Below, we use default learning rates (left) and ```--position_lr_init 0.000016 --scaling_lr 0.001"``` (right).
474
+
475
+ | ![Default learning rate result](assets/worse.png "title-1") <!-- --> | <!-- --> ![Reduced learning rate result](assets/better.png "title-2") |
476
+ | --- | --- |
477
+
478
+
479
+ - *I don't have 24 GB of VRAM for training, what do I do?* The VRAM consumption is determined by the number of points that are being optimized, which increases over time. If you only want to train to 7k iterations, you will need significantly less. To do the full training routine and avoid running out of memory, you can increase the ```--densify_grad_threshold```, ```--densification_interval``` or reduce the value of ```--densify_until_iter```. Note however that this will affect the quality of the result. Also try setting ```--test_iterations``` to ```-1``` to avoid memory spikes during testing. If ```--densify_grad_threshold``` is very high, no densification should occur and training should complete if the scene itself loads successfully.
480
+
481
+ - *24 GB of VRAM for reference quality training is still a lot! Can't we do it with less?* Yes, most likely. By our calculations it should be possible with **way** less memory (~8GB). If we can find the time we will try to achieve this. If some PyTorch veteran out there wants to tackle this, we look forward to your pull request!
482
+
483
+
484
+ - *How can I use the differentiable Gaussian rasterizer for my own project?* Easy, it is included in this repo as a submodule ```diff-gaussian-rasterization```. Feel free to check out and install the package. It's not really documented, but using it from the Python side is very straightforward (cf. ```gaussian_renderer/__init__.py```).
485
+
486
+ - *Wait, but ```<insert feature>``` isn't optimized and could be much better?* There are several parts we didn't even have time to think about improving (yet). The performance you get with this prototype is probably a rather slow baseline for what is physically possible.
487
+
488
+ - *Something is broken, how did this happen?* We tried hard to provide a solid and comprehensible basis to make use of the paper's method. We have refactored the code quite a bit, but we have limited capacity to test all possible usage scenarios. Thus, if part of the website, the code or the performance is lacking, please create an issue. If we find the time, we will do our best to address it.
gaussiansplatting/arguments/__init__.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Copyright (C) 2023, Inria
3
+ # GRAPHDECO research group, https://team.inria.fr/graphdeco
4
+ # All rights reserved.
5
+ #
6
+ # This software is free for non-commercial, research and evaluation use
7
+ # under the terms of the LICENSE.md file.
8
+ #
9
+ # For inquiries contact george.drettakis@inria.fr
10
+ #
11
+
12
+ from argparse import ArgumentParser, Namespace
13
+ import sys
14
+ import os
15
+
16
+ class GroupParams:
17
+ pass
18
+
19
+ class ParamGroup:
20
+ def __init__(self, parser: ArgumentParser, name : str, fill_none = False):
21
+ group = parser.add_argument_group(name)
22
+ for key, value in vars(self).items():
23
+ shorthand = False
24
+ if key.startswith("_"):
25
+ shorthand = True
26
+ key = key[1:]
27
+ t = type(value)
28
+ value = value if not fill_none else None
29
+ if shorthand:
30
+ if t == bool:
31
+ group.add_argument("--" + key, ("-" + key[0:1]), default=value, action="store_true")
32
+ else:
33
+ group.add_argument("--" + key, ("-" + key[0:1]), default=value, type=t)
34
+ else:
35
+ if t == bool:
36
+ group.add_argument("--" + key, default=value, action="store_true")
37
+ else:
38
+ group.add_argument("--" + key, default=value, type=t)
39
+
40
+ def extract(self, args):
41
+ group = GroupParams()
42
+ for arg in vars(args).items():
43
+ if arg[0] in vars(self) or ("_" + arg[0]) in vars(self):
44
+ setattr(group, arg[0], arg[1])
45
+ return group
46
+
47
+ class ModelParams(ParamGroup):
48
+ def __init__(self, parser, sentinel=False):
49
+ self.sh_degree = 3
50
+ self._source_path = ""
51
+ self._model_path = ""
52
+ self._images = "images"
53
+ self._resolution = -1
54
+ self._white_background = False
55
+ self.data_device = "cuda"
56
+ self.eval = False
57
+ super().__init__(parser, "Loading Parameters", sentinel)
58
+
59
+ def extract(self, args):
60
+ g = super().extract(args)
61
+ g.source_path = os.path.abspath(g.source_path)
62
+ return g
63
+ class PipelineParams(ParamGroup):
64
+ def __init__(self, parser):
65
+ self.convert_SHs_python = False
66
+ self.compute_cov3D_python = False
67
+ self.debug = False
68
+ super().__init__(parser, "Pipeline Parameters")
69
+
70
+ class OptimizationParams(ParamGroup):
71
+ def __init__(self, parser):
72
+ self.iterations = 3_200
73
+ self.position_lr_init = 0.00005
74
+ self.position_lr_final = 0.000025
75
+ self.position_lr_delay_mult = 0.5
76
+ self.position_lr_max_steps = 30_000
77
+ self.feature_lr = 0.0125
78
+ self.opacity_lr = 0.01
79
+ self.scaling_lr = 0.005
80
+ self.rotation_lr = 0.001
81
+ self.percent_dense = 0.01
82
+ self.lambda_dssim = 0.2
83
+ self.densification_interval = 100
84
+ self.opacity_reset_interval = 3000
85
+ self.densify_from_iter = 500
86
+ self.densify_until_iter = 15_000
87
+ self.densify_grad_threshold = 0.0002
88
+ super().__init__(parser, "Optimization Parameters")
89
+
90
+
91
+ def get_combined_args(parser : ArgumentParser):
92
+ cmdlne_string = sys.argv[1:]
93
+ cfgfile_string = "Namespace()"
94
+ args_cmdline = parser.parse_args(cmdlne_string)
95
+
96
+ try:
97
+ cfgfilepath = os.path.join(args_cmdline.model_path, "cfg_args")
98
+ print("Looking for config file in", cfgfilepath)
99
+ with open(cfgfilepath) as cfg_file:
100
+ print("Config file found: {}".format(cfgfilepath))
101
+ cfgfile_string = cfg_file.read()
102
+ except TypeError:
103
+ print("Config file not found at")
104
+ pass
105
+ args_cfgfile = eval(cfgfile_string)
106
+
107
+ merged_dict = vars(args_cfgfile).copy()
108
+ for k,v in vars(args_cmdline).items():
109
+ if v != None:
110
+ merged_dict[k] = v
111
+ return Namespace(**merged_dict)
gaussiansplatting/assets/better.png ADDED
gaussiansplatting/assets/logo_graphdeco.png ADDED
gaussiansplatting/assets/logo_inria.png ADDED
gaussiansplatting/assets/logo_mpi.png ADDED
gaussiansplatting/assets/logo_mpi.svg ADDED
gaussiansplatting/assets/logo_uca.png ADDED
gaussiansplatting/assets/select.png ADDED
gaussiansplatting/assets/teaser.png ADDED
gaussiansplatting/assets/worse.png ADDED
gaussiansplatting/convert.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Copyright (C) 2023, Inria
3
+ # GRAPHDECO research group, https://team.inria.fr/graphdeco
4
+ # All rights reserved.
5
+ #
6
+ # This software is free for non-commercial, research and evaluation use
7
+ # under the terms of the LICENSE.md file.
8
+ #
9
+ # For inquiries contact george.drettakis@inria.fr
10
+ #
11
+
12
+ import os
13
+ import logging
14
+ from argparse import ArgumentParser
15
+ import shutil
16
+
17
+ # This Python script is based on the shell converter script provided in the MipNerF 360 repository.
18
+ parser = ArgumentParser("Colmap converter")
19
+ parser.add_argument("--no_gpu", action='store_true')
20
+ parser.add_argument("--skip_matching", action='store_true')
21
+ parser.add_argument("--source_path", "-s", required=True, type=str)
22
+ parser.add_argument("--camera", default="OPENCV", type=str)
23
+ parser.add_argument("--colmap_executable", default="", type=str)
24
+ parser.add_argument("--resize", action="store_true")
25
+ parser.add_argument("--magick_executable", default="", type=str)
26
+ args = parser.parse_args()
27
+ colmap_command = '"{}"'.format(args.colmap_executable) if len(args.colmap_executable) > 0 else "colmap"
28
+ magick_command = '"{}"'.format(args.magick_executable) if len(args.magick_executable) > 0 else "magick"
29
+ use_gpu = 1 if not args.no_gpu else 0
30
+
31
+ if not args.skip_matching:
32
+ os.makedirs(args.source_path + "/distorted/sparse", exist_ok=True)
33
+
34
+ ## Feature extraction
35
+ feat_extracton_cmd = colmap_command + " feature_extractor "\
36
+ "--database_path " + args.source_path + "/distorted/database.db \
37
+ --image_path " + args.source_path + "/input \
38
+ --ImageReader.single_camera 1 \
39
+ --ImageReader.camera_model " + args.camera + " \
40
+ --SiftExtraction.use_gpu " + str(use_gpu)
41
+ exit_code = os.system(feat_extracton_cmd)
42
+ if exit_code != 0:
43
+ logging.error(f"Feature extraction failed with code {exit_code}. Exiting.")
44
+ exit(exit_code)
45
+
46
+ ## Feature matching
47
+ feat_matching_cmd = colmap_command + " exhaustive_matcher \
48
+ --database_path " + args.source_path + "/distorted/database.db \
49
+ --SiftMatching.use_gpu " + str(use_gpu)
50
+ exit_code = os.system(feat_matching_cmd)
51
+ if exit_code != 0:
52
+ logging.error(f"Feature matching failed with code {exit_code}. Exiting.")
53
+ exit(exit_code)
54
+
55
+ ### Bundle adjustment
56
+ # The default Mapper tolerance is unnecessarily large,
57
+ # decreasing it speeds up bundle adjustment steps.
58
+ mapper_cmd = (colmap_command + " mapper \
59
+ --database_path " + args.source_path + "/distorted/database.db \
60
+ --image_path " + args.source_path + "/input \
61
+ --output_path " + args.source_path + "/distorted/sparse \
62
+ --Mapper.ba_global_function_tolerance=0.000001")
63
+ exit_code = os.system(mapper_cmd)
64
+ if exit_code != 0:
65
+ logging.error(f"Mapper failed with code {exit_code}. Exiting.")
66
+ exit(exit_code)
67
+
68
+ ### Image undistortion
69
+ ## We need to undistort our images into ideal pinhole intrinsics.
70
+ img_undist_cmd = (colmap_command + " image_undistorter \
71
+ --image_path " + args.source_path + "/input \
72
+ --input_path " + args.source_path + "/distorted/sparse/0 \
73
+ --output_path " + args.source_path + "\
74
+ --output_type COLMAP")
75
+ exit_code = os.system(img_undist_cmd)
76
+ if exit_code != 0:
77
+ logging.error(f"Mapper failed with code {exit_code}. Exiting.")
78
+ exit(exit_code)
79
+
80
+ files = os.listdir(args.source_path + "/sparse")
81
+ os.makedirs(args.source_path + "/sparse/0", exist_ok=True)
82
+ # Copy each file from the source directory to the destination directory
83
+ for file in files:
84
+ if file == '0':
85
+ continue
86
+ source_file = os.path.join(args.source_path, "sparse", file)
87
+ destination_file = os.path.join(args.source_path, "sparse", "0", file)
88
+ shutil.move(source_file, destination_file)
89
+
90
+ if(args.resize):
91
+ print("Copying and resizing...")
92
+
93
+ # Resize images.
94
+ os.makedirs(args.source_path + "/images_2", exist_ok=True)
95
+ os.makedirs(args.source_path + "/images_4", exist_ok=True)
96
+ os.makedirs(args.source_path + "/images_8", exist_ok=True)
97
+ # Get the list of files in the source directory
98
+ files = os.listdir(args.source_path + "/images")
99
+ # Copy each file from the source directory to the destination directory
100
+ for file in files:
101
+ source_file = os.path.join(args.source_path, "images", file)
102
+
103
+ destination_file = os.path.join(args.source_path, "images_2", file)
104
+ shutil.copy2(source_file, destination_file)
105
+ exit_code = os.system(magick_command + " mogrify -resize 50% " + destination_file)
106
+ if exit_code != 0:
107
+ logging.error(f"50% resize failed with code {exit_code}. Exiting.")
108
+ exit(exit_code)
109
+
110
+ destination_file = os.path.join(args.source_path, "images_4", file)
111
+ shutil.copy2(source_file, destination_file)
112
+ exit_code = os.system(magick_command + " mogrify -resize 25% " + destination_file)
113
+ if exit_code != 0:
114
+ logging.error(f"25% resize failed with code {exit_code}. Exiting.")
115
+ exit(exit_code)
116
+
117
+ destination_file = os.path.join(args.source_path, "images_8", file)
118
+ shutil.copy2(source_file, destination_file)
119
+ exit_code = os.system(magick_command + " mogrify -resize 12.5% " + destination_file)
120
+ if exit_code != 0:
121
+ logging.error(f"12.5% resize failed with code {exit_code}. Exiting.")
122
+ exit(exit_code)
123
+
124
+ print("Done.")
gaussiansplatting/environment.yml ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: gaussian
2
+ channels:
3
+ - pytorch
4
+ - conda-forge
5
+ - defaults
6
+ dependencies:
7
+ - cudatoolkit=11.6
8
+ - plyfile=0.8.1
9
+ - python=3.7.13
10
+ - pip=22.3.1
11
+ - pytorch=1.12.1
12
+ - torchaudio=0.12.1
13
+ - torchvision=0.13.1
14
+ - tqdm
15
+ - pip:
16
+ - submodules/diff-gaussian-rasterization
17
+ - submodules/simple-knn
gaussiansplatting/full_eval.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Copyright (C) 2023, Inria
3
+ # GRAPHDECO research group, https://team.inria.fr/graphdeco
4
+ # All rights reserved.
5
+ #
6
+ # This software is free for non-commercial, research and evaluation use
7
+ # under the terms of the LICENSE.md file.
8
+ #
9
+ # For inquiries contact george.drettakis@inria.fr
10
+ #
11
+
12
+ import os
13
+ from argparse import ArgumentParser
14
+
15
+ mipnerf360_outdoor_scenes = ["bicycle", "flowers", "garden", "stump", "treehill"]
16
+ mipnerf360_indoor_scenes = ["room", "counter", "kitchen", "bonsai"]
17
+ tanks_and_temples_scenes = ["truck", "train"]
18
+ deep_blending_scenes = ["drjohnson", "playroom"]
19
+
20
+ parser = ArgumentParser(description="Full evaluation script parameters")
21
+ parser.add_argument("--skip_training", action="store_true")
22
+ parser.add_argument("--skip_rendering", action="store_true")
23
+ parser.add_argument("--skip_metrics", action="store_true")
24
+ parser.add_argument("--output_path", default="./eval")
25
+ args, _ = parser.parse_known_args()
26
+
27
+ all_scenes = []
28
+ all_scenes.extend(mipnerf360_outdoor_scenes)
29
+ all_scenes.extend(mipnerf360_indoor_scenes)
30
+ all_scenes.extend(tanks_and_temples_scenes)
31
+ all_scenes.extend(deep_blending_scenes)
32
+
33
+ if not args.skip_training or not args.skip_rendering:
34
+ parser.add_argument('--mipnerf360', "-m360", required=True, type=str)
35
+ parser.add_argument("--tanksandtemples", "-tat", required=True, type=str)
36
+ parser.add_argument("--deepblending", "-db", required=True, type=str)
37
+ args = parser.parse_args()
38
+
39
+ if not args.skip_training:
40
+ common_args = " --quiet --eval --test_iterations -1 "
41
+ for scene in mipnerf360_outdoor_scenes:
42
+ source = args.mipnerf360 + "/" + scene
43
+ os.system("python train.py -s " + source + " -i images_4 -m " + args.output_path + "/" + scene + common_args)
44
+ for scene in mipnerf360_indoor_scenes:
45
+ source = args.mipnerf360 + "/" + scene
46
+ os.system("python train.py -s " + source + " -i images_2 -m " + args.output_path + "/" + scene + common_args)
47
+ for scene in tanks_and_temples_scenes:
48
+ source = args.tanksandtemples + "/" + scene
49
+ os.system("python train.py -s " + source + " -m " + args.output_path + "/" + scene + common_args)
50
+ for scene in deep_blending_scenes:
51
+ source = args.deepblending + "/" + scene
52
+ os.system("python train.py -s " + source + " -m " + args.output_path + "/" + scene + common_args)
53
+
54
+ if not args.skip_rendering:
55
+ all_sources = []
56
+ for scene in mipnerf360_outdoor_scenes:
57
+ all_sources.append(args.mipnerf360 + "/" + scene)
58
+ for scene in mipnerf360_indoor_scenes:
59
+ all_sources.append(args.mipnerf360 + "/" + scene)
60
+ for scene in tanks_and_temples_scenes:
61
+ all_sources.append(args.tanksandtemples + "/" + scene)
62
+ for scene in deep_blending_scenes:
63
+ all_sources.append(args.deepblending + "/" + scene)
64
+
65
+ common_args = " --quiet --eval --skip_train"
66
+ for scene, source in zip(all_scenes, all_sources):
67
+ os.system("python render.py --iteration 7000 -s " + source + " -m " + args.output_path + "/" + scene + common_args)
68
+ os.system("python render.py --iteration 30000 -s " + source + " -m " + args.output_path + "/" + scene + common_args)
69
+
70
+ if not args.skip_metrics:
71
+ scenes_string = ""
72
+ for scene in all_scenes:
73
+ scenes_string += "\"" + args.output_path + "/" + scene + "\" "
74
+
75
+ os.system("python metrics.py -m " + scenes_string)
gaussiansplatting/gaussian_renderer/__init__.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Copyright (C) 2023, Inria
3
+ # GRAPHDECO research group, https://team.inria.fr/graphdeco
4
+ # All rights reserved.
5
+ #
6
+ # This software is free for non-commercial, research and evaluation use
7
+ # under the terms of the LICENSE.md file.
8
+ #
9
+ # For inquiries contact george.drettakis@inria.fr
10
+ #
11
+
12
+ import torch
13
+ import math
14
+ from diff_gaussian_rasterization import GaussianRasterizationSettings, GaussianRasterizer
15
+ from gaussiansplatting.scene.gaussian_model import GaussianModel
16
+ from gaussiansplatting.utils.sh_utils import eval_sh
17
+
18
+ def render(viewpoint_camera, pc : GaussianModel, pipe, bg_color : torch.Tensor, scaling_modifier = 1.0, override_color = None):
19
+ """
20
+ Render the scene.
21
+
22
+ Background tensor (bg_color) must be on GPU!
23
+ """
24
+
25
+ # Create zero tensor. We will use it to make pytorch return gradients of the 2D (screen-space) means
26
+ screenspace_points = torch.zeros_like(pc.get_xyz, dtype=pc.get_xyz.dtype, requires_grad=True, device="cuda") + 0
27
+ try:
28
+ screenspace_points.retain_grad()
29
+ except:
30
+ pass
31
+
32
+ # Set up rasterization configuration
33
+ tanfovx = math.tan(viewpoint_camera.FoVx * 0.5)
34
+ tanfovy = math.tan(viewpoint_camera.FoVy * 0.5)
35
+
36
+ raster_settings = GaussianRasterizationSettings(
37
+ image_height=int(viewpoint_camera.image_height),
38
+ image_width=int(viewpoint_camera.image_width),
39
+ tanfovx=tanfovx,
40
+ tanfovy=tanfovy,
41
+ bg=bg_color,
42
+ scale_modifier=scaling_modifier,
43
+ viewmatrix=viewpoint_camera.world_view_transform,
44
+ projmatrix=viewpoint_camera.full_proj_transform,
45
+ sh_degree=pc.active_sh_degree,
46
+ campos=viewpoint_camera.camera_center,
47
+ prefiltered=False,
48
+ )
49
+
50
+ rasterizer = GaussianRasterizer(raster_settings=raster_settings)
51
+
52
+ means3D = pc.get_xyz
53
+ means2D = screenspace_points
54
+ opacity = pc.get_opacity
55
+
56
+ # If precomputed 3d covariance is provided, use it. If not, then it will be computed from
57
+ # scaling / rotation by the rasterizer.
58
+ scales = None
59
+ rotations = None
60
+ cov3D_precomp = None
61
+ if pipe.compute_cov3D_python:
62
+ cov3D_precomp = pc.get_covariance(scaling_modifier)
63
+ else:
64
+ scales = pc.get_scaling
65
+ rotations = pc.get_rotation
66
+
67
+ # If precomputed colors are provided, use them. Otherwise, if it is desired to precompute colors
68
+ # from SHs in Python, do it. If not, then SH -> RGB conversion will be done by rasterizer.
69
+ shs = None
70
+ colors_precomp = None
71
+ if override_color is None:
72
+ if pipe.convert_SHs_python:
73
+ shs_view = pc.get_features.transpose(1, 2).view(-1, 3, (pc.max_sh_degree+1)**2)
74
+ dir_pp = (pc.get_xyz - viewpoint_camera.camera_center.repeat(pc.get_features.shape[0], 1))
75
+ dir_pp_normalized = dir_pp/dir_pp.norm(dim=1, keepdim=True)
76
+ sh2rgb = eval_sh(pc.active_sh_degree, shs_view, dir_pp_normalized)
77
+ colors_precomp = torch.clamp_min(sh2rgb + 0.5, 0.0)
78
+ else:
79
+ shs = pc.get_features
80
+ else:
81
+ colors_precomp = override_color
82
+
83
+ # Rasterize visible Gaussians to image, obtain their radii (on screen).
84
+ # import pdb; pdb.set_trace()
85
+ rendered_image, radii ,depth= rasterizer(
86
+ means3D = means3D.float(),
87
+ means2D = means2D.float(),
88
+ shs = shs.float(),
89
+ colors_precomp = colors_precomp,
90
+ opacities = opacity.float(),
91
+ scales = scales.float(),
92
+ rotations = rotations.float(),
93
+ cov3D_precomp = cov3D_precomp)
94
+
95
+ # Those Gaussians that were frustum culled or had a radius of 0 were not visible.
96
+ # They will be excluded from value updates used in the splitting criteria.
97
+ return {"render": rendered_image,
98
+ "viewspace_points": screenspace_points,
99
+ "visibility_filter" : radii > 0,
100
+ "radii": radii,
101
+ "depth_3dgs":depth}
gaussiansplatting/gaussian_renderer/network_gui.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Copyright (C) 2023, Inria
3
+ # GRAPHDECO research group, https://team.inria.fr/graphdeco
4
+ # All rights reserved.
5
+ #
6
+ # This software is free for non-commercial, research and evaluation use
7
+ # under the terms of the LICENSE.md file.
8
+ #
9
+ # For inquiries contact george.drettakis@inria.fr
10
+ #
11
+
12
+ import torch
13
+ import traceback
14
+ import socket
15
+ import json
16
+ from gaussiansplatting.scene.cameras import MiniCam
17
+
18
+ host = "127.0.0.1"
19
+ port = 6009
20
+
21
+ conn = None
22
+ addr = None
23
+
24
+ listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
25
+
26
+ def init(wish_host, wish_port):
27
+ global host, port, listener
28
+ host = wish_host
29
+ port = wish_port
30
+ listener.bind((host, port))
31
+ listener.listen()
32
+ listener.settimeout(0)
33
+
34
+ def try_connect():
35
+ global conn, addr, listener
36
+ try:
37
+ conn, addr = listener.accept()
38
+ print(f"\nConnected by {addr}")
39
+ conn.settimeout(None)
40
+ except Exception as inst:
41
+ pass
42
+
43
+ def read():
44
+ global conn
45
+ messageLength = conn.recv(4)
46
+ messageLength = int.from_bytes(messageLength, 'little')
47
+ message = conn.recv(messageLength)
48
+ return json.loads(message.decode("utf-8"))
49
+
50
+ def send(message_bytes, verify):
51
+ global conn
52
+ if message_bytes != None:
53
+ conn.sendall(message_bytes)
54
+ conn.sendall(len(verify).to_bytes(4, 'little'))
55
+ conn.sendall(bytes(verify, 'ascii'))
56
+
57
+ def receive():
58
+ message = read()
59
+
60
+ width = message["resolution_x"]
61
+ height = message["resolution_y"]
62
+
63
+ if width != 0 and height != 0:
64
+ try:
65
+ do_training = bool(message["train"])
66
+ fovy = message["fov_y"]
67
+ fovx = message["fov_x"]
68
+ znear = message["z_near"]
69
+ zfar = message["z_far"]
70
+ do_shs_python = bool(message["shs_python"])
71
+ do_rot_scale_python = bool(message["rot_scale_python"])
72
+ keep_alive = bool(message["keep_alive"])
73
+ scaling_modifier = message["scaling_modifier"]
74
+ world_view_transform = torch.reshape(torch.tensor(message["view_matrix"]), (4, 4)).cuda()
75
+ world_view_transform[:,1] = -world_view_transform[:,1]
76
+ world_view_transform[:,2] = -world_view_transform[:,2]
77
+ full_proj_transform = torch.reshape(torch.tensor(message["view_projection_matrix"]), (4, 4)).cuda()
78
+ full_proj_transform[:,1] = -full_proj_transform[:,1]
79
+ custom_cam = MiniCam(width, height, fovy, fovx, znear, zfar, world_view_transform, full_proj_transform)
80
+ except Exception as e:
81
+ print("")
82
+ traceback.print_exc()
83
+ raise e
84
+ return custom_cam, do_training, do_shs_python, do_rot_scale_python, keep_alive, scaling_modifier
85
+ else:
86
+ return None, None, None, None, None, None
gaussiansplatting/lpipsPyTorch/__init__.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ from .modules.lpips import LPIPS
4
+
5
+
6
+ def lpips(x: torch.Tensor,
7
+ y: torch.Tensor,
8
+ net_type: str = 'alex',
9
+ version: str = '0.1'):
10
+ r"""Function that measures
11
+ Learned Perceptual Image Patch Similarity (LPIPS).
12
+
13
+ Arguments:
14
+ x, y (torch.Tensor): the input tensors to compare.
15
+ net_type (str): the network type to compare the features:
16
+ 'alex' | 'squeeze' | 'vgg'. Default: 'alex'.
17
+ version (str): the version of LPIPS. Default: 0.1.
18
+ """
19
+ device = x.device
20
+ criterion = LPIPS(net_type, version).to(device)
21
+ return criterion(x, y)
gaussiansplatting/lpipsPyTorch/modules/lpips.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+ from .networks import get_network, LinLayers
5
+ from .utils import get_state_dict
6
+
7
+
8
+ class LPIPS(nn.Module):
9
+ r"""Creates a criterion that measures
10
+ Learned Perceptual Image Patch Similarity (LPIPS).
11
+
12
+ Arguments:
13
+ net_type (str): the network type to compare the features:
14
+ 'alex' | 'squeeze' | 'vgg'. Default: 'alex'.
15
+ version (str): the version of LPIPS. Default: 0.1.
16
+ """
17
+ def __init__(self, net_type: str = 'alex', version: str = '0.1'):
18
+
19
+ assert version in ['0.1'], 'v0.1 is only supported now'
20
+
21
+ super(LPIPS, self).__init__()
22
+
23
+ # pretrained network
24
+ self.net = get_network(net_type)
25
+
26
+ # linear layers
27
+ self.lin = LinLayers(self.net.n_channels_list)
28
+ self.lin.load_state_dict(get_state_dict(net_type, version))
29
+
30
+ def forward(self, x: torch.Tensor, y: torch.Tensor):
31
+ feat_x, feat_y = self.net(x), self.net(y)
32
+
33
+ diff = [(fx - fy) ** 2 for fx, fy in zip(feat_x, feat_y)]
34
+ res = [l(d).mean((2, 3), True) for d, l in zip(diff, self.lin)]
35
+
36
+ return torch.sum(torch.cat(res, 0), 0, True)
gaussiansplatting/lpipsPyTorch/modules/networks.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Sequence
2
+
3
+ from itertools import chain
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ from torchvision import models
8
+
9
+ from .utils import normalize_activation
10
+
11
+
12
+ def get_network(net_type: str):
13
+ if net_type == 'alex':
14
+ return AlexNet()
15
+ elif net_type == 'squeeze':
16
+ return SqueezeNet()
17
+ elif net_type == 'vgg':
18
+ return VGG16()
19
+ else:
20
+ raise NotImplementedError('choose net_type from [alex, squeeze, vgg].')
21
+
22
+
23
+ class LinLayers(nn.ModuleList):
24
+ def __init__(self, n_channels_list: Sequence[int]):
25
+ super(LinLayers, self).__init__([
26
+ nn.Sequential(
27
+ nn.Identity(),
28
+ nn.Conv2d(nc, 1, 1, 1, 0, bias=False)
29
+ ) for nc in n_channels_list
30
+ ])
31
+
32
+ for param in self.parameters():
33
+ param.requires_grad = False
34
+
35
+
36
+ class BaseNet(nn.Module):
37
+ def __init__(self):
38
+ super(BaseNet, self).__init__()
39
+
40
+ # register buffer
41
+ self.register_buffer(
42
+ 'mean', torch.Tensor([-.030, -.088, -.188])[None, :, None, None])
43
+ self.register_buffer(
44
+ 'std', torch.Tensor([.458, .448, .450])[None, :, None, None])
45
+
46
+ def set_requires_grad(self, state: bool):
47
+ for param in chain(self.parameters(), self.buffers()):
48
+ param.requires_grad = state
49
+
50
+ def z_score(self, x: torch.Tensor):
51
+ return (x - self.mean) / self.std
52
+
53
+ def forward(self, x: torch.Tensor):
54
+ x = self.z_score(x)
55
+
56
+ output = []
57
+ for i, (_, layer) in enumerate(self.layers._modules.items(), 1):
58
+ x = layer(x)
59
+ if i in self.target_layers:
60
+ output.append(normalize_activation(x))
61
+ if len(output) == len(self.target_layers):
62
+ break
63
+ return output
64
+
65
+
66
+ class SqueezeNet(BaseNet):
67
+ def __init__(self):
68
+ super(SqueezeNet, self).__init__()
69
+
70
+ self.layers = models.squeezenet1_1(True).features
71
+ self.target_layers = [2, 5, 8, 10, 11, 12, 13]
72
+ self.n_channels_list = [64, 128, 256, 384, 384, 512, 512]
73
+
74
+ self.set_requires_grad(False)
75
+
76
+
77
+ class AlexNet(BaseNet):
78
+ def __init__(self):
79
+ super(AlexNet, self).__init__()
80
+
81
+ self.layers = models.alexnet(True).features
82
+ self.target_layers = [2, 5, 8, 10, 12]
83
+ self.n_channels_list = [64, 192, 384, 256, 256]
84
+
85
+ self.set_requires_grad(False)
86
+
87
+
88
+ class VGG16(BaseNet):
89
+ def __init__(self):
90
+ super(VGG16, self).__init__()
91
+
92
+ self.layers = models.vgg16(weights=models.VGG16_Weights.IMAGENET1K_V1).features
93
+ self.target_layers = [4, 9, 16, 23, 30]
94
+ self.n_channels_list = [64, 128, 256, 512, 512]
95
+
96
+ self.set_requires_grad(False)
gaussiansplatting/lpipsPyTorch/modules/utils.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+
3
+ import torch
4
+
5
+
6
+ def normalize_activation(x, eps=1e-10):
7
+ norm_factor = torch.sqrt(torch.sum(x ** 2, dim=1, keepdim=True))
8
+ return x / (norm_factor + eps)
9
+
10
+
11
+ def get_state_dict(net_type: str = 'alex', version: str = '0.1'):
12
+ # build url
13
+ url = 'https://raw.githubusercontent.com/richzhang/PerceptualSimilarity/' \
14
+ + f'master/lpips/weights/v{version}/{net_type}.pth'
15
+
16
+ # download
17
+ old_state_dict = torch.hub.load_state_dict_from_url(
18
+ url, progress=True,
19
+ map_location=None if torch.cuda.is_available() else torch.device('cpu')
20
+ )
21
+
22
+ # rename keys
23
+ new_state_dict = OrderedDict()
24
+ for key, val in old_state_dict.items():
25
+ new_key = key
26
+ new_key = new_key.replace('lin', '')
27
+ new_key = new_key.replace('model.', '')
28
+ new_state_dict[new_key] = val
29
+
30
+ return new_state_dict
gaussiansplatting/metrics.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Copyright (C) 2023, Inria
3
+ # GRAPHDECO research group, https://team.inria.fr/graphdeco
4
+ # All rights reserved.
5
+ #
6
+ # This software is free for non-commercial, research and evaluation use
7
+ # under the terms of the LICENSE.md file.
8
+ #
9
+ # For inquiries contact george.drettakis@inria.fr
10
+ #
11
+
12
+ from pathlib import Path
13
+ import os
14
+ from PIL import Image
15
+ import torch
16
+ import torchvision.transforms.functional as tf
17
+ from utils.loss_utils import ssim
18
+ from lpipsPyTorch import lpips
19
+ import json
20
+ from tqdm import tqdm
21
+ from utils.image_utils import psnr
22
+ from argparse import ArgumentParser
23
+
24
+ def readImages(renders_dir, gt_dir):
25
+ renders = []
26
+ gts = []
27
+ image_names = []
28
+ for fname in os.listdir(renders_dir):
29
+ render = Image.open(renders_dir / fname)
30
+ gt = Image.open(gt_dir / fname)
31
+ renders.append(tf.to_tensor(render).unsqueeze(0)[:, :3, :, :].cuda())
32
+ gts.append(tf.to_tensor(gt).unsqueeze(0)[:, :3, :, :].cuda())
33
+ image_names.append(fname)
34
+ return renders, gts, image_names
35
+
36
+ def evaluate(model_paths):
37
+
38
+ full_dict = {}
39
+ per_view_dict = {}
40
+ full_dict_polytopeonly = {}
41
+ per_view_dict_polytopeonly = {}
42
+ print("")
43
+
44
+ for scene_dir in model_paths:
45
+ try:
46
+ print("Scene:", scene_dir)
47
+ full_dict[scene_dir] = {}
48
+ per_view_dict[scene_dir] = {}
49
+ full_dict_polytopeonly[scene_dir] = {}
50
+ per_view_dict_polytopeonly[scene_dir] = {}
51
+
52
+ test_dir = Path(scene_dir) / "test"
53
+
54
+ for method in os.listdir(test_dir):
55
+ print("Method:", method)
56
+
57
+ full_dict[scene_dir][method] = {}
58
+ per_view_dict[scene_dir][method] = {}
59
+ full_dict_polytopeonly[scene_dir][method] = {}
60
+ per_view_dict_polytopeonly[scene_dir][method] = {}
61
+
62
+ method_dir = test_dir / method
63
+ gt_dir = method_dir/ "gt"
64
+ renders_dir = method_dir / "renders"
65
+ renders, gts, image_names = readImages(renders_dir, gt_dir)
66
+
67
+ ssims = []
68
+ psnrs = []
69
+ lpipss = []
70
+
71
+ for idx in tqdm(range(len(renders)), desc="Metric evaluation progress"):
72
+ ssims.append(ssim(renders[idx], gts[idx]))
73
+ psnrs.append(psnr(renders[idx], gts[idx]))
74
+ lpipss.append(lpips(renders[idx], gts[idx], net_type='vgg'))
75
+
76
+ print(" SSIM : {:>12.7f}".format(torch.tensor(ssims).mean(), ".5"))
77
+ print(" PSNR : {:>12.7f}".format(torch.tensor(psnrs).mean(), ".5"))
78
+ print(" LPIPS: {:>12.7f}".format(torch.tensor(lpipss).mean(), ".5"))
79
+ print("")
80
+
81
+ full_dict[scene_dir][method].update({"SSIM": torch.tensor(ssims).mean().item(),
82
+ "PSNR": torch.tensor(psnrs).mean().item(),
83
+ "LPIPS": torch.tensor(lpipss).mean().item()})
84
+ per_view_dict[scene_dir][method].update({"SSIM": {name: ssim for ssim, name in zip(torch.tensor(ssims).tolist(), image_names)},
85
+ "PSNR": {name: psnr for psnr, name in zip(torch.tensor(psnrs).tolist(), image_names)},
86
+ "LPIPS": {name: lp for lp, name in zip(torch.tensor(lpipss).tolist(), image_names)}})
87
+
88
+ with open(scene_dir + "/results.json", 'w') as fp:
89
+ json.dump(full_dict[scene_dir], fp, indent=True)
90
+ with open(scene_dir + "/per_view.json", 'w') as fp:
91
+ json.dump(per_view_dict[scene_dir], fp, indent=True)
92
+ except:
93
+ print("Unable to compute metrics for model", scene_dir)
94
+
95
+ if __name__ == "__main__":
96
+ device = torch.device("cuda:0")
97
+ torch.cuda.set_device(device)
98
+
99
+ # Set up command line argument parser
100
+ parser = ArgumentParser(description="Training script parameters")
101
+ parser.add_argument('--model_paths', '-m', required=True, nargs="+", type=str, default=[])
102
+ args = parser.parse_args()
103
+ evaluate(args.model_paths)
gaussiansplatting/render.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Copyright (C) 2023, Inria
3
+ # GRAPHDECO research group, https://team.inria.fr/graphdeco
4
+ # All rights reserved.
5
+ #
6
+ # This software is free for non-commercial, research and evaluation use
7
+ # under the terms of the LICENSE.md file.
8
+ #
9
+ # For inquiries contact george.drettakis@inria.fr
10
+ #
11
+
12
+ import torch
13
+ from scene import Scene
14
+ import os
15
+ from tqdm import tqdm
16
+ from os import makedirs
17
+ from gaussian_renderer import render
18
+ import torchvision
19
+ from utils.general_utils import safe_state
20
+ from argparse import ArgumentParser
21
+ from arguments import ModelParams, PipelineParams, get_combined_args
22
+ from gaussian_renderer import GaussianModel
23
+
24
+ def render_set(model_path, name, iteration, views, gaussians, pipeline, background):
25
+ render_path = os.path.join(model_path, name, "ours_{}".format(iteration), "renders")
26
+ gts_path = os.path.join(model_path, name, "ours_{}".format(iteration), "gt")
27
+
28
+ makedirs(render_path, exist_ok=True)
29
+ makedirs(gts_path, exist_ok=True)
30
+
31
+ for idx, view in enumerate(tqdm(views, desc="Rendering progress")):
32
+ rendering = render(view, gaussians, pipeline, background)["render"]
33
+ gt = view.original_image[0:3, :, :]
34
+ torchvision.utils.save_image(rendering, os.path.join(render_path, '{0:05d}'.format(idx) + ".png"))
35
+ torchvision.utils.save_image(gt, os.path.join(gts_path, '{0:05d}'.format(idx) + ".png"))
36
+
37
+ def render_sets(dataset : ModelParams, iteration : int, pipeline : PipelineParams, skip_train : bool, skip_test : bool):
38
+ with torch.no_grad():
39
+ gaussians = GaussianModel(dataset.sh_degree)
40
+ scene = Scene(dataset, gaussians, load_iteration=iteration, shuffle=False)
41
+
42
+ bg_color = [1,1,1] if dataset.white_background else [0, 0, 0]
43
+ background = torch.tensor(bg_color, dtype=torch.float32, device="cuda")
44
+
45
+ if not skip_train:
46
+ render_set(dataset.model_path, "train", scene.loaded_iter, scene.getTrainCameras(), gaussians, pipeline, background)
47
+
48
+ if not skip_test:
49
+ render_set(dataset.model_path, "test", scene.loaded_iter, scene.getTestCameras(), gaussians, pipeline, background)
50
+
51
+ if __name__ == "__main__":
52
+ # Set up command line argument parser
53
+ parser = ArgumentParser(description="Testing script parameters")
54
+ model = ModelParams(parser, sentinel=True)
55
+ pipeline = PipelineParams(parser)
56
+ parser.add_argument("--iteration", default=-1, type=int)
57
+ parser.add_argument("--skip_train", action="store_true")
58
+ parser.add_argument("--skip_test", action="store_true")
59
+ parser.add_argument("--quiet", action="store_true")
60
+ args = get_combined_args(parser)
61
+ print("Rendering " + args.model_path)
62
+
63
+ # Initialize system state (RNG)
64
+ safe_state(args.quiet)
65
+
66
+ render_sets(model.extract(args), args.iteration, pipeline.extract(args), args.skip_train, args.skip_test)
gaussiansplatting/scene/__init__.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Copyright (C) 2023, Inria
3
+ # GRAPHDECO research group, https://team.inria.fr/graphdeco
4
+ # All rights reserved.
5
+ #
6
+ # This software is free for non-commercial, research and evaluation use
7
+ # under the terms of the LICENSE.md file.
8
+ #
9
+ # For inquiries contact george.drettakis@inria.fr
10
+ #
11
+
12
+ import os
13
+ import random
14
+ import json
15
+ from gaussiansplatting.utils.system_utils import searchForMaxIteration
16
+ from gaussiansplatting.scene.dataset_readers import sceneLoadTypeCallbacks
17
+ from gaussiansplatting.scene.gaussian_model import GaussianModel
18
+ from gaussiansplatting.arguments import ModelParams
19
+ from gaussiansplatting.utils.camera_utils import cameraList_from_camInfos, camera_to_JSON
20
+
21
+ class Scene:
22
+
23
+ gaussians : GaussianModel
24
+
25
+ def __init__(self, args : ModelParams, gaussians : GaussianModel, load_iteration=None, shuffle=True, resolution_scales=[1.0]):
26
+ """b
27
+ :param path: Path to colmap scene main folder.
28
+ """
29
+ self.model_path = args.model_path
30
+ self.loaded_iter = None
31
+ self.gaussians = gaussians
32
+
33
+ if load_iteration:
34
+ if load_iteration == -1:
35
+ self.loaded_iter = searchForMaxIteration(os.path.join(self.model_path, "point_cloud"))
36
+ else:
37
+ self.loaded_iter = load_iteration
38
+ print("Loading trained model at iteration {}".format(self.loaded_iter))
39
+
40
+ self.train_cameras = {}
41
+ self.test_cameras = {}
42
+
43
+ if os.path.exists(os.path.join(args.source_path, "sparse")):
44
+ scene_info = sceneLoadTypeCallbacks["Colmap"](args.source_path, args.images, args.eval)
45
+ elif os.path.exists(os.path.join(args.source_path, "transforms_train.json")):
46
+ print("Found transforms_train.json file, assuming Blender data set!")
47
+ scene_info = sceneLoadTypeCallbacks["Blender"](args.source_path, args.white_background, args.eval)
48
+ else:
49
+ assert False, "Could not recognize scene type!"
50
+
51
+ if not self.loaded_iter:
52
+ with open(scene_info.ply_path, 'rb') as src_file, open(os.path.join(self.model_path, "input.ply") , 'wb') as dest_file:
53
+ dest_file.write(src_file.read())
54
+ json_cams = []
55
+ camlist = []
56
+ if scene_info.test_cameras:
57
+ camlist.extend(scene_info.test_cameras)
58
+ if scene_info.train_cameras:
59
+ camlist.extend(scene_info.train_cameras)
60
+ for id, cam in enumerate(camlist):
61
+ json_cams.append(camera_to_JSON(id, cam))
62
+ with open(os.path.join(self.model_path, "cameras.json"), 'w') as file:
63
+ json.dump(json_cams, file)
64
+
65
+ if shuffle:
66
+ random.shuffle(scene_info.train_cameras) # Multi-res consistent random shuffling
67
+ random.shuffle(scene_info.test_cameras) # Multi-res consistent random shuffling
68
+
69
+ self.cameras_extent = scene_info.nerf_normalization["radius"]
70
+
71
+ for resolution_scale in resolution_scales:
72
+ print("Loading Training Cameras")
73
+ self.train_cameras[resolution_scale] = cameraList_from_camInfos(scene_info.train_cameras, resolution_scale, args)
74
+ print("Loading Test Cameras")
75
+ self.test_cameras[resolution_scale] = cameraList_from_camInfos(scene_info.test_cameras, resolution_scale, args)
76
+
77
+ if self.loaded_iter:
78
+ self.gaussians.load_ply(os.path.join(self.model_path,
79
+ "point_cloud",
80
+ "iteration_" + str(self.loaded_iter),
81
+ "point_cloud.ply"))
82
+ else:
83
+ self.gaussians.create_from_pcd(scene_info.point_cloud, self.cameras_extent)
84
+
85
+ def save(self, iteration):
86
+ point_cloud_path = os.path.join(self.model_path, "point_cloud/iteration_{}".format(iteration))
87
+ self.gaussians.save_ply(os.path.join(point_cloud_path, "point_cloud.ply"))
88
+
89
+ def getTrainCameras(self, scale=1.0):
90
+ return self.train_cameras[scale]
91
+
92
+ def getTestCameras(self, scale=1.0):
93
+ return self.test_cameras[scale]
gaussiansplatting/scene/cameras.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Copyright (C) 2023, Inria
3
+ # GRAPHDECO research group, https://team.inria.fr/graphdeco
4
+ # All rights reserved.
5
+ #
6
+ # This software is free for non-commercial, research and evaluation use
7
+ # under the terms of the LICENSE.md file.
8
+ #
9
+ # For inquiries contact george.drettakis@inria.fr
10
+ #
11
+
12
+ import torch
13
+ from torch import nn
14
+ import numpy as np
15
+ from gaussiansplatting.utils.graphics_utils import getWorld2View2, getProjectionMatrix, focal2fov, fov2focal,getWorld2View2_tensor,getWorld2View_tensor
16
+
17
+ class Camera(nn.Module):
18
+ def __init__(self, c2w, FoVy, height, width,
19
+ trans=torch.tensor([0.0, 0.0, 0.0]), scale=1.0, data_device = "cuda"
20
+ ):
21
+ super(Camera, self).__init__()
22
+ FoVx = focal2fov(fov2focal(FoVy, height), width)
23
+ # FoVx = focal2fov(fov2focal(FoVy, width), height)
24
+
25
+
26
+ R = c2w[:3, :3]
27
+ T = c2w[:3, 3]
28
+
29
+ self.R = R.float()
30
+ self.T = T.float()
31
+ self.FoVx = FoVx
32
+ self.FoVy = FoVy
33
+ self.image_height =height
34
+ self.image_width = width
35
+
36
+ try:
37
+ self.data_device = torch.device(data_device)
38
+ except Exception as e:
39
+ print(e)
40
+ print(f"[Warning] Custom device {data_device} failed, fallback to default cuda device" )
41
+ self.data_device = torch.device("cuda")
42
+
43
+
44
+ self.zfar = 100.0
45
+ self.znear = 0.01
46
+
47
+ self.trans = trans.float()
48
+ self.scale = scale
49
+
50
+ self.world_view_transform = getWorld2View2_tensor(R, T).transpose(0, 1).float().cuda()
51
+ self.projection_matrix = getProjectionMatrix(znear=self.znear, zfar=self.zfar, fovX=self.FoVx, fovY=self.FoVy).transpose(0,1).float().cuda()
52
+ self.full_proj_transform = (self.world_view_transform.unsqueeze(0).bmm(self.projection_matrix.unsqueeze(0))).squeeze(0).float()
53
+ self.camera_center = self.world_view_transform.inverse()[3, :3].float()
54
+ # print('self.camera_center',self.camera_center)
55
+
56
+ class MiniCam:
57
+ def __init__(self, width, height, fovy, fovx, znear, zfar, world_view_transform, full_proj_transform):
58
+ self.image_width = width
59
+ self.image_height = height
60
+ self.FoVy = fovy
61
+ self.FoVx = fovx
62
+ self.znear = znear
63
+ self.zfar = zfar
64
+ self.world_view_transform = world_view_transform
65
+ self.full_proj_transform = full_proj_transform
66
+ view_inv = torch.inverse(self.world_view_transform)
67
+ self.camera_center = view_inv[3][:3]
68
+
gaussiansplatting/scene/colmap_loader.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Copyright (C) 2023, Inria
3
+ # GRAPHDECO research group, https://team.inria.fr/graphdeco
4
+ # All rights reserved.
5
+ #
6
+ # This software is free for non-commercial, research and evaluation use
7
+ # under the terms of the LICENSE.md file.
8
+ #
9
+ # For inquiries contact george.drettakis@inria.fr
10
+ #
11
+
12
+ import numpy as np
13
+ import collections
14
+ import struct
15
+
16
+ CameraModel = collections.namedtuple(
17
+ "CameraModel", ["model_id", "model_name", "num_params"])
18
+ Camera = collections.namedtuple(
19
+ "Camera", ["id", "model", "width", "height", "params"])
20
+ BaseImage = collections.namedtuple(
21
+ "Image", ["id", "qvec", "tvec", "camera_id", "name", "xys", "point3D_ids"])
22
+ Point3D = collections.namedtuple(
23
+ "Point3D", ["id", "xyz", "rgb", "error", "image_ids", "point2D_idxs"])
24
+ CAMERA_MODELS = {
25
+ CameraModel(model_id=0, model_name="SIMPLE_PINHOLE", num_params=3),
26
+ CameraModel(model_id=1, model_name="PINHOLE", num_params=4),
27
+ CameraModel(model_id=2, model_name="SIMPLE_RADIAL", num_params=4),
28
+ CameraModel(model_id=3, model_name="RADIAL", num_params=5),
29
+ CameraModel(model_id=4, model_name="OPENCV", num_params=8),
30
+ CameraModel(model_id=5, model_name="OPENCV_FISHEYE", num_params=8),
31
+ CameraModel(model_id=6, model_name="FULL_OPENCV", num_params=12),
32
+ CameraModel(model_id=7, model_name="FOV", num_params=5),
33
+ CameraModel(model_id=8, model_name="SIMPLE_RADIAL_FISHEYE", num_params=4),
34
+ CameraModel(model_id=9, model_name="RADIAL_FISHEYE", num_params=5),
35
+ CameraModel(model_id=10, model_name="THIN_PRISM_FISHEYE", num_params=12)
36
+ }
37
+ CAMERA_MODEL_IDS = dict([(camera_model.model_id, camera_model)
38
+ for camera_model in CAMERA_MODELS])
39
+ CAMERA_MODEL_NAMES = dict([(camera_model.model_name, camera_model)
40
+ for camera_model in CAMERA_MODELS])
41
+
42
+
43
+ def qvec2rotmat(qvec):
44
+ return np.array([
45
+ [1 - 2 * qvec[2]**2 - 2 * qvec[3]**2,
46
+ 2 * qvec[1] * qvec[2] - 2 * qvec[0] * qvec[3],
47
+ 2 * qvec[3] * qvec[1] + 2 * qvec[0] * qvec[2]],
48
+ [2 * qvec[1] * qvec[2] + 2 * qvec[0] * qvec[3],
49
+ 1 - 2 * qvec[1]**2 - 2 * qvec[3]**2,
50
+ 2 * qvec[2] * qvec[3] - 2 * qvec[0] * qvec[1]],
51
+ [2 * qvec[3] * qvec[1] - 2 * qvec[0] * qvec[2],
52
+ 2 * qvec[2] * qvec[3] + 2 * qvec[0] * qvec[1],
53
+ 1 - 2 * qvec[1]**2 - 2 * qvec[2]**2]])
54
+
55
+ def rotmat2qvec(R):
56
+ Rxx, Ryx, Rzx, Rxy, Ryy, Rzy, Rxz, Ryz, Rzz = R.flat
57
+ K = np.array([
58
+ [Rxx - Ryy - Rzz, 0, 0, 0],
59
+ [Ryx + Rxy, Ryy - Rxx - Rzz, 0, 0],
60
+ [Rzx + Rxz, Rzy + Ryz, Rzz - Rxx - Ryy, 0],
61
+ [Ryz - Rzy, Rzx - Rxz, Rxy - Ryx, Rxx + Ryy + Rzz]]) / 3.0
62
+ eigvals, eigvecs = np.linalg.eigh(K)
63
+ qvec = eigvecs[[3, 0, 1, 2], np.argmax(eigvals)]
64
+ if qvec[0] < 0:
65
+ qvec *= -1
66
+ return qvec
67
+
68
+ class Image(BaseImage):
69
+ def qvec2rotmat(self):
70
+ return qvec2rotmat(self.qvec)
71
+
72
+ def read_next_bytes(fid, num_bytes, format_char_sequence, endian_character="<"):
73
+ """Read and unpack the next bytes from a binary file.
74
+ :param fid:
75
+ :param num_bytes: Sum of combination of {2, 4, 8}, e.g. 2, 6, 16, 30, etc.
76
+ :param format_char_sequence: List of {c, e, f, d, h, H, i, I, l, L, q, Q}.
77
+ :param endian_character: Any of {@, =, <, >, !}
78
+ :return: Tuple of read and unpacked values.
79
+ """
80
+ data = fid.read(num_bytes)
81
+ return struct.unpack(endian_character + format_char_sequence, data)
82
+
83
+ def read_points3D_text(path):
84
+ """
85
+ see: src/base/reconstruction.cc
86
+ void Reconstruction::ReadPoints3DText(const std::string& path)
87
+ void Reconstruction::WritePoints3DText(const std::string& path)
88
+ """
89
+ xyzs = None
90
+ rgbs = None
91
+ errors = None
92
+ with open(path, "r") as fid:
93
+ while True:
94
+ line = fid.readline()
95
+ if not line:
96
+ break
97
+ line = line.strip()
98
+ if len(line) > 0 and line[0] != "#":
99
+ elems = line.split()
100
+ xyz = np.array(tuple(map(float, elems[1:4])))
101
+ rgb = np.array(tuple(map(int, elems[4:7])))
102
+ error = np.array(float(elems[7]))
103
+ if xyzs is None:
104
+ xyzs = xyz[None, ...]
105
+ rgbs = rgb[None, ...]
106
+ errors = error[None, ...]
107
+ else:
108
+ xyzs = np.append(xyzs, xyz[None, ...], axis=0)
109
+ rgbs = np.append(rgbs, rgb[None, ...], axis=0)
110
+ errors = np.append(errors, error[None, ...], axis=0)
111
+ return xyzs, rgbs, errors
112
+
113
+ def read_points3D_binary(path_to_model_file):
114
+ """
115
+ see: src/base/reconstruction.cc
116
+ void Reconstruction::ReadPoints3DBinary(const std::string& path)
117
+ void Reconstruction::WritePoints3DBinary(const std::string& path)
118
+ """
119
+
120
+
121
+ with open(path_to_model_file, "rb") as fid:
122
+ num_points = read_next_bytes(fid, 8, "Q")[0]
123
+
124
+ xyzs = np.empty((num_points, 3))
125
+ rgbs = np.empty((num_points, 3))
126
+ errors = np.empty((num_points, 1))
127
+
128
+ for p_id in range(num_points):
129
+ binary_point_line_properties = read_next_bytes(
130
+ fid, num_bytes=43, format_char_sequence="QdddBBBd")
131
+ xyz = np.array(binary_point_line_properties[1:4])
132
+ rgb = np.array(binary_point_line_properties[4:7])
133
+ error = np.array(binary_point_line_properties[7])
134
+ track_length = read_next_bytes(
135
+ fid, num_bytes=8, format_char_sequence="Q")[0]
136
+ track_elems = read_next_bytes(
137
+ fid, num_bytes=8*track_length,
138
+ format_char_sequence="ii"*track_length)
139
+ xyzs[p_id] = xyz
140
+ rgbs[p_id] = rgb
141
+ errors[p_id] = error
142
+ return xyzs, rgbs, errors
143
+
144
+ def read_intrinsics_text(path):
145
+ """
146
+ Taken from https://github.com/colmap/colmap/blob/dev/scripts/python/read_write_model.py
147
+ """
148
+ cameras = {}
149
+ with open(path, "r") as fid:
150
+ while True:
151
+ line = fid.readline()
152
+ if not line:
153
+ break
154
+ line = line.strip()
155
+ if len(line) > 0 and line[0] != "#":
156
+ elems = line.split()
157
+ camera_id = int(elems[0])
158
+ model = elems[1]
159
+ assert model == "PINHOLE", "While the loader support other types, the rest of the code assumes PINHOLE"
160
+ width = int(elems[2])
161
+ height = int(elems[3])
162
+ params = np.array(tuple(map(float, elems[4:])))
163
+ cameras[camera_id] = Camera(id=camera_id, model=model,
164
+ width=width, height=height,
165
+ params=params)
166
+ return cameras
167
+
168
+ def read_extrinsics_binary(path_to_model_file):
169
+ """
170
+ see: src/base/reconstruction.cc
171
+ void Reconstruction::ReadImagesBinary(const std::string& path)
172
+ void Reconstruction::WriteImagesBinary(const std::string& path)
173
+ """
174
+ images = {}
175
+ with open(path_to_model_file, "rb") as fid:
176
+ num_reg_images = read_next_bytes(fid, 8, "Q")[0]
177
+ for _ in range(num_reg_images):
178
+ binary_image_properties = read_next_bytes(
179
+ fid, num_bytes=64, format_char_sequence="idddddddi")
180
+ image_id = binary_image_properties[0]
181
+ qvec = np.array(binary_image_properties[1:5])
182
+ tvec = np.array(binary_image_properties[5:8])
183
+ camera_id = binary_image_properties[8]
184
+ image_name = ""
185
+ current_char = read_next_bytes(fid, 1, "c")[0]
186
+ while current_char != b"\x00": # look for the ASCII 0 entry
187
+ image_name += current_char.decode("utf-8")
188
+ current_char = read_next_bytes(fid, 1, "c")[0]
189
+ num_points2D = read_next_bytes(fid, num_bytes=8,
190
+ format_char_sequence="Q")[0]
191
+ x_y_id_s = read_next_bytes(fid, num_bytes=24*num_points2D,
192
+ format_char_sequence="ddq"*num_points2D)
193
+ xys = np.column_stack([tuple(map(float, x_y_id_s[0::3])),
194
+ tuple(map(float, x_y_id_s[1::3]))])
195
+ point3D_ids = np.array(tuple(map(int, x_y_id_s[2::3])))
196
+ images[image_id] = Image(
197
+ id=image_id, qvec=qvec, tvec=tvec,
198
+ camera_id=camera_id, name=image_name,
199
+ xys=xys, point3D_ids=point3D_ids)
200
+ return images
201
+
202
+
203
+ def read_intrinsics_binary(path_to_model_file):
204
+ """
205
+ see: src/base/reconstruction.cc
206
+ void Reconstruction::WriteCamerasBinary(const std::string& path)
207
+ void Reconstruction::ReadCamerasBinary(const std::string& path)
208
+ """
209
+ cameras = {}
210
+ with open(path_to_model_file, "rb") as fid:
211
+ num_cameras = read_next_bytes(fid, 8, "Q")[0]
212
+ for _ in range(num_cameras):
213
+ camera_properties = read_next_bytes(
214
+ fid, num_bytes=24, format_char_sequence="iiQQ")
215
+ camera_id = camera_properties[0]
216
+ model_id = camera_properties[1]
217
+ model_name = CAMERA_MODEL_IDS[camera_properties[1]].model_name
218
+ width = camera_properties[2]
219
+ height = camera_properties[3]
220
+ num_params = CAMERA_MODEL_IDS[model_id].num_params
221
+ params = read_next_bytes(fid, num_bytes=8*num_params,
222
+ format_char_sequence="d"*num_params)
223
+ cameras[camera_id] = Camera(id=camera_id,
224
+ model=model_name,
225
+ width=width,
226
+ height=height,
227
+ params=np.array(params))
228
+ assert len(cameras) == num_cameras
229
+ return cameras
230
+
231
+
232
+ def read_extrinsics_text(path):
233
+ """
234
+ Taken from https://github.com/colmap/colmap/blob/dev/scripts/python/read_write_model.py
235
+ """
236
+ images = {}
237
+ with open(path, "r") as fid:
238
+ while True:
239
+ line = fid.readline()
240
+ if not line:
241
+ break
242
+ line = line.strip()
243
+ if len(line) > 0 and line[0] != "#":
244
+ elems = line.split()
245
+ image_id = int(elems[0])
246
+ qvec = np.array(tuple(map(float, elems[1:5])))
247
+ tvec = np.array(tuple(map(float, elems[5:8])))
248
+ camera_id = int(elems[8])
249
+ image_name = elems[9]
250
+ elems = fid.readline().split()
251
+ xys = np.column_stack([tuple(map(float, elems[0::3])),
252
+ tuple(map(float, elems[1::3]))])
253
+ point3D_ids = np.array(tuple(map(int, elems[2::3])))
254
+ images[image_id] = Image(
255
+ id=image_id, qvec=qvec, tvec=tvec,
256
+ camera_id=camera_id, name=image_name,
257
+ xys=xys, point3D_ids=point3D_ids)
258
+ return images
259
+
260
+
261
+ def read_colmap_bin_array(path):
262
+ """
263
+ Taken from https://github.com/colmap/colmap/blob/dev/scripts/python/read_dense.py
264
+
265
+ :param path: path to the colmap binary file.
266
+ :return: nd array with the floating point values in the value
267
+ """
268
+ with open(path, "rb") as fid:
269
+ width, height, channels = np.genfromtxt(fid, delimiter="&", max_rows=1,
270
+ usecols=(0, 1, 2), dtype=int)
271
+ fid.seek(0)
272
+ num_delimiter = 0
273
+ byte = fid.read(1)
274
+ while True:
275
+ if byte == b"&":
276
+ num_delimiter += 1
277
+ if num_delimiter >= 3:
278
+ break
279
+ byte = fid.read(1)
280
+ array = np.fromfile(fid, np.float32)
281
+ array = array.reshape((width, height, channels), order="F")
282
+ return np.transpose(array, (1, 0, 2)).squeeze()
gaussiansplatting/scene/dataset_readers.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Copyright (C) 2023, Inria
3
+ # GRAPHDECO research group, https://team.inria.fr/graphdeco
4
+ # All rights reserved.
5
+ #
6
+ # This software is free for non-commercial, research and evaluation use
7
+ # under the terms of the LICENSE.md file.
8
+ #
9
+ # For inquiries contact george.drettakis@inria.fr
10
+ #
11
+
12
+ import os
13
+ import sys
14
+ from PIL import Image
15
+ from typing import NamedTuple
16
+ from gaussiansplatting.scene.colmap_loader import read_extrinsics_text, read_intrinsics_text, qvec2rotmat, \
17
+ read_extrinsics_binary, read_intrinsics_binary, read_points3D_binary, read_points3D_text
18
+ from gaussiansplatting.utils.graphics_utils import getWorld2View2, focal2fov, fov2focal
19
+ import numpy as np
20
+ import json
21
+ from pathlib import Path
22
+ from plyfile import PlyData, PlyElement
23
+ from gaussiansplatting.utils.sh_utils import SH2RGB
24
+ from gaussiansplatting.scene.gaussian_model import BasicPointCloud
25
+
26
+ class CameraInfo(NamedTuple):
27
+ uid: int
28
+ R: np.array
29
+ T: np.array
30
+ FovY: np.array
31
+ FovX: np.array
32
+ image: np.array
33
+ image_path: str
34
+ image_name: str
35
+ width: int
36
+ height: int
37
+
38
+ class SceneInfo(NamedTuple):
39
+ point_cloud: BasicPointCloud
40
+ train_cameras: list
41
+ test_cameras: list
42
+ nerf_normalization: dict
43
+ ply_path: str
44
+
45
+ def getNerfppNorm(cam_info):
46
+ def get_center_and_diag(cam_centers):
47
+ cam_centers = np.hstack(cam_centers)
48
+ avg_cam_center = np.mean(cam_centers, axis=1, keepdims=True)
49
+ center = avg_cam_center
50
+ dist = np.linalg.norm(cam_centers - center, axis=0, keepdims=True)
51
+ diagonal = np.max(dist)
52
+ return center.flatten(), diagonal
53
+
54
+ cam_centers = []
55
+
56
+ for cam in cam_info:
57
+ W2C = getWorld2View2(cam.R, cam.T)
58
+ C2W = np.linalg.inv(W2C)
59
+ cam_centers.append(C2W[:3, 3:4])
60
+
61
+ center, diagonal = get_center_and_diag(cam_centers)
62
+ radius = diagonal * 1.1
63
+
64
+ translate = -center
65
+
66
+ return {"translate": translate, "radius": radius}
67
+
68
+ def readColmapCameras(cam_extrinsics, cam_intrinsics, images_folder):
69
+ cam_infos = []
70
+ for idx, key in enumerate(cam_extrinsics):
71
+ sys.stdout.write('\r')
72
+ # the exact output you're looking for:
73
+ sys.stdout.write("Reading camera {}/{}".format(idx+1, len(cam_extrinsics)))
74
+ sys.stdout.flush()
75
+
76
+ extr = cam_extrinsics[key]
77
+ intr = cam_intrinsics[extr.camera_id]
78
+ height = intr.height
79
+ width = intr.width
80
+
81
+ uid = intr.id
82
+ R = np.transpose(qvec2rotmat(extr.qvec))
83
+ T = np.array(extr.tvec)
84
+
85
+ if intr.model=="SIMPLE_PINHOLE":
86
+ focal_length_x = intr.params[0]
87
+ FovY = focal2fov(focal_length_x, height)
88
+ FovX = focal2fov(focal_length_x, width)
89
+ elif intr.model=="PINHOLE":
90
+ focal_length_x = intr.params[0]
91
+ focal_length_y = intr.params[1]
92
+ FovY = focal2fov(focal_length_y, height)
93
+ FovX = focal2fov(focal_length_x, width)
94
+ else:
95
+ assert False, "Colmap camera model not handled: only undistorted datasets (PINHOLE or SIMPLE_PINHOLE cameras) supported!"
96
+
97
+ image_path = os.path.join(images_folder, os.path.basename(extr.name))
98
+ image_name = os.path.basename(image_path).split(".")[0]
99
+ image = Image.open(image_path)
100
+
101
+ cam_info = CameraInfo(uid=uid, R=R, T=T, FovY=FovY, FovX=FovX, image=image,
102
+ image_path=image_path, image_name=image_name, width=width, height=height)
103
+ cam_infos.append(cam_info)
104
+ sys.stdout.write('\n')
105
+ return cam_infos
106
+
107
+ def fetchPly(path):
108
+ plydata = PlyData.read(path)
109
+ vertices = plydata['vertex']
110
+ positions = np.vstack([vertices['x'], vertices['y'], vertices['z']]).T
111
+ colors = np.vstack([vertices['red'], vertices['green'], vertices['blue']]).T / 255.0
112
+ normals = np.vstack([vertices['nx'], vertices['ny'], vertices['nz']]).T
113
+ return BasicPointCloud(points=positions, colors=colors, normals=normals)
114
+
115
+ def storePly(path, xyz, rgb):
116
+ # Define the dtype for the structured array
117
+ dtype = [('x', 'f4'), ('y', 'f4'), ('z', 'f4'),
118
+ ('nx', 'f4'), ('ny', 'f4'), ('nz', 'f4'),
119
+ ('red', 'u1'), ('green', 'u1'), ('blue', 'u1')]
120
+
121
+ normals = np.zeros_like(xyz)
122
+
123
+ elements = np.empty(xyz.shape[0], dtype=dtype)
124
+ attributes = np.concatenate((xyz, normals, rgb), axis=1)
125
+ elements[:] = list(map(tuple, attributes))
126
+
127
+ # Create the PlyData object and write to file
128
+ vertex_element = PlyElement.describe(elements, 'vertex')
129
+ ply_data = PlyData([vertex_element])
130
+ ply_data.write(path)
131
+
132
+ def readColmapSceneInfo(path, images, eval, llffhold=8):
133
+ try:
134
+ cameras_extrinsic_file = os.path.join(path, "sparse/0", "images.bin")
135
+ cameras_intrinsic_file = os.path.join(path, "sparse/0", "cameras.bin")
136
+ cam_extrinsics = read_extrinsics_binary(cameras_extrinsic_file)
137
+ cam_intrinsics = read_intrinsics_binary(cameras_intrinsic_file)
138
+ except:
139
+ cameras_extrinsic_file = os.path.join(path, "sparse/0", "images.txt")
140
+ cameras_intrinsic_file = os.path.join(path, "sparse/0", "cameras.txt")
141
+ cam_extrinsics = read_extrinsics_text(cameras_extrinsic_file)
142
+ cam_intrinsics = read_intrinsics_text(cameras_intrinsic_file)
143
+
144
+ reading_dir = "images" if images == None else images
145
+ cam_infos_unsorted = readColmapCameras(cam_extrinsics=cam_extrinsics, cam_intrinsics=cam_intrinsics, images_folder=os.path.join(path, reading_dir))
146
+ cam_infos = sorted(cam_infos_unsorted.copy(), key = lambda x : x.image_name)
147
+
148
+ if eval:
149
+ train_cam_infos = [c for idx, c in enumerate(cam_infos) if idx % llffhold != 0]
150
+ test_cam_infos = [c for idx, c in enumerate(cam_infos) if idx % llffhold == 0]
151
+ else:
152
+ train_cam_infos = cam_infos
153
+ test_cam_infos = []
154
+
155
+ nerf_normalization = getNerfppNorm(train_cam_infos)
156
+
157
+ ply_path = os.path.join(path, "sparse/0/points3D.ply")
158
+ bin_path = os.path.join(path, "sparse/0/points3D.bin")
159
+ txt_path = os.path.join(path, "sparse/0/points3D.txt")
160
+ if not os.path.exists(ply_path):
161
+ print("Converting point3d.bin to .ply, will happen only the first time you open the scene.")
162
+ try:
163
+ xyz, rgb, _ = read_points3D_binary(bin_path)
164
+ except:
165
+ xyz, rgb, _ = read_points3D_text(txt_path)
166
+ storePly(ply_path, xyz, rgb)
167
+ try:
168
+ pcd = fetchPly(ply_path)
169
+ except:
170
+ pcd = None
171
+
172
+ scene_info = SceneInfo(point_cloud=pcd,
173
+ train_cameras=train_cam_infos,
174
+ test_cameras=test_cam_infos,
175
+ nerf_normalization=nerf_normalization,
176
+ ply_path=ply_path)
177
+ return scene_info
178
+
179
+ def readCamerasFromTransforms(path, transformsfile, white_background, extension=".png"):
180
+ cam_infos = []
181
+
182
+ with open(os.path.join(path, transformsfile)) as json_file:
183
+ contents = json.load(json_file)
184
+ fovx = contents["camera_angle_x"]
185
+
186
+ frames = contents["frames"]
187
+ for idx, frame in enumerate(frames):
188
+ cam_name = os.path.join(path, frame["file_path"] + extension)
189
+
190
+ matrix = np.linalg.inv(np.array(frame["transform_matrix"]))
191
+ R = -np.transpose(matrix[:3,:3])
192
+ R[:,0] = -R[:,0]
193
+ T = -matrix[:3, 3]
194
+
195
+ image_path = os.path.join(path, cam_name)
196
+ image_name = Path(cam_name).stem
197
+ image = Image.open(image_path)
198
+
199
+ im_data = np.array(image.convert("RGBA"))
200
+
201
+ bg = np.array([1,1,1]) if white_background else np.array([0, 0, 0])
202
+
203
+ norm_data = im_data / 255.0
204
+ arr = norm_data[:,:,:3] * norm_data[:, :, 3:4] + bg * (1 - norm_data[:, :, 3:4])
205
+ image = Image.fromarray(np.array(arr*255.0, dtype=np.byte), "RGB")
206
+
207
+ fovy = focal2fov(fov2focal(fovx, image.size[0]), image.size[1])
208
+ FovY = fovy
209
+ FovX = fovx
210
+
211
+ cam_infos.append(CameraInfo(uid=idx, R=R, T=T, FovY=FovY, FovX=FovX, image=image,
212
+ image_path=image_path, image_name=image_name, width=image.size[0], height=image.size[1]))
213
+
214
+ return cam_infos
215
+
216
+ def readNerfSyntheticInfo(path, white_background, eval, extension=".png"):
217
+ print("Reading Training Transforms")
218
+ train_cam_infos = readCamerasFromTransforms(path, "transforms_train.json", white_background, extension)
219
+ print("Reading Test Transforms")
220
+ test_cam_infos = readCamerasFromTransforms(path, "transforms_test.json", white_background, extension)
221
+
222
+ if not eval:
223
+ train_cam_infos.extend(test_cam_infos)
224
+ test_cam_infos = []
225
+
226
+ nerf_normalization = getNerfppNorm(train_cam_infos)
227
+
228
+ ply_path = os.path.join(path, "points3d.ply")
229
+ if not os.path.exists(ply_path):
230
+ # Since this data set has no colmap data, we start with random points
231
+ num_pts = 100_000
232
+ print(f"Generating random point cloud ({num_pts})...")
233
+
234
+ # We create random points inside the bounds of the synthetic Blender scenes
235
+ xyz = np.random.random((num_pts, 3)) * 2.6 - 1.3
236
+ shs = np.random.random((num_pts, 3)) / 255.0
237
+ pcd = BasicPointCloud(points=xyz, colors=SH2RGB(shs), normals=np.zeros((num_pts, 3)))
238
+
239
+ storePly(ply_path, xyz, SH2RGB(shs) * 255)
240
+ try:
241
+ pcd = fetchPly(ply_path)
242
+ except:
243
+ pcd = None
244
+
245
+ scene_info = SceneInfo(point_cloud=pcd,
246
+ train_cameras=train_cam_infos,
247
+ test_cameras=test_cam_infos,
248
+ nerf_normalization=nerf_normalization,
249
+ ply_path=ply_path)
250
+ return scene_info
251
+
252
+ sceneLoadTypeCallbacks = {
253
+ "Colmap": readColmapSceneInfo,
254
+ "Blender" : readNerfSyntheticInfo
255
+ }
gaussiansplatting/scene/gaussian_model.py ADDED
@@ -0,0 +1,419 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Copyright (C) 2023, Inria
3
+ # GRAPHDECO research group, https://team.inria.fr/graphdeco
4
+ # All rights reserved.
5
+ #
6
+ # This software is free for non-commercial, research and evaluation use
7
+ # under the terms of the LICENSE.md file.
8
+ #
9
+ # For inquiries contact george.drettakis@inria.fr
10
+ #
11
+
12
+ import torch
13
+ import numpy as np
14
+ from gaussiansplatting.utils.general_utils import inverse_sigmoid, get_expon_lr_func, build_rotation
15
+ from torch import nn
16
+ import os
17
+ from gaussiansplatting.utils.system_utils import mkdir_p
18
+ from plyfile import PlyData, PlyElement
19
+ from gaussiansplatting.utils.sh_utils import RGB2SH
20
+ from simple_knn._C import distCUDA2
21
+ from gaussiansplatting.utils.graphics_utils import BasicPointCloud
22
+ from gaussiansplatting.utils.general_utils import strip_symmetric, build_scaling_rotation
23
+
24
+ class GaussianModel:
25
+
26
+ def setup_functions(self):
27
+ def build_covariance_from_scaling_rotation(scaling, scaling_modifier, rotation):
28
+ L = build_scaling_rotation(scaling_modifier * scaling, rotation)
29
+ actual_covariance = L @ L.transpose(1, 2)
30
+ symm = strip_symmetric(actual_covariance)
31
+ return symm
32
+
33
+ self.scaling_activation = torch.exp
34
+ self.scaling_inverse_activation = torch.log
35
+
36
+ self.covariance_activation = build_covariance_from_scaling_rotation
37
+
38
+ self.opacity_activation = torch.sigmoid
39
+ self.inverse_opacity_activation = inverse_sigmoid
40
+
41
+ self.rotation_activation = torch.nn.functional.normalize
42
+
43
+
44
+ def __init__(self, sh_degree : int):
45
+ self.active_sh_degree = 0
46
+ self.max_sh_degree = sh_degree
47
+ self._xyz = torch.empty(0)
48
+ self._features_dc = torch.empty(0)
49
+ self._features_rest = torch.empty(0)
50
+ self._scaling = torch.empty(0)
51
+ self._rotation = torch.empty(0)
52
+ self._opacity = torch.empty(0)
53
+ self.max_radii2D = torch.empty(0)
54
+ self.xyz_gradient_accum = torch.empty(0)
55
+ self.denom = torch.empty(0)
56
+ self.optimizer = None
57
+ self.percent_dense = 0
58
+ self.spatial_lr_scale = 0
59
+ self.setup_functions()
60
+
61
+ def capture(self):
62
+ return (
63
+ self.active_sh_degree,
64
+ self._xyz,
65
+ self._features_dc,
66
+ self._features_rest,
67
+ self._scaling,
68
+ self._rotation,
69
+ self._opacity,
70
+ self.max_radii2D,
71
+ self.xyz_gradient_accum,
72
+ self.denom,
73
+ self.optimizer.state_dict(),
74
+ self.spatial_lr_scale,
75
+ )
76
+
77
+ def restore(self, model_args, training_args):
78
+ (self.active_sh_degree,
79
+ self._xyz,
80
+ self._features_dc,
81
+ self._features_rest,
82
+ self._scaling,
83
+ self._rotation,
84
+ self._opacity,
85
+ self.max_radii2D,
86
+ xyz_gradient_accum,
87
+ denom,
88
+ opt_dict,
89
+ self.spatial_lr_scale) = model_args
90
+ self.training_setup(training_args)
91
+ self.xyz_gradient_accum = xyz_gradient_accum
92
+ self.denom = denom
93
+ self.optimizer.load_state_dict(opt_dict)
94
+
95
+ @property
96
+ def get_scaling(self):
97
+ return self.scaling_activation(self._scaling)
98
+
99
+ @property
100
+ def get_rotation(self):
101
+ return self.rotation_activation(self._rotation)
102
+
103
+ @property
104
+ def get_xyz(self):
105
+ return self._xyz
106
+
107
+ @property
108
+ def get_features(self):
109
+ features_dc = self._features_dc
110
+ features_rest = self._features_rest
111
+ return torch.cat((features_dc, features_rest), dim=1)
112
+
113
+ @property
114
+ def get_opacity(self):
115
+ return self.opacity_activation(self._opacity)
116
+
117
+ def get_covariance(self, scaling_modifier = 1):
118
+ return self.covariance_activation(self.get_scaling, scaling_modifier, self._rotation)
119
+
120
+ def oneupSHdegree(self):
121
+ if self.active_sh_degree < self.max_sh_degree:
122
+ self.active_sh_degree += 1
123
+
124
+ def create_from_pcd(self, pcd : BasicPointCloud, spatial_lr_scale : float):
125
+ self.spatial_lr_scale = spatial_lr_scale
126
+ fused_point_cloud = torch.tensor(np.asarray(pcd.points)).float().cuda()
127
+ fused_color = RGB2SH(torch.tensor(np.asarray(pcd.colors)).float().cuda())
128
+ features = torch.zeros((fused_color.shape[0], 3, (self.max_sh_degree + 1) ** 2)).float().cuda()
129
+ features[:, :3, 0 ] = fused_color
130
+ features[:, 3:, 1:] = 0.0
131
+
132
+ print("Number of points at initialisation : ", fused_point_cloud.shape[0])
133
+
134
+ dist2 = torch.clamp_min(distCUDA2(torch.from_numpy(np.asarray(pcd.points)).float().cuda()), 0.0000001)
135
+ scales = torch.log(torch.sqrt(dist2))[...,None].repeat(1, 3)
136
+ rots = torch.zeros((fused_point_cloud.shape[0], 4), device="cuda")
137
+ rots[:, 0] = 1
138
+
139
+ opacities = inverse_sigmoid(0.1 * torch.ones((fused_point_cloud.shape[0], 1), dtype=torch.float, device="cuda"))
140
+
141
+ self._xyz = nn.Parameter(fused_point_cloud.requires_grad_(True))
142
+ self._features_dc = nn.Parameter(features[:,:,0:1].transpose(1, 2).contiguous().requires_grad_(True))
143
+ self._features_rest = nn.Parameter(features[:,:,1:].transpose(1, 2).contiguous().requires_grad_(True))
144
+ self._scaling = nn.Parameter(scales.requires_grad_(True))
145
+ self._rotation = nn.Parameter(rots.requires_grad_(True))
146
+ self._opacity = nn.Parameter(opacities.requires_grad_(True))
147
+ self.max_radii2D = torch.zeros((self.get_xyz.shape[0]), device="cuda")
148
+
149
+ def training_setup(self, training_args):
150
+ self.percent_dense = training_args.percent_dense
151
+ self.xyz_gradient_accum = torch.zeros((self.get_xyz.shape[0], 1), device="cuda")
152
+ self.denom = torch.zeros((self.get_xyz.shape[0], 1), device="cuda")
153
+
154
+ scale = 1.0
155
+ scale_small = 1.0
156
+ l = [
157
+ {'params': [self._xyz], 'lr': training_args.position_lr_init * self.spatial_lr_scale * scale_small, "name": "xyz"},
158
+ {'params': [self._features_dc], 'lr': training_args.feature_lr* scale, "name": "f_dc"},
159
+ {'params': [self._features_rest], 'lr': training_args.feature_lr * scale/ 20.0, "name": "f_rest"},
160
+ {'params': [self._opacity], 'lr': training_args.opacity_lr* scale_small, "name": "opacity"},
161
+ {'params': [self._scaling], 'lr': training_args.scaling_lr* scale_small, "name": "scaling"},
162
+ {'params': [self._rotation], 'lr': training_args.rotation_lr* scale_small, "name": "rotation"}
163
+ ]
164
+ self.params_list = l
165
+ self.optimizer = torch.optim.Adam(l, lr=0.0, eps=1e-15)
166
+ self.xyz_scheduler_args = get_expon_lr_func(lr_init=training_args.position_lr_init*self.spatial_lr_scale* scale_small,
167
+ lr_final=training_args.position_lr_final*self.spatial_lr_scale* scale_small,
168
+ lr_delay_mult=training_args.position_lr_delay_mult,
169
+ max_steps=training_args.position_lr_max_steps)
170
+
171
+ def update_learning_rate(self, iteration):
172
+ ''' Learning rate scheduling per step '''
173
+ for param_group in self.optimizer.param_groups:
174
+ if param_group["name"] == "xyz":
175
+ lr = self.xyz_scheduler_args(iteration)
176
+ param_group['lr'] = lr
177
+ # print("xyz lr : ", lr)
178
+ # if param_group["name"] == "f_dc":
179
+ # # import pdb; pdb.set_trace()
180
+ # param_group['lr'] = param_group['lr'] * ((0.5) ** (1.0 / 1200.0))
181
+ # if param_group["name"] == "f_rest":
182
+ # # import pdb; pdb.set_trace()
183
+ # param_group['lr'] = param_group['lr'] * ((0.5) ** (1.0 / 1200.0))
184
+
185
+
186
+
187
+ def construct_list_of_attributes(self):
188
+ l = ['x', 'y', 'z', 'nx', 'ny', 'nz']
189
+ # All channels except the 3 DC
190
+ for i in range(self._features_dc.shape[1]*self._features_dc.shape[2]):
191
+ l.append('f_dc_{}'.format(i))
192
+ for i in range(self._features_rest.shape[1]*self._features_rest.shape[2]):
193
+ l.append('f_rest_{}'.format(i))
194
+ l.append('opacity')
195
+ for i in range(self._scaling.shape[1]):
196
+ l.append('scale_{}'.format(i))
197
+ for i in range(self._rotation.shape[1]):
198
+ l.append('rot_{}'.format(i))
199
+ return l
200
+
201
+ def save_ply(self, path):
202
+ mkdir_p(os.path.dirname(path))
203
+
204
+ xyz = self._xyz.detach().cpu().numpy()
205
+ normals = np.zeros_like(xyz)
206
+ f_dc = self._features_dc.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()
207
+ f_rest = self._features_rest.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()
208
+ opacities = self._opacity.detach().cpu().numpy()
209
+ scale = self._scaling.detach().cpu().numpy()
210
+ rotation = self._rotation.detach().cpu().numpy()
211
+
212
+ dtype_full = [(attribute, 'f4') for attribute in self.construct_list_of_attributes()]
213
+
214
+ elements = np.empty(xyz.shape[0], dtype=dtype_full)
215
+ attributes = np.concatenate((xyz, normals, f_dc, f_rest, opacities, scale, rotation), axis=1)
216
+ elements[:] = list(map(tuple, attributes))
217
+ el = PlyElement.describe(elements, 'vertex')
218
+ PlyData([el]).write(path)
219
+
220
+ def reset_opacity(self):
221
+ opacities_new = inverse_sigmoid(torch.min(self.get_opacity, torch.ones_like(self.get_opacity)*0.01))
222
+ optimizable_tensors = self.replace_tensor_to_optimizer(opacities_new, "opacity")
223
+ self._opacity = optimizable_tensors["opacity"]
224
+
225
+ def load_ply(self, path):
226
+ plydata = PlyData.read(path)
227
+
228
+ xyz = np.stack((np.asarray(plydata.elements[0]["x"]),
229
+ np.asarray(plydata.elements[0]["y"]),
230
+ np.asarray(plydata.elements[0]["z"])), axis=1)
231
+ opacities = np.asarray(plydata.elements[0]["opacity"])[..., np.newaxis]
232
+
233
+ features_dc = np.zeros((xyz.shape[0], 3, 1))
234
+ features_dc[:, 0, 0] = np.asarray(plydata.elements[0]["f_dc_0"])
235
+ features_dc[:, 1, 0] = np.asarray(plydata.elements[0]["f_dc_1"])
236
+ features_dc[:, 2, 0] = np.asarray(plydata.elements[0]["f_dc_2"])
237
+
238
+ extra_f_names = [p.name for p in plydata.elements[0].properties if p.name.startswith("f_rest_")]
239
+ extra_f_names = sorted(extra_f_names, key = lambda x: int(x.split('_')[-1]))
240
+ assert len(extra_f_names)==3*(self.max_sh_degree + 1) ** 2 - 3
241
+ features_extra = np.zeros((xyz.shape[0], len(extra_f_names)))
242
+ for idx, attr_name in enumerate(extra_f_names):
243
+ features_extra[:, idx] = np.asarray(plydata.elements[0][attr_name])
244
+ # Reshape (P,F*SH_coeffs) to (P, F, SH_coeffs except DC)
245
+ features_extra = features_extra.reshape((features_extra.shape[0], 3, (self.max_sh_degree + 1) ** 2 - 1))
246
+
247
+ scale_names = [p.name for p in plydata.elements[0].properties if p.name.startswith("scale_")]
248
+ scale_names = sorted(scale_names, key = lambda x: int(x.split('_')[-1]))
249
+ scales = np.zeros((xyz.shape[0], len(scale_names)))
250
+ for idx, attr_name in enumerate(scale_names):
251
+ scales[:, idx] = np.asarray(plydata.elements[0][attr_name])
252
+
253
+ rot_names = [p.name for p in plydata.elements[0].properties if p.name.startswith("rot")]
254
+ rot_names = sorted(rot_names, key = lambda x: int(x.split('_')[-1]))
255
+ rots = np.zeros((xyz.shape[0], len(rot_names)))
256
+ for idx, attr_name in enumerate(rot_names):
257
+ rots[:, idx] = np.asarray(plydata.elements[0][attr_name])
258
+
259
+ self._xyz = nn.Parameter(torch.tensor(xyz, dtype=torch.float, device="cuda").requires_grad_(True))
260
+ self._features_dc = nn.Parameter(torch.tensor(features_dc, dtype=torch.float, device="cuda").transpose(1, 2).contiguous().requires_grad_(True))
261
+ self._features_rest = nn.Parameter(torch.tensor(features_extra, dtype=torch.float, device="cuda").transpose(1, 2).contiguous().requires_grad_(True))
262
+ self._opacity = nn.Parameter(torch.tensor(opacities, dtype=torch.float, device="cuda").requires_grad_(True))
263
+ self._scaling = nn.Parameter(torch.tensor(scales, dtype=torch.float, device="cuda").requires_grad_(True))
264
+ self._rotation = nn.Parameter(torch.tensor(rots, dtype=torch.float, device="cuda").requires_grad_(True))
265
+
266
+ self.active_sh_degree = self.max_sh_degree
267
+
268
+ def replace_tensor_to_optimizer(self, tensor, name):
269
+ optimizable_tensors = {}
270
+ for group in self.optimizer.param_groups:
271
+ if group["name"] == name:
272
+ stored_state = self.optimizer.state.get(group['params'][0], None)
273
+ stored_state["exp_avg"] = torch.zeros_like(tensor)
274
+ stored_state["exp_avg_sq"] = torch.zeros_like(tensor)
275
+
276
+ del self.optimizer.state[group['params'][0]]
277
+ group["params"][0] = nn.Parameter(tensor.requires_grad_(True))
278
+ self.optimizer.state[group['params'][0]] = stored_state
279
+
280
+ optimizable_tensors[group["name"]] = group["params"][0]
281
+ return optimizable_tensors
282
+
283
+ def _prune_optimizer(self, mask):
284
+ optimizable_tensors = {}
285
+ for group in self.optimizer.param_groups:
286
+ stored_state = self.optimizer.state.get(group['params'][0], None)
287
+ if stored_state is not None:
288
+ stored_state["exp_avg"] = stored_state["exp_avg"][mask]
289
+ stored_state["exp_avg_sq"] = stored_state["exp_avg_sq"][mask]
290
+
291
+ del self.optimizer.state[group['params'][0]]
292
+ group["params"][0] = nn.Parameter((group["params"][0][mask].requires_grad_(True)))
293
+ self.optimizer.state[group['params'][0]] = stored_state
294
+
295
+ optimizable_tensors[group["name"]] = group["params"][0]
296
+ else:
297
+ group["params"][0] = nn.Parameter(group["params"][0][mask].requires_grad_(True))
298
+ optimizable_tensors[group["name"]] = group["params"][0]
299
+ return optimizable_tensors
300
+
301
+ def prune_points(self, mask):
302
+ valid_points_mask = ~mask
303
+ optimizable_tensors = self._prune_optimizer(valid_points_mask)
304
+
305
+ self._xyz = optimizable_tensors["xyz"]
306
+ self._features_dc = optimizable_tensors["f_dc"]
307
+ self._features_rest = optimizable_tensors["f_rest"]
308
+ self._opacity = optimizable_tensors["opacity"]
309
+ self._scaling = optimizable_tensors["scaling"]
310
+ self._rotation = optimizable_tensors["rotation"]
311
+
312
+ self.xyz_gradient_accum = self.xyz_gradient_accum[valid_points_mask]
313
+
314
+ self.denom = self.denom[valid_points_mask]
315
+ self.max_radii2D = self.max_radii2D[valid_points_mask]
316
+
317
+ def cat_tensors_to_optimizer(self, tensors_dict):
318
+ optimizable_tensors = {}
319
+ for group in self.optimizer.param_groups:
320
+ assert len(group["params"]) == 1
321
+ extension_tensor = tensors_dict[group["name"]]
322
+ stored_state = self.optimizer.state.get(group['params'][0], None)
323
+ if stored_state is not None:
324
+
325
+ stored_state["exp_avg"] = torch.cat((stored_state["exp_avg"], torch.zeros_like(extension_tensor)), dim=0)
326
+ stored_state["exp_avg_sq"] = torch.cat((stored_state["exp_avg_sq"], torch.zeros_like(extension_tensor)), dim=0)
327
+
328
+ del self.optimizer.state[group['params'][0]]
329
+ group["params"][0] = nn.Parameter(torch.cat((group["params"][0], extension_tensor), dim=0).requires_grad_(True))
330
+ self.optimizer.state[group['params'][0]] = stored_state
331
+
332
+ optimizable_tensors[group["name"]] = group["params"][0]
333
+ else:
334
+ group["params"][0] = nn.Parameter(torch.cat((group["params"][0], extension_tensor), dim=0).requires_grad_(True))
335
+ optimizable_tensors[group["name"]] = group["params"][0]
336
+
337
+ return optimizable_tensors
338
+
339
+ def densification_postfix(self, new_xyz, new_features_dc, new_features_rest, new_opacities, new_scaling, new_rotation):
340
+ d = {"xyz": new_xyz,
341
+ "f_dc": new_features_dc,
342
+ "f_rest": new_features_rest,
343
+ "opacity": new_opacities,
344
+ "scaling" : new_scaling,
345
+ "rotation" : new_rotation}
346
+
347
+ optimizable_tensors = self.cat_tensors_to_optimizer(d)
348
+ self._xyz = optimizable_tensors["xyz"]
349
+ self._features_dc = optimizable_tensors["f_dc"]
350
+ self._features_rest = optimizable_tensors["f_rest"]
351
+ self._opacity = optimizable_tensors["opacity"]
352
+ self._scaling = optimizable_tensors["scaling"]
353
+ self._rotation = optimizable_tensors["rotation"]
354
+
355
+ self.xyz_gradient_accum = torch.zeros((self.get_xyz.shape[0], 1), device="cuda")
356
+ self.denom = torch.zeros((self.get_xyz.shape[0], 1), device="cuda")
357
+ self.max_radii2D = torch.zeros((self.get_xyz.shape[0]), device="cuda")
358
+
359
+ def densify_and_split(self, grads, grad_threshold, scene_extent, N=2):
360
+ n_init_points = self.get_xyz.shape[0]
361
+ # Extract points that satisfy the gradient condition
362
+ padded_grad = torch.zeros((n_init_points), device="cuda")
363
+ padded_grad[:grads.shape[0]] = grads.squeeze()
364
+ selected_pts_mask = torch.where(padded_grad >= grad_threshold, True, False)
365
+ selected_pts_mask = torch.logical_and(selected_pts_mask,
366
+ torch.max(self.get_scaling, dim=1).values > self.percent_dense*scene_extent)
367
+
368
+ stds = self.get_scaling[selected_pts_mask].repeat(N,1)
369
+ means =torch.zeros((stds.size(0), 3),device="cuda")
370
+ samples = torch.normal(mean=means, std=stds)
371
+ rots = build_rotation(self._rotation[selected_pts_mask]).repeat(N,1,1)
372
+ new_xyz = torch.bmm(rots, samples.unsqueeze(-1)).squeeze(-1) + self.get_xyz[selected_pts_mask].repeat(N, 1)
373
+ new_scaling = self.scaling_inverse_activation(self.get_scaling[selected_pts_mask].repeat(N,1) / (0.8*N))
374
+ new_rotation = self._rotation[selected_pts_mask].repeat(N,1)
375
+ new_features_dc = self._features_dc[selected_pts_mask].repeat(N,1,1)
376
+ new_features_rest = self._features_rest[selected_pts_mask].repeat(N,1,1)
377
+ new_opacity = self._opacity[selected_pts_mask].repeat(N,1)
378
+
379
+ self.densification_postfix(new_xyz, new_features_dc, new_features_rest, new_opacity, new_scaling, new_rotation)
380
+
381
+ prune_filter = torch.cat((selected_pts_mask, torch.zeros(N * selected_pts_mask.sum(), device="cuda", dtype=bool)))
382
+ self.prune_points(prune_filter)
383
+
384
+ def densify_and_clone(self, grads, grad_threshold, scene_extent):
385
+ # Extract points that satisfy the gradient condition
386
+ selected_pts_mask = torch.where(torch.norm(grads, dim=-1) >= grad_threshold, True, False)
387
+ selected_pts_mask = torch.logical_and(selected_pts_mask,
388
+ torch.max(self.get_scaling, dim=1).values <= self.percent_dense*scene_extent)
389
+
390
+ new_xyz = self._xyz[selected_pts_mask]
391
+ new_features_dc = self._features_dc[selected_pts_mask]
392
+ new_features_rest = self._features_rest[selected_pts_mask]
393
+ new_opacities = self._opacity[selected_pts_mask]
394
+ new_scaling = self._scaling[selected_pts_mask]
395
+ new_rotation = self._rotation[selected_pts_mask]
396
+
397
+ self.densification_postfix(new_xyz, new_features_dc, new_features_rest, new_opacities, new_scaling, new_rotation)
398
+
399
+ def densify_and_prune(self, max_grad, min_opacity, extent, max_screen_size):
400
+ grads = self.xyz_gradient_accum / self.denom
401
+ grads[grads.isnan()] = 0.0
402
+
403
+ self.densify_and_clone(grads, max_grad, extent)
404
+ self.densify_and_split(grads, max_grad, extent)
405
+
406
+ prune_mask = (self.get_opacity < min_opacity).squeeze()
407
+ if max_screen_size:
408
+ big_points_vs = self.max_radii2D > max_screen_size
409
+ big_points_ws = self.get_scaling.max(dim=1).values > 0.1 * extent
410
+ prune_mask = torch.logical_or(torch.logical_or(prune_mask, big_points_vs), big_points_ws)
411
+ self.prune_points(prune_mask)
412
+
413
+ torch.cuda.empty_cache()
414
+
415
+ def add_densification_stats(self, viewspace_point_tensor, update_filter):
416
+
417
+ self.xyz_gradient_accum[update_filter] += torch.norm(viewspace_point_tensor[update_filter,:2], dim=-1, keepdim=True)
418
+
419
+ self.denom[update_filter] += 1
gaussiansplatting/submodules/diff-gaussian-rasterization/.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ build/
2
+ diff_gaussian_rasterization.egg-info/
3
+ dist/
gaussiansplatting/submodules/diff-gaussian-rasterization/.gitmodules ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [submodule "third_party/glm"]
2
+ path = third_party/glm
3
+ url = https://github.com/g-truc/glm.git
gaussiansplatting/submodules/diff-gaussian-rasterization/CMakeLists.txt ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Copyright (C) 2023, Inria
3
+ # GRAPHDECO research group, https://team.inria.fr/graphdeco
4
+ # All rights reserved.
5
+ #
6
+ # This software is free for non-commercial, research and evaluation use
7
+ # under the terms of the LICENSE.md file.
8
+ #
9
+ # For inquiries contact george.drettakis@inria.fr
10
+ #
11
+
12
+ cmake_minimum_required(VERSION 3.20)
13
+
14
+ project(DiffRast LANGUAGES CUDA CXX)
15
+
16
+ set(CMAKE_CXX_STANDARD 17)
17
+ set(CMAKE_CXX_EXTENSIONS OFF)
18
+ set(CMAKE_CUDA_STANDARD 17)
19
+
20
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
21
+
22
+ add_library(CudaRasterizer
23
+ cuda_rasterizer/backward.h
24
+ cuda_rasterizer/backward.cu
25
+ cuda_rasterizer/forward.h
26
+ cuda_rasterizer/forward.cu
27
+ cuda_rasterizer/auxiliary.h
28
+ cuda_rasterizer/rasterizer_impl.cu
29
+ cuda_rasterizer/rasterizer_impl.h
30
+ cuda_rasterizer/rasterizer.h
31
+ )
32
+
33
+ set_target_properties(CudaRasterizer PROPERTIES CUDA_ARCHITECTURES "70;75;86")
34
+
35
+ target_include_directories(CudaRasterizer PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/cuda_rasterizer)
36
+ target_include_directories(CudaRasterizer PRIVATE third_party/glm ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES})
gaussiansplatting/submodules/diff-gaussian-rasterization/LICENSE.md ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Gaussian-Splatting License
2
+ ===========================
3
+
4
+ **Inria** and **the Max Planck Institut for Informatik (MPII)** hold all the ownership rights on the *Software* named **gaussian-splatting**.
5
+ The *Software* is in the process of being registered with the Agence pour la Protection des
6
+ Programmes (APP).
7
+
8
+ The *Software* is still being developed by the *Licensor*.
9
+
10
+ *Licensor*'s goal is to allow the research community to use, test and evaluate
11
+ the *Software*.
12
+
13
+ ## 1. Definitions
14
+
15
+ *Licensee* means any person or entity that uses the *Software* and distributes
16
+ its *Work*.
17
+
18
+ *Licensor* means the owners of the *Software*, i.e Inria and MPII
19
+
20
+ *Software* means the original work of authorship made available under this
21
+ License ie gaussian-splatting.
22
+
23
+ *Work* means the *Software* and any additions to or derivative works of the
24
+ *Software* that are made available under this License.
25
+
26
+
27
+ ## 2. Purpose
28
+ This license is intended to define the rights granted to the *Licensee* by
29
+ Licensors under the *Software*.
30
+
31
+ ## 3. Rights granted
32
+
33
+ For the above reasons Licensors have decided to distribute the *Software*.
34
+ Licensors grant non-exclusive rights to use the *Software* for research purposes
35
+ to research users (both academic and industrial), free of charge, without right
36
+ to sublicense.. The *Software* may be used "non-commercially", i.e., for research
37
+ and/or evaluation purposes only.
38
+
39
+ Subject to the terms and conditions of this License, you are granted a
40
+ non-exclusive, royalty-free, license to reproduce, prepare derivative works of,
41
+ publicly display, publicly perform and distribute its *Work* and any resulting
42
+ derivative works in any form.
43
+
44
+ ## 4. Limitations
45
+
46
+ **4.1 Redistribution.** You may reproduce or distribute the *Work* only if (a) you do
47
+ so under this License, (b) you include a complete copy of this License with
48
+ your distribution, and (c) you retain without modification any copyright,
49
+ patent, trademark, or attribution notices that are present in the *Work*.
50
+
51
+ **4.2 Derivative Works.** You may specify that additional or different terms apply
52
+ to the use, reproduction, and distribution of your derivative works of the *Work*
53
+ ("Your Terms") only if (a) Your Terms provide that the use limitation in
54
+ Section 2 applies to your derivative works, and (b) you identify the specific
55
+ derivative works that are subject to Your Terms. Notwithstanding Your Terms,
56
+ this License (including the redistribution requirements in Section 3.1) will
57
+ continue to apply to the *Work* itself.
58
+
59
+ **4.3** Any other use without of prior consent of Licensors is prohibited. Research
60
+ users explicitly acknowledge having received from Licensors all information
61
+ allowing to appreciate the adequacy between of the *Software* and their needs and
62
+ to undertake all necessary precautions for its execution and use.
63
+
64
+ **4.4** The *Software* is provided both as a compiled library file and as source
65
+ code. In case of using the *Software* for a publication or other results obtained
66
+ through the use of the *Software*, users are strongly encouraged to cite the
67
+ corresponding publications as explained in the documentation of the *Software*.
68
+
69
+ ## 5. Disclaimer
70
+
71
+ THE USER CANNOT USE, EXPLOIT OR DISTRIBUTE THE *SOFTWARE* FOR COMMERCIAL PURPOSES
72
+ WITHOUT PRIOR AND EXPLICIT CONSENT OF LICENSORS. YOU MUST CONTACT INRIA FOR ANY
73
+ UNAUTHORIZED USE: stip-sophia.transfert@inria.fr . ANY SUCH ACTION WILL
74
+ CONSTITUTE A FORGERY. THIS *SOFTWARE* IS PROVIDED "AS IS" WITHOUT ANY WARRANTIES
75
+ OF ANY NATURE AND ANY EXPRESS OR IMPLIED WARRANTIES, WITH REGARDS TO COMMERCIAL
76
+ USE, PROFESSIONNAL USE, LEGAL OR NOT, OR OTHER, OR COMMERCIALISATION OR
77
+ ADAPTATION. UNLESS EXPLICITLY PROVIDED BY LAW, IN NO EVENT, SHALL INRIA OR THE
78
+ AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
79
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
80
+ GOODS OR SERVICES, LOSS OF USE, DATA, OR PROFITS OR BUSINESS INTERRUPTION)
81
+ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
82
+ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING FROM, OUT OF OR
83
+ IN CONNECTION WITH THE *SOFTWARE* OR THE USE OR OTHER DEALINGS IN THE *SOFTWARE*.
gaussiansplatting/submodules/diff-gaussian-rasterization/README.md ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Differential Gaussian Rasterization
2
+
3
+ This is a forked repository of the rasterization pipeline from the paper "3D Gaussian Splatting for Real-Time Rendering of Radiance Fields". I have made some extensions to it:
4
+
5
+ - main branch incorporates only the forward pass of depth, which is used for depth visualization.
6
+ - 4th-degree: add the 4th degree of SH
7
+ - depth: add both the forward and backward pass of depth, which is used for some tasks with depth supervision.
8
+ - latest: is the dev branch that contains acc and depth visualization, together with depth backward pass.
9
+
10
+ <section class="section" id="BibTeX">
11
+ <div class="container is-max-desktop content">
12
+ <h2 class="title">BibTeX</h2>
13
+ <pre><code>@Article{kerbl3Dgaussians,
14
+ author = {Kerbl, Bernhard and Kopanas, Georgios and Leimk{\"u}hler, Thomas and Drettakis, George},
15
+ title = {3D Gaussian Splatting for Real-Time Radiance Field Rendering},
16
+ journal = {ACM Transactions on Graphics},
17
+ number = {4},
18
+ volume = {42},
19
+ month = {July},
20
+ year = {2023},
21
+ url = {https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/}
22
+ }</code></pre>
23
+ </div>
24
+ </section>
gaussiansplatting/submodules/diff-gaussian-rasterization/cuda_rasterizer/auxiliary.h ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (C) 2023, Inria
3
+ * GRAPHDECO research group, https://team.inria.fr/graphdeco
4
+ * All rights reserved.
5
+ *
6
+ * This software is free for non-commercial, research and evaluation use
7
+ * under the terms of the LICENSE.md file.
8
+ *
9
+ * For inquiries contact george.drettakis@inria.fr
10
+ */
11
+
12
+ #ifndef CUDA_RASTERIZER_AUXILIARY_H_INCLUDED
13
+ #define CUDA_RASTERIZER_AUXILIARY_H_INCLUDED
14
+
15
+ #include "config.h"
16
+ #include "stdio.h"
17
+
18
+ #define BLOCK_SIZE (BLOCK_X * BLOCK_Y)
19
+ #define NUM_WARPS (BLOCK_SIZE/32)
20
+
21
+ // Spherical harmonics coefficients
22
+ __device__ const float SH_C0 = 0.28209479177387814f;
23
+ __device__ const float SH_C1 = 0.4886025119029199f;
24
+ __device__ const float SH_C2[] = {
25
+ 1.0925484305920792f,
26
+ -1.0925484305920792f,
27
+ 0.31539156525252005f,
28
+ -1.0925484305920792f,
29
+ 0.5462742152960396f
30
+ };
31
+ __device__ const float SH_C3[] = {
32
+ -0.5900435899266435f,
33
+ 2.890611442640554f,
34
+ -0.4570457994644658f,
35
+ 0.3731763325901154f,
36
+ -0.4570457994644658f,
37
+ 1.445305721320277f,
38
+ -0.5900435899266435f
39
+ };
40
+
41
+ __forceinline__ __device__ float ndc2Pix(float v, int S)
42
+ {
43
+ return ((v + 1.0) * S - 1.0) * 0.5;
44
+ }
45
+
46
+ __forceinline__ __device__ void getRect(const float2 p, int max_radius, uint2& rect_min, uint2& rect_max, dim3 grid)
47
+ {
48
+ rect_min = {
49
+ min(grid.x, max((int)0, (int)((p.x - max_radius) / BLOCK_X))),
50
+ min(grid.y, max((int)0, (int)((p.y - max_radius) / BLOCK_Y)))
51
+ };
52
+ rect_max = {
53
+ min(grid.x, max((int)0, (int)((p.x + max_radius + BLOCK_X - 1) / BLOCK_X))),
54
+ min(grid.y, max((int)0, (int)((p.y + max_radius + BLOCK_Y - 1) / BLOCK_Y)))
55
+ };
56
+ }
57
+
58
+ __forceinline__ __device__ float3 transformPoint4x3(const float3& p, const float* matrix)
59
+ {
60
+ float3 transformed = {
61
+ matrix[0] * p.x + matrix[4] * p.y + matrix[8] * p.z + matrix[12],
62
+ matrix[1] * p.x + matrix[5] * p.y + matrix[9] * p.z + matrix[13],
63
+ matrix[2] * p.x + matrix[6] * p.y + matrix[10] * p.z + matrix[14],
64
+ };
65
+ return transformed;
66
+ }
67
+
68
+ __forceinline__ __device__ float4 transformPoint4x4(const float3& p, const float* matrix)
69
+ {
70
+ float4 transformed = {
71
+ matrix[0] * p.x + matrix[4] * p.y + matrix[8] * p.z + matrix[12],
72
+ matrix[1] * p.x + matrix[5] * p.y + matrix[9] * p.z + matrix[13],
73
+ matrix[2] * p.x + matrix[6] * p.y + matrix[10] * p.z + matrix[14],
74
+ matrix[3] * p.x + matrix[7] * p.y + matrix[11] * p.z + matrix[15]
75
+ };
76
+ return transformed;
77
+ }
78
+
79
+ __forceinline__ __device__ float3 transformVec4x3(const float3& p, const float* matrix)
80
+ {
81
+ float3 transformed = {
82
+ matrix[0] * p.x + matrix[4] * p.y + matrix[8] * p.z,
83
+ matrix[1] * p.x + matrix[5] * p.y + matrix[9] * p.z,
84
+ matrix[2] * p.x + matrix[6] * p.y + matrix[10] * p.z,
85
+ };
86
+ return transformed;
87
+ }
88
+
89
+ __forceinline__ __device__ float3 transformVec4x3Transpose(const float3& p, const float* matrix)
90
+ {
91
+ float3 transformed = {
92
+ matrix[0] * p.x + matrix[1] * p.y + matrix[2] * p.z,
93
+ matrix[4] * p.x + matrix[5] * p.y + matrix[6] * p.z,
94
+ matrix[8] * p.x + matrix[9] * p.y + matrix[10] * p.z,
95
+ };
96
+ return transformed;
97
+ }
98
+
99
+ __forceinline__ __device__ float dnormvdz(float3 v, float3 dv)
100
+ {
101
+ float sum2 = v.x * v.x + v.y * v.y + v.z * v.z;
102
+ float invsum32 = 1.0f / sqrt(sum2 * sum2 * sum2);
103
+ float dnormvdz = (-v.x * v.z * dv.x - v.y * v.z * dv.y + (sum2 - v.z * v.z) * dv.z) * invsum32;
104
+ return dnormvdz;
105
+ }
106
+
107
+ __forceinline__ __device__ float3 dnormvdv(float3 v, float3 dv)
108
+ {
109
+ float sum2 = v.x * v.x + v.y * v.y + v.z * v.z;
110
+ float invsum32 = 1.0f / sqrt(sum2 * sum2 * sum2);
111
+
112
+ float3 dnormvdv;
113
+ dnormvdv.x = ((+sum2 - v.x * v.x) * dv.x - v.y * v.x * dv.y - v.z * v.x * dv.z) * invsum32;
114
+ dnormvdv.y = (-v.x * v.y * dv.x + (sum2 - v.y * v.y) * dv.y - v.z * v.y * dv.z) * invsum32;
115
+ dnormvdv.z = (-v.x * v.z * dv.x - v.y * v.z * dv.y + (sum2 - v.z * v.z) * dv.z) * invsum32;
116
+ return dnormvdv;
117
+ }
118
+
119
+ __forceinline__ __device__ float4 dnormvdv(float4 v, float4 dv)
120
+ {
121
+ float sum2 = v.x * v.x + v.y * v.y + v.z * v.z + v.w * v.w;
122
+ float invsum32 = 1.0f / sqrt(sum2 * sum2 * sum2);
123
+
124
+ float4 vdv = { v.x * dv.x, v.y * dv.y, v.z * dv.z, v.w * dv.w };
125
+ float vdv_sum = vdv.x + vdv.y + vdv.z + vdv.w;
126
+ float4 dnormvdv;
127
+ dnormvdv.x = ((sum2 - v.x * v.x) * dv.x - v.x * (vdv_sum - vdv.x)) * invsum32;
128
+ dnormvdv.y = ((sum2 - v.y * v.y) * dv.y - v.y * (vdv_sum - vdv.y)) * invsum32;
129
+ dnormvdv.z = ((sum2 - v.z * v.z) * dv.z - v.z * (vdv_sum - vdv.z)) * invsum32;
130
+ dnormvdv.w = ((sum2 - v.w * v.w) * dv.w - v.w * (vdv_sum - vdv.w)) * invsum32;
131
+ return dnormvdv;
132
+ }
133
+
134
+ __forceinline__ __device__ float sigmoid(float x)
135
+ {
136
+ return 1.0f / (1.0f + expf(-x));
137
+ }
138
+
139
+ __forceinline__ __device__ bool in_frustum(int idx,
140
+ const float* orig_points,
141
+ const float* viewmatrix,
142
+ const float* projmatrix,
143
+ bool prefiltered,
144
+ float3& p_view)
145
+ {
146
+ float3 p_orig = { orig_points[3 * idx], orig_points[3 * idx + 1], orig_points[3 * idx + 2] };
147
+
148
+ // Bring points to screen space
149
+ float4 p_hom = transformPoint4x4(p_orig, projmatrix);
150
+ float p_w = 1.0f / (p_hom.w + 0.0000001f);
151
+ float3 p_proj = { p_hom.x * p_w, p_hom.y * p_w, p_hom.z * p_w };
152
+ p_view = transformPoint4x3(p_orig, viewmatrix);
153
+
154
+ if (p_view.z <= 0.2f)// || ((p_proj.x < -1.3 || p_proj.x > 1.3 || p_proj.y < -1.3 || p_proj.y > 1.3)))
155
+ {
156
+ if (prefiltered)
157
+ {
158
+ printf("Point is filtered although prefiltered is set. This shouldn't happen!");
159
+ __trap();
160
+ }
161
+ return false;
162
+ }
163
+ return true;
164
+ }
165
+
166
+ #define CHECK_CUDA(A, debug) \
167
+ A; if(debug) { \
168
+ auto ret = cudaDeviceSynchronize(); \
169
+ if (ret != cudaSuccess) { \
170
+ std::cerr << "\n[CUDA ERROR] in " << __FILE__ << "\nLine " << __LINE__ << ": " << cudaGetErrorString(ret); \
171
+ throw std::runtime_error(cudaGetErrorString(ret)); \
172
+ } \
173
+ }
174
+
175
+ #endif
gaussiansplatting/submodules/diff-gaussian-rasterization/cuda_rasterizer/backward.cu ADDED
@@ -0,0 +1,657 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (C) 2023, Inria
3
+ * GRAPHDECO research group, https://team.inria.fr/graphdeco
4
+ * All rights reserved.
5
+ *
6
+ * This software is free for non-commercial, research and evaluation use
7
+ * under the terms of the LICENSE.md file.
8
+ *
9
+ * For inquiries contact george.drettakis@inria.fr
10
+ */
11
+
12
+ #include "backward.h"
13
+ #include "auxiliary.h"
14
+ #include <cooperative_groups.h>
15
+ #include <cooperative_groups/reduce.h>
16
+ namespace cg = cooperative_groups;
17
+
18
+ // Backward pass for conversion of spherical harmonics to RGB for
19
+ // each Gaussian.
20
+ __device__ void computeColorFromSH(int idx, int deg, int max_coeffs, const glm::vec3* means, glm::vec3 campos, const float* shs, const bool* clamped, const glm::vec3* dL_dcolor, glm::vec3* dL_dmeans, glm::vec3* dL_dshs)
21
+ {
22
+ // Compute intermediate values, as it is done during forward
23
+ glm::vec3 pos = means[idx];
24
+ glm::vec3 dir_orig = pos - campos;
25
+ glm::vec3 dir = dir_orig / glm::length(dir_orig);
26
+
27
+ glm::vec3* sh = ((glm::vec3*)shs) + idx * max_coeffs;
28
+
29
+ // Use PyTorch rule for clamping: if clamping was applied,
30
+ // gradient becomes 0.
31
+ glm::vec3 dL_dRGB = dL_dcolor[idx];
32
+ dL_dRGB.x *= clamped[3 * idx + 0] ? 0 : 1;
33
+ dL_dRGB.y *= clamped[3 * idx + 1] ? 0 : 1;
34
+ dL_dRGB.z *= clamped[3 * idx + 2] ? 0 : 1;
35
+
36
+ glm::vec3 dRGBdx(0, 0, 0);
37
+ glm::vec3 dRGBdy(0, 0, 0);
38
+ glm::vec3 dRGBdz(0, 0, 0);
39
+ float x = dir.x;
40
+ float y = dir.y;
41
+ float z = dir.z;
42
+
43
+ // Target location for this Gaussian to write SH gradients to
44
+ glm::vec3* dL_dsh = dL_dshs + idx * max_coeffs;
45
+
46
+ // No tricks here, just high school-level calculus.
47
+ float dRGBdsh0 = SH_C0;
48
+ dL_dsh[0] = dRGBdsh0 * dL_dRGB;
49
+ if (deg > 0)
50
+ {
51
+ float dRGBdsh1 = -SH_C1 * y;
52
+ float dRGBdsh2 = SH_C1 * z;
53
+ float dRGBdsh3 = -SH_C1 * x;
54
+ dL_dsh[1] = dRGBdsh1 * dL_dRGB;
55
+ dL_dsh[2] = dRGBdsh2 * dL_dRGB;
56
+ dL_dsh[3] = dRGBdsh3 * dL_dRGB;
57
+
58
+ dRGBdx = -SH_C1 * sh[3];
59
+ dRGBdy = -SH_C1 * sh[1];
60
+ dRGBdz = SH_C1 * sh[2];
61
+
62
+ if (deg > 1)
63
+ {
64
+ float xx = x * x, yy = y * y, zz = z * z;
65
+ float xy = x * y, yz = y * z, xz = x * z;
66
+
67
+ float dRGBdsh4 = SH_C2[0] * xy;
68
+ float dRGBdsh5 = SH_C2[1] * yz;
69
+ float dRGBdsh6 = SH_C2[2] * (2.f * zz - xx - yy);
70
+ float dRGBdsh7 = SH_C2[3] * xz;
71
+ float dRGBdsh8 = SH_C2[4] * (xx - yy);
72
+ dL_dsh[4] = dRGBdsh4 * dL_dRGB;
73
+ dL_dsh[5] = dRGBdsh5 * dL_dRGB;
74
+ dL_dsh[6] = dRGBdsh6 * dL_dRGB;
75
+ dL_dsh[7] = dRGBdsh7 * dL_dRGB;
76
+ dL_dsh[8] = dRGBdsh8 * dL_dRGB;
77
+
78
+ dRGBdx += SH_C2[0] * y * sh[4] + SH_C2[2] * 2.f * -x * sh[6] + SH_C2[3] * z * sh[7] + SH_C2[4] * 2.f * x * sh[8];
79
+ dRGBdy += SH_C2[0] * x * sh[4] + SH_C2[1] * z * sh[5] + SH_C2[2] * 2.f * -y * sh[6] + SH_C2[4] * 2.f * -y * sh[8];
80
+ dRGBdz += SH_C2[1] * y * sh[5] + SH_C2[2] * 2.f * 2.f * z * sh[6] + SH_C2[3] * x * sh[7];
81
+
82
+ if (deg > 2)
83
+ {
84
+ float dRGBdsh9 = SH_C3[0] * y * (3.f * xx - yy);
85
+ float dRGBdsh10 = SH_C3[1] * xy * z;
86
+ float dRGBdsh11 = SH_C3[2] * y * (4.f * zz - xx - yy);
87
+ float dRGBdsh12 = SH_C3[3] * z * (2.f * zz - 3.f * xx - 3.f * yy);
88
+ float dRGBdsh13 = SH_C3[4] * x * (4.f * zz - xx - yy);
89
+ float dRGBdsh14 = SH_C3[5] * z * (xx - yy);
90
+ float dRGBdsh15 = SH_C3[6] * x * (xx - 3.f * yy);
91
+ dL_dsh[9] = dRGBdsh9 * dL_dRGB;
92
+ dL_dsh[10] = dRGBdsh10 * dL_dRGB;
93
+ dL_dsh[11] = dRGBdsh11 * dL_dRGB;
94
+ dL_dsh[12] = dRGBdsh12 * dL_dRGB;
95
+ dL_dsh[13] = dRGBdsh13 * dL_dRGB;
96
+ dL_dsh[14] = dRGBdsh14 * dL_dRGB;
97
+ dL_dsh[15] = dRGBdsh15 * dL_dRGB;
98
+
99
+ dRGBdx += (
100
+ SH_C3[0] * sh[9] * 3.f * 2.f * xy +
101
+ SH_C3[1] * sh[10] * yz +
102
+ SH_C3[2] * sh[11] * -2.f * xy +
103
+ SH_C3[3] * sh[12] * -3.f * 2.f * xz +
104
+ SH_C3[4] * sh[13] * (-3.f * xx + 4.f * zz - yy) +
105
+ SH_C3[5] * sh[14] * 2.f * xz +
106
+ SH_C3[6] * sh[15] * 3.f * (xx - yy));
107
+
108
+ dRGBdy += (
109
+ SH_C3[0] * sh[9] * 3.f * (xx - yy) +
110
+ SH_C3[1] * sh[10] * xz +
111
+ SH_C3[2] * sh[11] * (-3.f * yy + 4.f * zz - xx) +
112
+ SH_C3[3] * sh[12] * -3.f * 2.f * yz +
113
+ SH_C3[4] * sh[13] * -2.f * xy +
114
+ SH_C3[5] * sh[14] * -2.f * yz +
115
+ SH_C3[6] * sh[15] * -3.f * 2.f * xy);
116
+
117
+ dRGBdz += (
118
+ SH_C3[1] * sh[10] * xy +
119
+ SH_C3[2] * sh[11] * 4.f * 2.f * yz +
120
+ SH_C3[3] * sh[12] * 3.f * (2.f * zz - xx - yy) +
121
+ SH_C3[4] * sh[13] * 4.f * 2.f * xz +
122
+ SH_C3[5] * sh[14] * (xx - yy));
123
+ }
124
+ }
125
+ }
126
+
127
+ // The view direction is an input to the computation. View direction
128
+ // is influenced by the Gaussian's mean, so SHs gradients
129
+ // must propagate back into 3D position.
130
+ glm::vec3 dL_ddir(glm::dot(dRGBdx, dL_dRGB), glm::dot(dRGBdy, dL_dRGB), glm::dot(dRGBdz, dL_dRGB));
131
+
132
+ // Account for normalization of direction
133
+ float3 dL_dmean = dnormvdv(float3{ dir_orig.x, dir_orig.y, dir_orig.z }, float3{ dL_ddir.x, dL_ddir.y, dL_ddir.z });
134
+
135
+ // Gradients of loss w.r.t. Gaussian means, but only the portion
136
+ // that is caused because the mean affects the view-dependent color.
137
+ // Additional mean gradient is accumulated in below methods.
138
+ dL_dmeans[idx] += glm::vec3(dL_dmean.x, dL_dmean.y, dL_dmean.z);
139
+ }
140
+
141
+ // Backward version of INVERSE 2D covariance matrix computation
142
+ // (due to length launched as separate kernel before other
143
+ // backward steps contained in preprocess)
144
+ __global__ void computeCov2DCUDA(int P,
145
+ const float3* means,
146
+ const int* radii,
147
+ const float* cov3Ds,
148
+ const float h_x, float h_y,
149
+ const float tan_fovx, float tan_fovy,
150
+ const float* view_matrix,
151
+ const float* dL_dconics,
152
+ float3* dL_dmeans,
153
+ float* dL_dcov)
154
+ {
155
+ auto idx = cg::this_grid().thread_rank();
156
+ if (idx >= P || !(radii[idx] > 0))
157
+ return;
158
+
159
+ // Reading location of 3D covariance for this Gaussian
160
+ const float* cov3D = cov3Ds + 6 * idx;
161
+
162
+ // Fetch gradients, recompute 2D covariance and relevant
163
+ // intermediate forward results needed in the backward.
164
+ float3 mean = means[idx];
165
+ float3 dL_dconic = { dL_dconics[4 * idx], dL_dconics[4 * idx + 1], dL_dconics[4 * idx + 3] };
166
+ float3 t = transformPoint4x3(mean, view_matrix);
167
+
168
+ const float limx = 1.3f * tan_fovx;
169
+ const float limy = 1.3f * tan_fovy;
170
+ const float txtz = t.x / t.z;
171
+ const float tytz = t.y / t.z;
172
+ t.x = min(limx, max(-limx, txtz)) * t.z;
173
+ t.y = min(limy, max(-limy, tytz)) * t.z;
174
+
175
+ const float x_grad_mul = txtz < -limx || txtz > limx ? 0 : 1;
176
+ const float y_grad_mul = tytz < -limy || tytz > limy ? 0 : 1;
177
+
178
+ glm::mat3 J = glm::mat3(h_x / t.z, 0.0f, -(h_x * t.x) / (t.z * t.z),
179
+ 0.0f, h_y / t.z, -(h_y * t.y) / (t.z * t.z),
180
+ 0, 0, 0);
181
+
182
+ glm::mat3 W = glm::mat3(
183
+ view_matrix[0], view_matrix[4], view_matrix[8],
184
+ view_matrix[1], view_matrix[5], view_matrix[9],
185
+ view_matrix[2], view_matrix[6], view_matrix[10]);
186
+
187
+ glm::mat3 Vrk = glm::mat3(
188
+ cov3D[0], cov3D[1], cov3D[2],
189
+ cov3D[1], cov3D[3], cov3D[4],
190
+ cov3D[2], cov3D[4], cov3D[5]);
191
+
192
+ glm::mat3 T = W * J;
193
+
194
+ glm::mat3 cov2D = glm::transpose(T) * glm::transpose(Vrk) * T;
195
+
196
+ // Use helper variables for 2D covariance entries. More compact.
197
+ float a = cov2D[0][0] += 0.3f;
198
+ float b = cov2D[0][1];
199
+ float c = cov2D[1][1] += 0.3f;
200
+
201
+ float denom = a * c - b * b;
202
+ float dL_da = 0, dL_db = 0, dL_dc = 0;
203
+ float denom2inv = 1.0f / ((denom * denom) + 0.0000001f);
204
+
205
+ if (denom2inv != 0)
206
+ {
207
+ // Gradients of loss w.r.t. entries of 2D covariance matrix,
208
+ // given gradients of loss w.r.t. conic matrix (inverse covariance matrix).
209
+ // e.g., dL / da = dL / d_conic_a * d_conic_a / d_a
210
+ dL_da = denom2inv * (-c * c * dL_dconic.x + 2 * b * c * dL_dconic.y + (denom - a * c) * dL_dconic.z);
211
+ dL_dc = denom2inv * (-a * a * dL_dconic.z + 2 * a * b * dL_dconic.y + (denom - a * c) * dL_dconic.x);
212
+ dL_db = denom2inv * 2 * (b * c * dL_dconic.x - (denom + 2 * b * b) * dL_dconic.y + a * b * dL_dconic.z);
213
+
214
+ // Gradients of loss L w.r.t. each 3D covariance matrix (Vrk) entry,
215
+ // given gradients w.r.t. 2D covariance matrix (diagonal).
216
+ // cov2D = transpose(T) * transpose(Vrk) * T;
217
+ dL_dcov[6 * idx + 0] = (T[0][0] * T[0][0] * dL_da + T[0][0] * T[1][0] * dL_db + T[1][0] * T[1][0] * dL_dc);
218
+ dL_dcov[6 * idx + 3] = (T[0][1] * T[0][1] * dL_da + T[0][1] * T[1][1] * dL_db + T[1][1] * T[1][1] * dL_dc);
219
+ dL_dcov[6 * idx + 5] = (T[0][2] * T[0][2] * dL_da + T[0][2] * T[1][2] * dL_db + T[1][2] * T[1][2] * dL_dc);
220
+
221
+ // Gradients of loss L w.r.t. each 3D covariance matrix (Vrk) entry,
222
+ // given gradients w.r.t. 2D covariance matrix (off-diagonal).
223
+ // Off-diagonal elements appear twice --> double the gradient.
224
+ // cov2D = transpose(T) * transpose(Vrk) * T;
225
+ dL_dcov[6 * idx + 1] = 2 * T[0][0] * T[0][1] * dL_da + (T[0][0] * T[1][1] + T[0][1] * T[1][0]) * dL_db + 2 * T[1][0] * T[1][1] * dL_dc;
226
+ dL_dcov[6 * idx + 2] = 2 * T[0][0] * T[0][2] * dL_da + (T[0][0] * T[1][2] + T[0][2] * T[1][0]) * dL_db + 2 * T[1][0] * T[1][2] * dL_dc;
227
+ dL_dcov[6 * idx + 4] = 2 * T[0][2] * T[0][1] * dL_da + (T[0][1] * T[1][2] + T[0][2] * T[1][1]) * dL_db + 2 * T[1][1] * T[1][2] * dL_dc;
228
+ }
229
+ else
230
+ {
231
+ for (int i = 0; i < 6; i++)
232
+ dL_dcov[6 * idx + i] = 0;
233
+ }
234
+
235
+ // Gradients of loss w.r.t. upper 2x3 portion of intermediate matrix T
236
+ // cov2D = transpose(T) * transpose(Vrk) * T;
237
+ float dL_dT00 = 2 * (T[0][0] * Vrk[0][0] + T[0][1] * Vrk[0][1] + T[0][2] * Vrk[0][2]) * dL_da +
238
+ (T[1][0] * Vrk[0][0] + T[1][1] * Vrk[0][1] + T[1][2] * Vrk[0][2]) * dL_db;
239
+ float dL_dT01 = 2 * (T[0][0] * Vrk[1][0] + T[0][1] * Vrk[1][1] + T[0][2] * Vrk[1][2]) * dL_da +
240
+ (T[1][0] * Vrk[1][0] + T[1][1] * Vrk[1][1] + T[1][2] * Vrk[1][2]) * dL_db;
241
+ float dL_dT02 = 2 * (T[0][0] * Vrk[2][0] + T[0][1] * Vrk[2][1] + T[0][2] * Vrk[2][2]) * dL_da +
242
+ (T[1][0] * Vrk[2][0] + T[1][1] * Vrk[2][1] + T[1][2] * Vrk[2][2]) * dL_db;
243
+ float dL_dT10 = 2 * (T[1][0] * Vrk[0][0] + T[1][1] * Vrk[0][1] + T[1][2] * Vrk[0][2]) * dL_dc +
244
+ (T[0][0] * Vrk[0][0] + T[0][1] * Vrk[0][1] + T[0][2] * Vrk[0][2]) * dL_db;
245
+ float dL_dT11 = 2 * (T[1][0] * Vrk[1][0] + T[1][1] * Vrk[1][1] + T[1][2] * Vrk[1][2]) * dL_dc +
246
+ (T[0][0] * Vrk[1][0] + T[0][1] * Vrk[1][1] + T[0][2] * Vrk[1][2]) * dL_db;
247
+ float dL_dT12 = 2 * (T[1][0] * Vrk[2][0] + T[1][1] * Vrk[2][1] + T[1][2] * Vrk[2][2]) * dL_dc +
248
+ (T[0][0] * Vrk[2][0] + T[0][1] * Vrk[2][1] + T[0][2] * Vrk[2][2]) * dL_db;
249
+
250
+ // Gradients of loss w.r.t. upper 3x2 non-zero entries of Jacobian matrix
251
+ // T = W * J
252
+ float dL_dJ00 = W[0][0] * dL_dT00 + W[0][1] * dL_dT01 + W[0][2] * dL_dT02;
253
+ float dL_dJ02 = W[2][0] * dL_dT00 + W[2][1] * dL_dT01 + W[2][2] * dL_dT02;
254
+ float dL_dJ11 = W[1][0] * dL_dT10 + W[1][1] * dL_dT11 + W[1][2] * dL_dT12;
255
+ float dL_dJ12 = W[2][0] * dL_dT10 + W[2][1] * dL_dT11 + W[2][2] * dL_dT12;
256
+
257
+ float tz = 1.f / t.z;
258
+ float tz2 = tz * tz;
259
+ float tz3 = tz2 * tz;
260
+
261
+ // Gradients of loss w.r.t. transformed Gaussian mean t
262
+ float dL_dtx = x_grad_mul * -h_x * tz2 * dL_dJ02;
263
+ float dL_dty = y_grad_mul * -h_y * tz2 * dL_dJ12;
264
+ float dL_dtz = -h_x * tz2 * dL_dJ00 - h_y * tz2 * dL_dJ11 + (2 * h_x * t.x) * tz3 * dL_dJ02 + (2 * h_y * t.y) * tz3 * dL_dJ12;
265
+
266
+ // Account for transformation of mean to t
267
+ // t = transformPoint4x3(mean, view_matrix);
268
+ float3 dL_dmean = transformVec4x3Transpose({ dL_dtx, dL_dty, dL_dtz }, view_matrix);
269
+
270
+ // Gradients of loss w.r.t. Gaussian means, but only the portion
271
+ // that is caused because the mean affects the covariance matrix.
272
+ // Additional mean gradient is accumulated in BACKWARD::preprocess.
273
+ dL_dmeans[idx] = dL_dmean;
274
+ }
275
+
276
+ // Backward pass for the conversion of scale and rotation to a
277
+ // 3D covariance matrix for each Gaussian.
278
+ __device__ void computeCov3D(int idx, const glm::vec3 scale, float mod, const glm::vec4 rot, const float* dL_dcov3Ds, glm::vec3* dL_dscales, glm::vec4* dL_drots)
279
+ {
280
+ // Recompute (intermediate) results for the 3D covariance computation.
281
+ glm::vec4 q = rot;// / glm::length(rot);
282
+ float r = q.x;
283
+ float x = q.y;
284
+ float y = q.z;
285
+ float z = q.w;
286
+
287
+ glm::mat3 R = glm::mat3(
288
+ 1.f - 2.f * (y * y + z * z), 2.f * (x * y - r * z), 2.f * (x * z + r * y),
289
+ 2.f * (x * y + r * z), 1.f - 2.f * (x * x + z * z), 2.f * (y * z - r * x),
290
+ 2.f * (x * z - r * y), 2.f * (y * z + r * x), 1.f - 2.f * (x * x + y * y)
291
+ );
292
+
293
+ glm::mat3 S = glm::mat3(1.0f);
294
+
295
+ glm::vec3 s = mod * scale;
296
+ S[0][0] = s.x;
297
+ S[1][1] = s.y;
298
+ S[2][2] = s.z;
299
+
300
+ glm::mat3 M = S * R;
301
+
302
+ const float* dL_dcov3D = dL_dcov3Ds + 6 * idx;
303
+
304
+ glm::vec3 dunc(dL_dcov3D[0], dL_dcov3D[3], dL_dcov3D[5]);
305
+ glm::vec3 ounc = 0.5f * glm::vec3(dL_dcov3D[1], dL_dcov3D[2], dL_dcov3D[4]);
306
+
307
+ // Convert per-element covariance loss gradients to matrix form
308
+ glm::mat3 dL_dSigma = glm::mat3(
309
+ dL_dcov3D[0], 0.5f * dL_dcov3D[1], 0.5f * dL_dcov3D[2],
310
+ 0.5f * dL_dcov3D[1], dL_dcov3D[3], 0.5f * dL_dcov3D[4],
311
+ 0.5f * dL_dcov3D[2], 0.5f * dL_dcov3D[4], dL_dcov3D[5]
312
+ );
313
+
314
+ // Compute loss gradient w.r.t. matrix M
315
+ // dSigma_dM = 2 * M
316
+ glm::mat3 dL_dM = 2.0f * M * dL_dSigma;
317
+
318
+ glm::mat3 Rt = glm::transpose(R);
319
+ glm::mat3 dL_dMt = glm::transpose(dL_dM);
320
+
321
+ // Gradients of loss w.r.t. scale
322
+ glm::vec3* dL_dscale = dL_dscales + idx;
323
+ dL_dscale->x = glm::dot(Rt[0], dL_dMt[0]);
324
+ dL_dscale->y = glm::dot(Rt[1], dL_dMt[1]);
325
+ dL_dscale->z = glm::dot(Rt[2], dL_dMt[2]);
326
+
327
+ dL_dMt[0] *= s.x;
328
+ dL_dMt[1] *= s.y;
329
+ dL_dMt[2] *= s.z;
330
+
331
+ // Gradients of loss w.r.t. normalized quaternion
332
+ glm::vec4 dL_dq;
333
+ dL_dq.x = 2 * z * (dL_dMt[0][1] - dL_dMt[1][0]) + 2 * y * (dL_dMt[2][0] - dL_dMt[0][2]) + 2 * x * (dL_dMt[1][2] - dL_dMt[2][1]);
334
+ dL_dq.y = 2 * y * (dL_dMt[1][0] + dL_dMt[0][1]) + 2 * z * (dL_dMt[2][0] + dL_dMt[0][2]) + 2 * r * (dL_dMt[1][2] - dL_dMt[2][1]) - 4 * x * (dL_dMt[2][2] + dL_dMt[1][1]);
335
+ dL_dq.z = 2 * x * (dL_dMt[1][0] + dL_dMt[0][1]) + 2 * r * (dL_dMt[2][0] - dL_dMt[0][2]) + 2 * z * (dL_dMt[1][2] + dL_dMt[2][1]) - 4 * y * (dL_dMt[2][2] + dL_dMt[0][0]);
336
+ dL_dq.w = 2 * r * (dL_dMt[0][1] - dL_dMt[1][0]) + 2 * x * (dL_dMt[2][0] + dL_dMt[0][2]) + 2 * y * (dL_dMt[1][2] + dL_dMt[2][1]) - 4 * z * (dL_dMt[1][1] + dL_dMt[0][0]);
337
+
338
+ // Gradients of loss w.r.t. unnormalized quaternion
339
+ float4* dL_drot = (float4*)(dL_drots + idx);
340
+ *dL_drot = float4{ dL_dq.x, dL_dq.y, dL_dq.z, dL_dq.w };//dnormvdv(float4{ rot.x, rot.y, rot.z, rot.w }, float4{ dL_dq.x, dL_dq.y, dL_dq.z, dL_dq.w });
341
+ }
342
+
343
+ // Backward pass of the preprocessing steps, except
344
+ // for the covariance computation and inversion
345
+ // (those are handled by a previous kernel call)
346
+ template<int C>
347
+ __global__ void preprocessCUDA(
348
+ int P, int D, int M,
349
+ const float3* means,
350
+ const int* radii,
351
+ const float* shs,
352
+ const bool* clamped,
353
+ const glm::vec3* scales,
354
+ const glm::vec4* rotations,
355
+ const float scale_modifier,
356
+ const float* proj,
357
+ const glm::vec3* campos,
358
+ const float3* dL_dmean2D,
359
+ glm::vec3* dL_dmeans,
360
+ float* dL_dcolor,
361
+ float* dL_dcov3D,
362
+ float* dL_dsh,
363
+ glm::vec3* dL_dscale,
364
+ glm::vec4* dL_drot)
365
+ {
366
+ auto idx = cg::this_grid().thread_rank();
367
+ if (idx >= P || !(radii[idx] > 0))
368
+ return;
369
+
370
+ float3 m = means[idx];
371
+
372
+ // Taking care of gradients from the screenspace points
373
+ float4 m_hom = transformPoint4x4(m, proj);
374
+ float m_w = 1.0f / (m_hom.w + 0.0000001f);
375
+
376
+ // Compute loss gradient w.r.t. 3D means due to gradients of 2D means
377
+ // from rendering procedure
378
+ glm::vec3 dL_dmean;
379
+ float mul1 = (proj[0] * m.x + proj[4] * m.y + proj[8] * m.z + proj[12]) * m_w * m_w;
380
+ float mul2 = (proj[1] * m.x + proj[5] * m.y + proj[9] * m.z + proj[13]) * m_w * m_w;
381
+ dL_dmean.x = (proj[0] * m_w - proj[3] * mul1) * dL_dmean2D[idx].x + (proj[1] * m_w - proj[3] * mul2) * dL_dmean2D[idx].y;
382
+ dL_dmean.y = (proj[4] * m_w - proj[7] * mul1) * dL_dmean2D[idx].x + (proj[5] * m_w - proj[7] * mul2) * dL_dmean2D[idx].y;
383
+ dL_dmean.z = (proj[8] * m_w - proj[11] * mul1) * dL_dmean2D[idx].x + (proj[9] * m_w - proj[11] * mul2) * dL_dmean2D[idx].y;
384
+
385
+ // That's the second part of the mean gradient. Previous computation
386
+ // of cov2D and following SH conversion also affects it.
387
+ dL_dmeans[idx] += dL_dmean;
388
+
389
+ // Compute gradient updates due to computing colors from SHs
390
+ if (shs)
391
+ computeColorFromSH(idx, D, M, (glm::vec3*)means, *campos, shs, clamped, (glm::vec3*)dL_dcolor, (glm::vec3*)dL_dmeans, (glm::vec3*)dL_dsh);
392
+
393
+ // Compute gradient updates due to computing covariance from scale/rotation
394
+ if (scales)
395
+ computeCov3D(idx, scales[idx], scale_modifier, rotations[idx], dL_dcov3D, dL_dscale, dL_drot);
396
+ }
397
+
398
+ // Backward version of the rendering procedure.
399
+ template <uint32_t C>
400
+ __global__ void __launch_bounds__(BLOCK_X * BLOCK_Y)
401
+ renderCUDA(
402
+ const uint2* __restrict__ ranges,
403
+ const uint32_t* __restrict__ point_list,
404
+ int W, int H,
405
+ const float* __restrict__ bg_color,
406
+ const float2* __restrict__ points_xy_image,
407
+ const float4* __restrict__ conic_opacity,
408
+ const float* __restrict__ colors,
409
+ const float* __restrict__ final_Ts,
410
+ const uint32_t* __restrict__ n_contrib,
411
+ const float* __restrict__ dL_dpixels,
412
+ float3* __restrict__ dL_dmean2D,
413
+ float4* __restrict__ dL_dconic2D,
414
+ float* __restrict__ dL_dopacity,
415
+ float* __restrict__ dL_dcolors)
416
+ {
417
+ // We rasterize again. Compute necessary block info.
418
+ auto block = cg::this_thread_block();
419
+ const uint32_t horizontal_blocks = (W + BLOCK_X - 1) / BLOCK_X;
420
+ const uint2 pix_min = { block.group_index().x * BLOCK_X, block.group_index().y * BLOCK_Y };
421
+ const uint2 pix_max = { min(pix_min.x + BLOCK_X, W), min(pix_min.y + BLOCK_Y , H) };
422
+ const uint2 pix = { pix_min.x + block.thread_index().x, pix_min.y + block.thread_index().y };
423
+ const uint32_t pix_id = W * pix.y + pix.x;
424
+ const float2 pixf = { (float)pix.x, (float)pix.y };
425
+
426
+ const bool inside = pix.x < W&& pix.y < H;
427
+ const uint2 range = ranges[block.group_index().y * horizontal_blocks + block.group_index().x];
428
+
429
+ const int rounds = ((range.y - range.x + BLOCK_SIZE - 1) / BLOCK_SIZE);
430
+
431
+ bool done = !inside;
432
+ int toDo = range.y - range.x;
433
+
434
+ __shared__ int collected_id[BLOCK_SIZE];
435
+ __shared__ float2 collected_xy[BLOCK_SIZE];
436
+ __shared__ float4 collected_conic_opacity[BLOCK_SIZE];
437
+ __shared__ float collected_colors[C * BLOCK_SIZE];
438
+
439
+ // In the forward, we stored the final value for T, the
440
+ // product of all (1 - alpha) factors.
441
+ const float T_final = inside ? final_Ts[pix_id] : 0;
442
+ float T = T_final;
443
+
444
+ // We start from the back. The ID of the last contributing
445
+ // Gaussian is known from each pixel from the forward.
446
+ uint32_t contributor = toDo;
447
+ const int last_contributor = inside ? n_contrib[pix_id] : 0;
448
+
449
+ float accum_rec[C] = { 0 };
450
+ float dL_dpixel[C];
451
+ if (inside)
452
+ for (int i = 0; i < C; i++)
453
+ dL_dpixel[i] = dL_dpixels[i * H * W + pix_id];
454
+
455
+ float last_alpha = 0;
456
+ float last_color[C] = { 0 };
457
+
458
+ // Gradient of pixel coordinate w.r.t. normalized
459
+ // screen-space viewport corrdinates (-1 to 1)
460
+ const float ddelx_dx = 0.5 * W;
461
+ const float ddely_dy = 0.5 * H;
462
+
463
+ // Traverse all Gaussians
464
+ for (int i = 0; i < rounds; i++, toDo -= BLOCK_SIZE)
465
+ {
466
+ // Load auxiliary data into shared memory, start in the BACK
467
+ // and load them in revers order.
468
+ block.sync();
469
+ const int progress = i * BLOCK_SIZE + block.thread_rank();
470
+ if (range.x + progress < range.y)
471
+ {
472
+ const int coll_id = point_list[range.y - progress - 1];
473
+ collected_id[block.thread_rank()] = coll_id;
474
+ collected_xy[block.thread_rank()] = points_xy_image[coll_id];
475
+ collected_conic_opacity[block.thread_rank()] = conic_opacity[coll_id];
476
+ for (int i = 0; i < C; i++)
477
+ collected_colors[i * BLOCK_SIZE + block.thread_rank()] = colors[coll_id * C + i];
478
+ }
479
+ block.sync();
480
+
481
+ // Iterate over Gaussians
482
+ for (int j = 0; !done && j < min(BLOCK_SIZE, toDo); j++)
483
+ {
484
+ // Keep track of current Gaussian ID. Skip, if this one
485
+ // is behind the last contributor for this pixel.
486
+ contributor--;
487
+ if (contributor >= last_contributor)
488
+ continue;
489
+
490
+ // Compute blending values, as before.
491
+ const float2 xy = collected_xy[j];
492
+ const float2 d = { xy.x - pixf.x, xy.y - pixf.y };
493
+ const float4 con_o = collected_conic_opacity[j];
494
+ const float power = -0.5f * (con_o.x * d.x * d.x + con_o.z * d.y * d.y) - con_o.y * d.x * d.y;
495
+ if (power > 0.0f)
496
+ continue;
497
+
498
+ const float G = exp(power);
499
+ const float alpha = min(0.99f, con_o.w * G);
500
+ if (alpha < 1.0f / 255.0f)
501
+ continue;
502
+
503
+ T = T / (1.f - alpha);
504
+ const float dchannel_dcolor = alpha * T;
505
+
506
+ // Propagate gradients to per-Gaussian colors and keep
507
+ // gradients w.r.t. alpha (blending factor for a Gaussian/pixel
508
+ // pair).
509
+ float dL_dalpha = 0.0f;
510
+ const int global_id = collected_id[j];
511
+ for (int ch = 0; ch < C; ch++)
512
+ {
513
+ const float c = collected_colors[ch * BLOCK_SIZE + j];
514
+ // Update last color (to be used in the next iteration)
515
+ accum_rec[ch] = last_alpha * last_color[ch] + (1.f - last_alpha) * accum_rec[ch];
516
+ last_color[ch] = c;
517
+
518
+ const float dL_dchannel = dL_dpixel[ch];
519
+ dL_dalpha += (c - accum_rec[ch]) * dL_dchannel;
520
+ // Update the gradients w.r.t. color of the Gaussian.
521
+ // Atomic, since this pixel is just one of potentially
522
+ // many that were affected by this Gaussian.
523
+ atomicAdd(&(dL_dcolors[global_id * C + ch]), dchannel_dcolor * dL_dchannel);
524
+ }
525
+ dL_dalpha *= T;
526
+ // Update last alpha (to be used in the next iteration)
527
+ last_alpha = alpha;
528
+
529
+ // Account for fact that alpha also influences how much of
530
+ // the background color is added if nothing left to blend
531
+ float bg_dot_dpixel = 0;
532
+ for (int i = 0; i < C; i++)
533
+ bg_dot_dpixel += bg_color[i] * dL_dpixel[i];
534
+ dL_dalpha += (-T_final / (1.f - alpha)) * bg_dot_dpixel;
535
+
536
+
537
+ // Helpful reusable temporary variables
538
+ const float dL_dG = con_o.w * dL_dalpha;
539
+ const float gdx = G * d.x;
540
+ const float gdy = G * d.y;
541
+ const float dG_ddelx = -gdx * con_o.x - gdy * con_o.y;
542
+ const float dG_ddely = -gdy * con_o.z - gdx * con_o.y;
543
+
544
+ // Update gradients w.r.t. 2D mean position of the Gaussian
545
+ atomicAdd(&dL_dmean2D[global_id].x, dL_dG * dG_ddelx * ddelx_dx);
546
+ atomicAdd(&dL_dmean2D[global_id].y, dL_dG * dG_ddely * ddely_dy);
547
+
548
+ // Update gradients w.r.t. 2D covariance (2x2 matrix, symmetric)
549
+ atomicAdd(&dL_dconic2D[global_id].x, -0.5f * gdx * d.x * dL_dG);
550
+ atomicAdd(&dL_dconic2D[global_id].y, -0.5f * gdx * d.y * dL_dG);
551
+ atomicAdd(&dL_dconic2D[global_id].w, -0.5f * gdy * d.y * dL_dG);
552
+
553
+ // Update gradients w.r.t. opacity of the Gaussian
554
+ atomicAdd(&(dL_dopacity[global_id]), G * dL_dalpha);
555
+ }
556
+ }
557
+ }
558
+
559
+ void BACKWARD::preprocess(
560
+ int P, int D, int M,
561
+ const float3* means3D,
562
+ const int* radii,
563
+ const float* shs,
564
+ const bool* clamped,
565
+ const glm::vec3* scales,
566
+ const glm::vec4* rotations,
567
+ const float scale_modifier,
568
+ const float* cov3Ds,
569
+ const float* viewmatrix,
570
+ const float* projmatrix,
571
+ const float focal_x, float focal_y,
572
+ const float tan_fovx, float tan_fovy,
573
+ const glm::vec3* campos,
574
+ const float3* dL_dmean2D,
575
+ const float* dL_dconic,
576
+ glm::vec3* dL_dmean3D,
577
+ float* dL_dcolor,
578
+ float* dL_dcov3D,
579
+ float* dL_dsh,
580
+ glm::vec3* dL_dscale,
581
+ glm::vec4* dL_drot)
582
+ {
583
+ // Propagate gradients for the path of 2D conic matrix computation.
584
+ // Somewhat long, thus it is its own kernel rather than being part of
585
+ // "preprocess". When done, loss gradient w.r.t. 3D means has been
586
+ // modified and gradient w.r.t. 3D covariance matrix has been computed.
587
+ computeCov2DCUDA << <(P + 255) / 256, 256 >> > (
588
+ P,
589
+ means3D,
590
+ radii,
591
+ cov3Ds,
592
+ focal_x,
593
+ focal_y,
594
+ tan_fovx,
595
+ tan_fovy,
596
+ viewmatrix,
597
+ dL_dconic,
598
+ (float3*)dL_dmean3D,
599
+ dL_dcov3D);
600
+
601
+ // Propagate gradients for remaining steps: finish 3D mean gradients,
602
+ // propagate color gradients to SH (if desireD), propagate 3D covariance
603
+ // matrix gradients to scale and rotation.
604
+ preprocessCUDA<NUM_CHANNELS> << < (P + 255) / 256, 256 >> > (
605
+ P, D, M,
606
+ (float3*)means3D,
607
+ radii,
608
+ shs,
609
+ clamped,
610
+ (glm::vec3*)scales,
611
+ (glm::vec4*)rotations,
612
+ scale_modifier,
613
+ projmatrix,
614
+ campos,
615
+ (float3*)dL_dmean2D,
616
+ (glm::vec3*)dL_dmean3D,
617
+ dL_dcolor,
618
+ dL_dcov3D,
619
+ dL_dsh,
620
+ dL_dscale,
621
+ dL_drot);
622
+ }
623
+
624
+ void BACKWARD::render(
625
+ const dim3 grid, const dim3 block,
626
+ const uint2* ranges,
627
+ const uint32_t* point_list,
628
+ int W, int H,
629
+ const float* bg_color,
630
+ const float2* means2D,
631
+ const float4* conic_opacity,
632
+ const float* colors,
633
+ const float* final_Ts,
634
+ const uint32_t* n_contrib,
635
+ const float* dL_dpixels,
636
+ float3* dL_dmean2D,
637
+ float4* dL_dconic2D,
638
+ float* dL_dopacity,
639
+ float* dL_dcolors)
640
+ {
641
+ renderCUDA<NUM_CHANNELS> << <grid, block >> >(
642
+ ranges,
643
+ point_list,
644
+ W, H,
645
+ bg_color,
646
+ means2D,
647
+ conic_opacity,
648
+ colors,
649
+ final_Ts,
650
+ n_contrib,
651
+ dL_dpixels,
652
+ dL_dmean2D,
653
+ dL_dconic2D,
654
+ dL_dopacity,
655
+ dL_dcolors
656
+ );
657
+ }
gaussiansplatting/submodules/diff-gaussian-rasterization/cuda_rasterizer/backward.h ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (C) 2023, Inria
3
+ * GRAPHDECO research group, https://team.inria.fr/graphdeco
4
+ * All rights reserved.
5
+ *
6
+ * This software is free for non-commercial, research and evaluation use
7
+ * under the terms of the LICENSE.md file.
8
+ *
9
+ * For inquiries contact george.drettakis@inria.fr
10
+ */
11
+
12
+ #ifndef CUDA_RASTERIZER_BACKWARD_H_INCLUDED
13
+ #define CUDA_RASTERIZER_BACKWARD_H_INCLUDED
14
+
15
+ #include <cuda.h>
16
+ #include "cuda_runtime.h"
17
+ #include "device_launch_parameters.h"
18
+ #define GLM_FORCE_CUDA
19
+ #include <glm/glm.hpp>
20
+
21
+ namespace BACKWARD
22
+ {
23
+ void render(
24
+ const dim3 grid, dim3 block,
25
+ const uint2* ranges,
26
+ const uint32_t* point_list,
27
+ int W, int H,
28
+ const float* bg_color,
29
+ const float2* means2D,
30
+ const float4* conic_opacity,
31
+ const float* colors,
32
+ const float* final_Ts,
33
+ const uint32_t* n_contrib,
34
+ const float* dL_dpixels,
35
+ float3* dL_dmean2D,
36
+ float4* dL_dconic2D,
37
+ float* dL_dopacity,
38
+ float* dL_dcolors);
39
+
40
+ void preprocess(
41
+ int P, int D, int M,
42
+ const float3* means,
43
+ const int* radii,
44
+ const float* shs,
45
+ const bool* clamped,
46
+ const glm::vec3* scales,
47
+ const glm::vec4* rotations,
48
+ const float scale_modifier,
49
+ const float* cov3Ds,
50
+ const float* view,
51
+ const float* proj,
52
+ const float focal_x, float focal_y,
53
+ const float tan_fovx, float tan_fovy,
54
+ const glm::vec3* campos,
55
+ const float3* dL_dmean2D,
56
+ const float* dL_dconics,
57
+ glm::vec3* dL_dmeans,
58
+ float* dL_dcolor,
59
+ float* dL_dcov3D,
60
+ float* dL_dsh,
61
+ glm::vec3* dL_dscale,
62
+ glm::vec4* dL_drot);
63
+ }
64
+
65
+ #endif