From bd57f345ed9dbed1d81683e48199626de2ea9044 Mon Sep 17 00:00:00 2001 From: 3gg <3gg@shellblade.net> Date: Fri, 27 Jun 2025 10:18:39 -0700 Subject: Restructure project --- CMakeLists.txt | 91 +- README.md | 144 + bin/txt2c.py | 62 + cmake/shader.txt | 5 + cmake/txt2c.txt | 44 + contrib/cgltf-tangents/CMakeLists.txt | 13 + contrib/cgltf-tangents/LICENSE | 79 + contrib/cgltf-tangents/MikkTSpace/README.md | 4 + contrib/cgltf-tangents/MikkTSpace/mikktspace.c | 1899 +++++ contrib/cgltf-tangents/MikkTSpace/mikktspace.h | 145 + contrib/cgltf-tangents/README.md | 42 + contrib/cgltf-tangents/cgltf_tangents.c | 618 ++ contrib/cgltf-tangents/cgltf_tangents.h | 67 + contrib/cgltf-tangents/test/CMakeLists.txt | 11 + contrib/cgltf-tangents/test/main.c | 86 + contrib/cgltf/CMakeLists.txt | 8 + contrib/cgltf/LICENSE | 7 + contrib/cgltf/README.md | 154 + contrib/cgltf/cgltf.h | 5746 +++++++++++++++ contrib/cgltf/cgltf_write.h | 1173 +++ contrib/stb/CMakeLists.txt | 8 + contrib/stb/stb_image.h | 7762 ++++++++++++++++++++ .../2013SiggraphPresentationsNotes-26915738.pdf | Bin 0 -> 2947929 bytes doc/extern/Scene Graph - CSE 167.pdf | Bin 0 -> 890801 bytes doc/gfx.png | Bin 0 -> 6272 bytes doc/gfx.txt | 10 + doc/gltfOverview-2.0.0b.png | Bin 0 -> 4757973 bytes doc/pipeline.png | Bin 0 -> 10318 bytes doc/pipeline.txt | 16 + doc/renderer.png | Bin 0 -> 13144 bytes doc/renderer.txt | 18 + doc/scene.png | Bin 0 -> 59119 bytes doc/scene.txt | 109 + game/CMakeLists.txt | 22 - game/src/game.c | 218 - game/src/game.h | 21 - game/src/plugins/CMakeLists.txt | 29 - game/src/plugins/plugin.h | 52 - game/src/plugins/pong.c | 237 - game/src/plugins/texture_view.c | 144 - game/src/plugins/viewer.c | 374 - gfx-iso/CMakeLists.txt | 42 - gfx-iso/demos/CMakeLists.txt | 2 - gfx-iso/demos/checkerboard/CMakeLists.txt | 16 - gfx-iso/demos/checkerboard/checkerboard.c | 166 - gfx-iso/demos/isomap/CMakeLists.txt | 16 - gfx-iso/demos/isomap/isomap.c | 105 - gfx-iso/include/isogfx/backend.h | 28 - gfx-iso/include/isogfx/isogfx.h | 136 - gfx-iso/src/backend.c | 199 - gfx-iso/src/isogfx.c | 952 --- gfx-iso/tools/mkasset.py | 324 - gfx/CMakeLists.txt | 89 - gfx/README.md | 144 - gfx/bin/txt2c.py | 62 - gfx/cmake/shader.txt | 5 - gfx/cmake/txt2c.txt | 44 - gfx/contrib/cgltf-tangents/CMakeLists.txt | 13 - gfx/contrib/cgltf-tangents/LICENSE | 79 - gfx/contrib/cgltf-tangents/MikkTSpace/README.md | 4 - gfx/contrib/cgltf-tangents/MikkTSpace/mikktspace.c | 1899 ----- gfx/contrib/cgltf-tangents/MikkTSpace/mikktspace.h | 145 - gfx/contrib/cgltf-tangents/README.md | 42 - gfx/contrib/cgltf-tangents/cgltf_tangents.c | 618 -- gfx/contrib/cgltf-tangents/cgltf_tangents.h | 67 - gfx/contrib/cgltf-tangents/test/CMakeLists.txt | 11 - gfx/contrib/cgltf-tangents/test/main.c | 86 - gfx/contrib/cgltf/CMakeLists.txt | 8 - gfx/contrib/cgltf/LICENSE | 7 - gfx/contrib/cgltf/README.md | 154 - gfx/contrib/cgltf/cgltf.h | 5746 --------------- gfx/contrib/cgltf/cgltf_write.h | 1173 --- gfx/contrib/stb/CMakeLists.txt | 8 - gfx/contrib/stb/stb_image.h | 7762 -------------------- .../2013SiggraphPresentationsNotes-26915738.pdf | Bin 2947929 -> 0 bytes gfx/doc/extern/Scene Graph - CSE 167.pdf | Bin 890801 -> 0 bytes gfx/doc/gfx.png | Bin 6272 -> 0 bytes gfx/doc/gfx.txt | 10 - gfx/doc/gltfOverview-2.0.0b.png | Bin 4757973 -> 0 bytes gfx/doc/pipeline.png | Bin 10318 -> 0 bytes gfx/doc/pipeline.txt | 16 - gfx/doc/renderer.png | Bin 13144 -> 0 bytes gfx/doc/renderer.txt | 18 - gfx/doc/scene.png | Bin 59119 -> 0 bytes gfx/doc/scene.txt | 109 - gfx/include/gfx/asset.h | 99 - gfx/include/gfx/core.h | 501 -- gfx/include/gfx/gfx.h | 31 - gfx/include/gfx/renderer.h | 104 - gfx/include/gfx/scene.h | 11 - gfx/include/gfx/scene/animation.h | 142 - gfx/include/gfx/scene/camera.h | 22 - gfx/include/gfx/scene/light.h | 30 - gfx/include/gfx/scene/material.h | 25 - gfx/include/gfx/scene/mesh.h | 23 - gfx/include/gfx/scene/model.h | 12 - gfx/include/gfx/scene/node.h | 156 - gfx/include/gfx/scene/object.h | 39 - gfx/include/gfx/scene/scene.h | 21 - gfx/include/gfx/sizes.h | 95 - gfx/include/gfx/util/geometry.h | 13 - gfx/include/gfx/util/ibl.h | 25 - gfx/include/gfx/util/shader.h | 46 - gfx/include/gfx/util/skyquad.h | 22 - gfx/shaders/brdf_integration_map.frag | 93 - gfx/shaders/cook_torrance.frag | 255 - gfx/shaders/cook_torrance.vert | 75 - gfx/shaders/cubemap_filtering.vert | 39 - gfx/shaders/debug3d.frag | 21 - gfx/shaders/debug3d.vert | 15 - gfx/shaders/immediate_mode.frag | 10 - gfx/shaders/immediate_mode.vert | 11 - gfx/shaders/irradiance_map.frag | 65 - gfx/shaders/prefiltered_environment_map.frag | 78 - gfx/shaders/quad.vert | 9 - gfx/shaders/skyquad.frag | 13 - gfx/shaders/skyquad.vert | 27 - gfx/shaders/view_normal_mapped_normals.frag | 28 - gfx/shaders/view_normal_mapped_normals.vert | 22 - gfx/shaders/view_normals.frag | 11 - gfx/shaders/view_normals.vert | 15 - gfx/shaders/view_tangents.frag | 17 - gfx/shaders/view_tangents.vert | 14 - gfx/shaders/view_texture.frag | 15 - gfx/shaders/view_texture.vert | 13 - gfx/src/asset/asset_cache.c | 252 - gfx/src/asset/asset_cache.h | 37 - gfx/src/asset/model.c | 1968 ----- gfx/src/asset/model.h | 12 - gfx/src/asset/texture.c | 177 - gfx/src/asset/texture.h | 7 - gfx/src/core/buffer.c | 85 - gfx/src/core/buffer.h | 26 - gfx/src/core/constants.h | 9 - gfx/src/core/core.c | 429 -- gfx/src/core/core_impl.h | 68 - gfx/src/core/framebuffer.c | 151 - gfx/src/core/framebuffer.h | 15 - gfx/src/core/geometry.c | 326 - gfx/src/core/geometry.h | 28 - gfx/src/core/gl_util.h | 45 - gfx/src/core/renderbuffer.c | 35 - gfx/src/core/renderbuffer.h | 15 - gfx/src/core/shader.c | 92 - gfx/src/core/shader.h | 17 - gfx/src/core/shader_program.c | 291 - gfx/src/core/shader_program.h | 24 - gfx/src/core/texture.c | 218 - gfx/src/core/texture.h | 35 - gfx/src/gfx.c | 73 - gfx/src/gfx_assert.h | 5 - gfx/src/renderer/imm_renderer.c | 260 - gfx/src/renderer/imm_renderer_impl.h | 44 - gfx/src/renderer/renderer.c | 396 - gfx/src/renderer/renderer_impl.h | 27 - gfx/src/scene/animation.c | 524 -- gfx/src/scene/animation_impl.h | 98 - gfx/src/scene/camera.c | 37 - gfx/src/scene/camera_impl.h | 12 - gfx/src/scene/light.c | 42 - gfx/src/scene/light_impl.h | 25 - gfx/src/scene/material.c | 57 - gfx/src/scene/material_impl.h | 16 - gfx/src/scene/mesh.c | 24 - gfx/src/scene/mesh_impl.h | 12 - gfx/src/scene/model.c | 45 - gfx/src/scene/model_impl.h | 17 - gfx/src/scene/node.c | 409 -- gfx/src/scene/node_impl.h | 40 - gfx/src/scene/object.c | 83 - gfx/src/scene/object_impl.h | 26 - gfx/src/scene/scene.c | 25 - gfx/src/scene/scene_graph.h | 138 - gfx/src/scene/scene_impl.h | 13 - gfx/src/scene/scene_memory.c | 149 - gfx/src/scene/scene_memory.h | 39 - gfx/src/scene/types.h | 24 - gfx/src/util/geometry.c | 44 - gfx/src/util/ibl.c | 328 - gfx/src/util/shader.c | 136 - gfx/src/util/skyquad.c | 161 - include/gfx/asset.h | 99 + include/gfx/core.h | 501 ++ include/gfx/gfx.h | 31 + include/gfx/renderer.h | 104 + include/gfx/scene.h | 11 + include/gfx/scene/animation.h | 142 + include/gfx/scene/camera.h | 22 + include/gfx/scene/light.h | 30 + include/gfx/scene/material.h | 25 + include/gfx/scene/mesh.h | 23 + include/gfx/scene/model.h | 12 + include/gfx/scene/node.h | 156 + include/gfx/scene/object.h | 39 + include/gfx/scene/scene.h | 21 + include/gfx/sizes.h | 95 + include/gfx/util/geometry.h | 13 + include/gfx/util/ibl.h | 25 + include/gfx/util/shader.h | 46 + include/gfx/util/skyquad.h | 22 + shaders/brdf_integration_map.frag | 93 + shaders/cook_torrance.frag | 255 + shaders/cook_torrance.vert | 75 + shaders/cubemap_filtering.vert | 39 + shaders/debug3d.frag | 21 + shaders/debug3d.vert | 15 + shaders/immediate_mode.frag | 10 + shaders/immediate_mode.vert | 11 + shaders/irradiance_map.frag | 65 + shaders/prefiltered_environment_map.frag | 78 + shaders/quad.vert | 9 + shaders/skyquad.frag | 13 + shaders/skyquad.vert | 27 + shaders/view_normal_mapped_normals.frag | 28 + shaders/view_normal_mapped_normals.vert | 22 + shaders/view_normals.frag | 11 + shaders/view_normals.vert | 15 + shaders/view_tangents.frag | 17 + shaders/view_tangents.vert | 14 + shaders/view_texture.frag | 15 + shaders/view_texture.vert | 13 + src/asset/asset_cache.c | 252 + src/asset/asset_cache.h | 37 + src/asset/model.c | 1968 +++++ src/asset/model.h | 12 + src/asset/texture.c | 177 + src/asset/texture.h | 7 + src/core/buffer.c | 85 + src/core/buffer.h | 26 + src/core/constants.h | 9 + src/core/core.c | 429 ++ src/core/core_impl.h | 68 + src/core/framebuffer.c | 151 + src/core/framebuffer.h | 15 + src/core/geometry.c | 326 + src/core/geometry.h | 28 + src/core/gl_util.h | 45 + src/core/renderbuffer.c | 35 + src/core/renderbuffer.h | 15 + src/core/shader.c | 92 + src/core/shader.h | 17 + src/core/shader_program.c | 291 + src/core/shader_program.h | 24 + src/core/texture.c | 218 + src/core/texture.h | 35 + src/gfx.c | 73 + src/gfx_assert.h | 5 + src/renderer/imm_renderer.c | 260 + src/renderer/imm_renderer_impl.h | 44 + src/renderer/renderer.c | 396 + src/renderer/renderer_impl.h | 27 + src/scene/animation.c | 524 ++ src/scene/animation_impl.h | 98 + src/scene/camera.c | 37 + src/scene/camera_impl.h | 12 + src/scene/light.c | 42 + src/scene/light_impl.h | 25 + src/scene/material.c | 57 + src/scene/material_impl.h | 16 + src/scene/mesh.c | 24 + src/scene/mesh_impl.h | 12 + src/scene/model.c | 45 + src/scene/model_impl.h | 17 + src/scene/node.c | 409 ++ src/scene/node_impl.h | 40 + src/scene/object.c | 83 + src/scene/object_impl.h | 26 + src/scene/scene.c | 25 + src/scene/scene_graph.h | 138 + src/scene/scene_impl.h | 13 + src/scene/scene_memory.c | 149 + src/scene/scene_memory.h | 39 + src/scene/types.h | 24 + src/util/geometry.c | 44 + src/util/ibl.c | 328 + src/util/shader.c | 136 + src/util/skyquad.c | 161 + 277 files changed, 28271 insertions(+), 31360 deletions(-) create mode 100644 README.md create mode 100755 bin/txt2c.py create mode 100644 cmake/shader.txt create mode 100644 cmake/txt2c.txt create mode 100644 contrib/cgltf-tangents/CMakeLists.txt create mode 100644 contrib/cgltf-tangents/LICENSE create mode 100644 contrib/cgltf-tangents/MikkTSpace/README.md create mode 100644 contrib/cgltf-tangents/MikkTSpace/mikktspace.c create mode 100644 contrib/cgltf-tangents/MikkTSpace/mikktspace.h create mode 100644 contrib/cgltf-tangents/README.md create mode 100644 contrib/cgltf-tangents/cgltf_tangents.c create mode 100644 contrib/cgltf-tangents/cgltf_tangents.h create mode 100644 contrib/cgltf-tangents/test/CMakeLists.txt create mode 100644 contrib/cgltf-tangents/test/main.c create mode 100644 contrib/cgltf/CMakeLists.txt create mode 100644 contrib/cgltf/LICENSE create mode 100644 contrib/cgltf/README.md create mode 100644 contrib/cgltf/cgltf.h create mode 100644 contrib/cgltf/cgltf_write.h create mode 100644 contrib/stb/CMakeLists.txt create mode 100644 contrib/stb/stb_image.h create mode 100644 doc/extern/2013SiggraphPresentationsNotes-26915738.pdf create mode 100644 doc/extern/Scene Graph - CSE 167.pdf create mode 100644 doc/gfx.png create mode 100644 doc/gfx.txt create mode 100644 doc/gltfOverview-2.0.0b.png create mode 100644 doc/pipeline.png create mode 100644 doc/pipeline.txt create mode 100644 doc/renderer.png create mode 100644 doc/renderer.txt create mode 100644 doc/scene.png create mode 100644 doc/scene.txt delete mode 100644 game/CMakeLists.txt delete mode 100644 game/src/game.c delete mode 100644 game/src/game.h delete mode 100644 game/src/plugins/CMakeLists.txt delete mode 100644 game/src/plugins/plugin.h delete mode 100644 game/src/plugins/pong.c delete mode 100644 game/src/plugins/texture_view.c delete mode 100644 game/src/plugins/viewer.c delete mode 100644 gfx-iso/CMakeLists.txt delete mode 100644 gfx-iso/demos/CMakeLists.txt delete mode 100644 gfx-iso/demos/checkerboard/CMakeLists.txt delete mode 100644 gfx-iso/demos/checkerboard/checkerboard.c delete mode 100644 gfx-iso/demos/isomap/CMakeLists.txt delete mode 100644 gfx-iso/demos/isomap/isomap.c delete mode 100644 gfx-iso/include/isogfx/backend.h delete mode 100644 gfx-iso/include/isogfx/isogfx.h delete mode 100644 gfx-iso/src/backend.c delete mode 100644 gfx-iso/src/isogfx.c delete mode 100644 gfx-iso/tools/mkasset.py delete mode 100644 gfx/CMakeLists.txt delete mode 100644 gfx/README.md delete mode 100755 gfx/bin/txt2c.py delete mode 100644 gfx/cmake/shader.txt delete mode 100644 gfx/cmake/txt2c.txt delete mode 100644 gfx/contrib/cgltf-tangents/CMakeLists.txt delete mode 100644 gfx/contrib/cgltf-tangents/LICENSE delete mode 100644 gfx/contrib/cgltf-tangents/MikkTSpace/README.md delete mode 100644 gfx/contrib/cgltf-tangents/MikkTSpace/mikktspace.c delete mode 100644 gfx/contrib/cgltf-tangents/MikkTSpace/mikktspace.h delete mode 100644 gfx/contrib/cgltf-tangents/README.md delete mode 100644 gfx/contrib/cgltf-tangents/cgltf_tangents.c delete mode 100644 gfx/contrib/cgltf-tangents/cgltf_tangents.h delete mode 100644 gfx/contrib/cgltf-tangents/test/CMakeLists.txt delete mode 100644 gfx/contrib/cgltf-tangents/test/main.c delete mode 100644 gfx/contrib/cgltf/CMakeLists.txt delete mode 100644 gfx/contrib/cgltf/LICENSE delete mode 100644 gfx/contrib/cgltf/README.md delete mode 100644 gfx/contrib/cgltf/cgltf.h delete mode 100644 gfx/contrib/cgltf/cgltf_write.h delete mode 100644 gfx/contrib/stb/CMakeLists.txt delete mode 100644 gfx/contrib/stb/stb_image.h delete mode 100644 gfx/doc/extern/2013SiggraphPresentationsNotes-26915738.pdf delete mode 100644 gfx/doc/extern/Scene Graph - CSE 167.pdf delete mode 100644 gfx/doc/gfx.png delete mode 100644 gfx/doc/gfx.txt delete mode 100644 gfx/doc/gltfOverview-2.0.0b.png delete mode 100644 gfx/doc/pipeline.png delete mode 100644 gfx/doc/pipeline.txt delete mode 100644 gfx/doc/renderer.png delete mode 100644 gfx/doc/renderer.txt delete mode 100644 gfx/doc/scene.png delete mode 100644 gfx/doc/scene.txt delete mode 100644 gfx/include/gfx/asset.h delete mode 100644 gfx/include/gfx/core.h delete mode 100644 gfx/include/gfx/gfx.h delete mode 100644 gfx/include/gfx/renderer.h delete mode 100644 gfx/include/gfx/scene.h delete mode 100644 gfx/include/gfx/scene/animation.h delete mode 100644 gfx/include/gfx/scene/camera.h delete mode 100644 gfx/include/gfx/scene/light.h delete mode 100644 gfx/include/gfx/scene/material.h delete mode 100644 gfx/include/gfx/scene/mesh.h delete mode 100644 gfx/include/gfx/scene/model.h delete mode 100644 gfx/include/gfx/scene/node.h delete mode 100644 gfx/include/gfx/scene/object.h delete mode 100644 gfx/include/gfx/scene/scene.h delete mode 100644 gfx/include/gfx/sizes.h delete mode 100644 gfx/include/gfx/util/geometry.h delete mode 100644 gfx/include/gfx/util/ibl.h delete mode 100644 gfx/include/gfx/util/shader.h delete mode 100644 gfx/include/gfx/util/skyquad.h delete mode 100644 gfx/shaders/brdf_integration_map.frag delete mode 100644 gfx/shaders/cook_torrance.frag delete mode 100644 gfx/shaders/cook_torrance.vert delete mode 100644 gfx/shaders/cubemap_filtering.vert delete mode 100644 gfx/shaders/debug3d.frag delete mode 100644 gfx/shaders/debug3d.vert delete mode 100644 gfx/shaders/immediate_mode.frag delete mode 100644 gfx/shaders/immediate_mode.vert delete mode 100644 gfx/shaders/irradiance_map.frag delete mode 100644 gfx/shaders/prefiltered_environment_map.frag delete mode 100644 gfx/shaders/quad.vert delete mode 100644 gfx/shaders/skyquad.frag delete mode 100644 gfx/shaders/skyquad.vert delete mode 100644 gfx/shaders/view_normal_mapped_normals.frag delete mode 100644 gfx/shaders/view_normal_mapped_normals.vert delete mode 100644 gfx/shaders/view_normals.frag delete mode 100644 gfx/shaders/view_normals.vert delete mode 100644 gfx/shaders/view_tangents.frag delete mode 100644 gfx/shaders/view_tangents.vert delete mode 100644 gfx/shaders/view_texture.frag delete mode 100644 gfx/shaders/view_texture.vert delete mode 100644 gfx/src/asset/asset_cache.c delete mode 100644 gfx/src/asset/asset_cache.h delete mode 100644 gfx/src/asset/model.c delete mode 100644 gfx/src/asset/model.h delete mode 100644 gfx/src/asset/texture.c delete mode 100644 gfx/src/asset/texture.h delete mode 100644 gfx/src/core/buffer.c delete mode 100644 gfx/src/core/buffer.h delete mode 100644 gfx/src/core/constants.h delete mode 100644 gfx/src/core/core.c delete mode 100644 gfx/src/core/core_impl.h delete mode 100644 gfx/src/core/framebuffer.c delete mode 100644 gfx/src/core/framebuffer.h delete mode 100644 gfx/src/core/geometry.c delete mode 100644 gfx/src/core/geometry.h delete mode 100644 gfx/src/core/gl_util.h delete mode 100644 gfx/src/core/renderbuffer.c delete mode 100644 gfx/src/core/renderbuffer.h delete mode 100644 gfx/src/core/shader.c delete mode 100644 gfx/src/core/shader.h delete mode 100644 gfx/src/core/shader_program.c delete mode 100644 gfx/src/core/shader_program.h delete mode 100644 gfx/src/core/texture.c delete mode 100644 gfx/src/core/texture.h delete mode 100644 gfx/src/gfx.c delete mode 100644 gfx/src/gfx_assert.h delete mode 100644 gfx/src/renderer/imm_renderer.c delete mode 100644 gfx/src/renderer/imm_renderer_impl.h delete mode 100644 gfx/src/renderer/renderer.c delete mode 100644 gfx/src/renderer/renderer_impl.h delete mode 100644 gfx/src/scene/animation.c delete mode 100644 gfx/src/scene/animation_impl.h delete mode 100644 gfx/src/scene/camera.c delete mode 100644 gfx/src/scene/camera_impl.h delete mode 100644 gfx/src/scene/light.c delete mode 100644 gfx/src/scene/light_impl.h delete mode 100644 gfx/src/scene/material.c delete mode 100644 gfx/src/scene/material_impl.h delete mode 100644 gfx/src/scene/mesh.c delete mode 100644 gfx/src/scene/mesh_impl.h delete mode 100644 gfx/src/scene/model.c delete mode 100644 gfx/src/scene/model_impl.h delete mode 100644 gfx/src/scene/node.c delete mode 100644 gfx/src/scene/node_impl.h delete mode 100644 gfx/src/scene/object.c delete mode 100644 gfx/src/scene/object_impl.h delete mode 100644 gfx/src/scene/scene.c delete mode 100644 gfx/src/scene/scene_graph.h delete mode 100644 gfx/src/scene/scene_impl.h delete mode 100644 gfx/src/scene/scene_memory.c delete mode 100644 gfx/src/scene/scene_memory.h delete mode 100644 gfx/src/scene/types.h delete mode 100644 gfx/src/util/geometry.c delete mode 100644 gfx/src/util/ibl.c delete mode 100644 gfx/src/util/shader.c delete mode 100644 gfx/src/util/skyquad.c create mode 100644 include/gfx/asset.h create mode 100644 include/gfx/core.h create mode 100644 include/gfx/gfx.h create mode 100644 include/gfx/renderer.h create mode 100644 include/gfx/scene.h create mode 100644 include/gfx/scene/animation.h create mode 100644 include/gfx/scene/camera.h create mode 100644 include/gfx/scene/light.h create mode 100644 include/gfx/scene/material.h create mode 100644 include/gfx/scene/mesh.h create mode 100644 include/gfx/scene/model.h create mode 100644 include/gfx/scene/node.h create mode 100644 include/gfx/scene/object.h create mode 100644 include/gfx/scene/scene.h create mode 100644 include/gfx/sizes.h create mode 100644 include/gfx/util/geometry.h create mode 100644 include/gfx/util/ibl.h create mode 100644 include/gfx/util/shader.h create mode 100644 include/gfx/util/skyquad.h create mode 100644 shaders/brdf_integration_map.frag create mode 100644 shaders/cook_torrance.frag create mode 100644 shaders/cook_torrance.vert create mode 100644 shaders/cubemap_filtering.vert create mode 100644 shaders/debug3d.frag create mode 100644 shaders/debug3d.vert create mode 100644 shaders/immediate_mode.frag create mode 100644 shaders/immediate_mode.vert create mode 100644 shaders/irradiance_map.frag create mode 100644 shaders/prefiltered_environment_map.frag create mode 100644 shaders/quad.vert create mode 100644 shaders/skyquad.frag create mode 100644 shaders/skyquad.vert create mode 100644 shaders/view_normal_mapped_normals.frag create mode 100644 shaders/view_normal_mapped_normals.vert create mode 100644 shaders/view_normals.frag create mode 100644 shaders/view_normals.vert create mode 100644 shaders/view_tangents.frag create mode 100644 shaders/view_tangents.vert create mode 100644 shaders/view_texture.frag create mode 100644 shaders/view_texture.vert create mode 100644 src/asset/asset_cache.c create mode 100644 src/asset/asset_cache.h create mode 100644 src/asset/model.c create mode 100644 src/asset/model.h create mode 100644 src/asset/texture.c create mode 100644 src/asset/texture.h create mode 100644 src/core/buffer.c create mode 100644 src/core/buffer.h create mode 100644 src/core/constants.h create mode 100644 src/core/core.c create mode 100644 src/core/core_impl.h create mode 100644 src/core/framebuffer.c create mode 100644 src/core/framebuffer.h create mode 100644 src/core/geometry.c create mode 100644 src/core/geometry.h create mode 100644 src/core/gl_util.h create mode 100644 src/core/renderbuffer.c create mode 100644 src/core/renderbuffer.h create mode 100644 src/core/shader.c create mode 100644 src/core/shader.h create mode 100644 src/core/shader_program.c create mode 100644 src/core/shader_program.h create mode 100644 src/core/texture.c create mode 100644 src/core/texture.h create mode 100644 src/gfx.c create mode 100644 src/gfx_assert.h create mode 100644 src/renderer/imm_renderer.c create mode 100644 src/renderer/imm_renderer_impl.h create mode 100644 src/renderer/renderer.c create mode 100644 src/renderer/renderer_impl.h create mode 100644 src/scene/animation.c create mode 100644 src/scene/animation_impl.h create mode 100644 src/scene/camera.c create mode 100644 src/scene/camera_impl.h create mode 100644 src/scene/light.c create mode 100644 src/scene/light_impl.h create mode 100644 src/scene/material.c create mode 100644 src/scene/material_impl.h create mode 100644 src/scene/mesh.c create mode 100644 src/scene/mesh_impl.h create mode 100644 src/scene/model.c create mode 100644 src/scene/model_impl.h create mode 100644 src/scene/node.c create mode 100644 src/scene/node_impl.h create mode 100644 src/scene/object.c create mode 100644 src/scene/object_impl.h create mode 100644 src/scene/scene.c create mode 100644 src/scene/scene_graph.h create mode 100644 src/scene/scene_impl.h create mode 100644 src/scene/scene_memory.c create mode 100644 src/scene/scene_memory.h create mode 100644 src/scene/types.h create mode 100644 src/util/geometry.c create mode 100644 src/util/ibl.c create mode 100644 src/util/shader.c create mode 100644 src/util/skyquad.c diff --git a/CMakeLists.txt b/CMakeLists.txt index 25c7560..b13f28b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,8 +1,91 @@ cmake_minimum_required(VERSION 3.0) -project(gfx-all) +include(cmake/shader.txt) + +add_subdirectory(contrib/cgltf) +add_subdirectory(contrib/cgltf-tangents) +add_subdirectory(contrib/stb) add_subdirectory(app) -add_subdirectory(gfx) -add_subdirectory(gfx-iso) -add_subdirectory(game) + +project(gfx) + +add_shader_library(shaders + shaders/brdf_integration_map.frag + shaders/cook_torrance.frag + shaders/cook_torrance.vert + shaders/cubemap_filtering.vert + shaders/debug3d.frag + shaders/debug3d.vert + shaders/immediate_mode.frag + shaders/immediate_mode.vert + shaders/irradiance_map.frag + shaders/prefiltered_environment_map.frag + shaders/quad.vert + shaders/skyquad.frag + shaders/skyquad.vert + shaders/view_normal_mapped_normals.frag + shaders/view_normal_mapped_normals.vert + shaders/view_normals.frag + shaders/view_normals.vert + shaders/view_tangents.frag + shaders/view_tangents.vert + shaders/view_texture.frag + shaders/view_texture.vert) + +add_library(gfx SHARED + src/asset/asset_cache.c + src/asset/model.c + src/asset/texture.c + src/core/buffer.c + src/core/core.c + src/core/framebuffer.c + src/core/geometry.c + src/core/renderbuffer.c + src/core/shader_program.c + src/core/shader.c + src/core/texture.c + src/renderer/imm_renderer.c + src/renderer/renderer.c + src/scene/animation.c + src/scene/camera.c + src/scene/light.c + src/scene/material.c + src/scene/mesh.c + src/scene/model.c + src/scene/node.c + src/scene/object.c + src/scene/scene.c + src/scene/scene_memory.c + src/gfx.c + src/util/geometry.c + src/util/ibl.c + src/util/shader.c + src/util/skyquad.c) + +target_include_directories(gfx PUBLIC + include) + +target_include_directories(gfx PRIVATE + src) + +target_compile_options(gfx PRIVATE -std=gnu11 -Wall -Wextra -Wpedantic) + +target_link_libraries(gfx PUBLIC + cstring + math) + +target_link_libraries(gfx PRIVATE + cassert + cgltf + cgltf-tangents + error + gfx-app + log + mempool + shaders + stb + # System libraries. + GL + # Required to initialize GLAD. + -ldl) diff --git a/README.md b/README.md new file mode 100644 index 0000000..f0b103d --- /dev/null +++ b/README.md @@ -0,0 +1,144 @@ +# GFX - 3D Rendering Library + +A portable 3D rendering library with minimal dependencies written for +educational purposes. + +## Guiding Principles + +- Provide enough functionality for graphics applications and indie games. +- Provide a minimal interface, physically hide the implementation. Make bindings + easy. +- Establish a clean separation from the render backend and the rest of the + library to allow for additional rendering backends (e.g. Vulkan). +- Strive for a minimal set of dependencies, all of which should ship and compile + with the graphics library for ease of use. +- Rely on dynamic allocation as little as possible. Isolate dynamic allocation + to where it is strictly needed. + +## Design + +### Gfx + +The `Gfx` object represents the graphics subsystem and is at the center of the +library's high-level API. The `Gfx` object exposes a `Render` backend and a +`Renderer` and allows the caller to create `Scene`s. + +### Render Backend + +The `Render` backend is a thin abstraction layer over low-level graphics APIs +like OpenGL or Vulkan. It holds GPU resources such as geometry, textures, +shaders, etc, and exposes functions to manipulate them. + +Currently there is only one implementation of the `Render` backend based on +OpenGL. + +#### Ownership + +The `Render` backend owns all rendering resources: buffers, geometries, +textures, shaders, etc. Even resources that point to other resources do not own +those other resources (geometries pointing to buffers). + +There is no ownership tracking in the render backend. It is up to the client to +manage resource lifetime. + +### Scene + +A `Scene` encapsulates a scene graph. A scene graph contains the elements that +make up a scene: nodes, cameras, lights, objects, etc. The current scene graph +implementation includes: + +- Camera +- Light +- Material +- Mesh +- Node +- Object +- Scene + +#### Hierarchy and Parenting + +Scene graphs typically expose functions on nodes to add/remove objects, cameras, +lights, etc. This implementation forces the hierarchy to be a strict tree and +not a more general DAG. Given this, and to avoid confusion, we instead expose +functions to set the parent node of an object/camera/light. If we exposed the +former, the API could create the illusion that the hierarchy can be a DAG. + +The strict tree hierarchy should not be that restrictive in practice. Even the +glTF 2.0 spec [enforces this](https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#nodes-and-hierarchy): + +> *For Version 2.0 conformance, the glTF node hierarchy is not a directed +> acyclic graph (DAG) or scene graph, but a disjoint union of strict trees. That +> is, no node may be a direct descendant of more than one node. This restriction +> is meant to simplify implementation and facilitate conformance.* + +#### Instancing + +Two use cases for instancing seem to be: + +1. Creating N identical clones, but each with a unique transform. (Ex: N +animated characters animated in unison but located in different locations.) +2. Creating N copies of a sub-tree, each now being their own unique tree. (Ex: +The same N animated characters, but each of them now being animated separately.) + +Some scene graphs +([Panda3D](https://docs.panda3d.org/1.10/python/programming/scene-graph/instancing)) +allow two or more nodes to point to the same child, or, in other words, a node +to have multiple parents. This turns the scene graph into a DAG and adds a +number of complications for us: + +1. Shared ownership of children. We would now need some sort of ref counting or +deferred GC to delete nodes and their subtrees. +2. Nodes no longer have a unique parent. +3. Given a node, we can no longer determine its location (which parent link do +you follow?), or any attribute that is derived from its parent(s). + +In our case, we stick to strict tree hierarchies. + +Use case (1), N identical clones with unique transforms, is not a problem for +us. This is because the bulk of the data -- geometry buffers, etc. -- is stored +in the render backend anyway. So creating a full copy of the node does not +present a significant overhead since we need a unique transform for each of the +clones anyway. + +Use case (2) does present a bit more overhead and we currently do not handle it. +This could be handled in the future by special-casing a node such as +`InstanceNode` that has one child subtree and N transforms (or other +attributes), one for each unique instance of that child subtree. + +Therefore, to visit the use cases again: + +1. N character clones animated in unison in different locations -> future + `InstanceNode`. +2. N unique character copies animated on their own -> copy the character subtree + (N unique skeletons; shared mesh data and textures stored in the render + backend.) + +#### Reading + +[Panda3D Scene Graph](https://docs.panda3d.org/1.10/python/programming/scene-graph/index) + +[Pixar's USD](https://graphics.pixar.com/usd/release/intro.html) + +### Renderer + +The `Renderer` takes a `Render` backend and a `Scene` and renders the scene. +Currently, only a forward renderer is provided, but additional renderers can be +implemented in the future. + +### Util + +Code under `util/` provides functionality that need not be in the core part +of the library (Gfx, render backend, scene or renderer). This includes functions +to compute irradiance maps, create procedural geometry, etc. + +## Ideas for Future Work + +- Render graphs to allow for custom multi-pass rendering algorithms. + +## Build (Ubuntu) + +``` +sudo apt install libbsd-dev libgl-dev libglfw3-dev zlib1g-dev +``` + +TODO: Add these libraries to `contrib/`. diff --git a/bin/txt2c.py b/bin/txt2c.py new file mode 100755 index 0000000..1d8ff70 --- /dev/null +++ b/bin/txt2c.py @@ -0,0 +1,62 @@ +#!/usr/bin/python3 + +import fileinput +import os +import sys + + +def escape_quotes(string): + return string.replace("\"", '\\"') + + +def escape_newlines(string): + return string.replace("\n", "\\n") + + +def quote(string): + return "\"" + string + "\"" + + +def main(): + if len(sys.argv) < 3: + print("Usage: {} [text files...] [C files...]".format(sys.argv[0])) + return 1 + + files = sys.argv[1:] + assert(len(files) % 2 == 0) + N = int(len(files) / 2) + text_files = files[:N] + c_files = files[N:] + + for i in range(len(text_files)): + text_file = text_files[i] + c_file = c_files[i] + h_file = c_file.replace(".c", ".h") + variable_name = os.path.basename(text_file).replace(".", "_") + + os.makedirs(os.path.join(".", os.path.dirname(c_file)), exist_ok=True) + + # Create the C file. + with open(c_file, 'w') as out_file: + out_file.write("const char {}[] =\n".format(variable_name)) + pad = " " + with open(text_file, 'r') as in_file: + for line in in_file.readlines(): + line = escape_quotes(line) + line = escape_newlines(line) + line = quote(line) + line = pad + line + "\n" + out_file.write(line) + out_file.write(pad + "\"\";") + + # Create the header file. + with open(h_file, 'w') as out_file: + out_file.write("#pragma once\n") + out_file.write("\n") + out_file.write("extern const char {}[];".format(variable_name)) + + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/cmake/shader.txt b/cmake/shader.txt new file mode 100644 index 0000000..8273f4d --- /dev/null +++ b/cmake/shader.txt @@ -0,0 +1,5 @@ +include(cmake/txt2c.txt) + +macro(add_shader_library) + txt2c(${ARGN}) +endmacro() diff --git a/cmake/txt2c.txt b/cmake/txt2c.txt new file mode 100644 index 0000000..0cb11a9 --- /dev/null +++ b/cmake/txt2c.txt @@ -0,0 +1,44 @@ +function(txt2c target) + set(BUILD_DIR "${CMAKE_CURRENT_BINARY_DIR}/${target}") + file(MAKE_DIRECTORY ${BUILD_DIR}) + message(${BUILD_DIR}) + + set(TEXT_FILES) + set(SOURCE_FILES) + set(INCLUDE_DIRECTORIES) + foreach(filepath IN ITEMS ${ARGN}) + set(textfile "${CMAKE_CURRENT_SOURCE_DIR}/${filepath}") + list(APPEND TEXT_FILES ${textfile}) + + set(srcfile "${BUILD_DIR}/${filepath}.c") + list(APPEND SOURCE_FILES ${srcfile}) + + get_filename_component(include_dir ${srcfile} DIRECTORY) + list(APPEND INCLUDE_DIRECTORIES ${include_dir}) + endforeach() + + foreach(filepath IN ITEMS ${TEXT_FILES}) + message(${filepath}) + endforeach() + + foreach(filepath IN ITEMS ${SOURCE_FILES}) + message(${filepath}) + endforeach() + + foreach(filepath IN ITEMS ${INCLUDE_DIRECTORIES}) + message(${filepath}) + endforeach() + + add_custom_command(OUTPUT ${SOURCE_FILES} + COMMAND "${PROJECT_SOURCE_DIR}/bin/txt2c.py" ${TEXT_FILES} ${SOURCE_FILES} + WORKING_DIRECTORY ${BUILD_DIR} + DEPENDS ${ARGN} + COMMENT "Generating ${target}") + + add_library(${target} + ${SOURCE_FILES}) + + target_include_directories(${target} PUBLIC + ${BUILD_DIR} + ${INCLUDE_DIRECTORIES}) +endfunction() diff --git a/contrib/cgltf-tangents/CMakeLists.txt b/contrib/cgltf-tangents/CMakeLists.txt new file mode 100644 index 0000000..2c0771e --- /dev/null +++ b/contrib/cgltf-tangents/CMakeLists.txt @@ -0,0 +1,13 @@ +cmake_minimum_required(VERSION 3.0) + +project(cgltf-tangents) + +add_library(cgltf-tangents + cgltf_tangents.c + MikkTSpace/mikktspace.c) + +target_include_directories(cgltf-tangents PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR}) + +target_link_libraries(cgltf-tangents PUBLIC + cgltf) diff --git a/contrib/cgltf-tangents/LICENSE b/contrib/cgltf-tangents/LICENSE new file mode 100644 index 0000000..7796e37 --- /dev/null +++ b/contrib/cgltf-tangents/LICENSE @@ -0,0 +1,79 @@ +This project has two third-party dependencies: +- MikkTSpace +- cgltf + +The license for this project and its dependencies are included below. + +-------------------------------------------------------------------------------- +cgltf-tangents +-------------------------------------------------------------------------------- + +Copyright 2022 Marc Sunet + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation and/or +other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +-------------------------------------------------------------------------------- +MikkTSpace +-------------------------------------------------------------------------------- + +Copyright (C) 2011 by Morten S. Mikkelsen + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + +3. This notice may not be removed or altered from any source distribution. + +-------------------------------------------------------------------------------- +cgltf +-------------------------------------------------------------------------------- + +Copyright (c) 2018-2021 Johannes Kuhlmann + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/contrib/cgltf-tangents/MikkTSpace/README.md b/contrib/cgltf-tangents/MikkTSpace/README.md new file mode 100644 index 0000000..9fda155 --- /dev/null +++ b/contrib/cgltf-tangents/MikkTSpace/README.md @@ -0,0 +1,4 @@ +# MikkTSpace +A common standard for tangent space used in baking tools to produce normal maps. + +More information can be found at http://www.mikktspace.com/. diff --git a/contrib/cgltf-tangents/MikkTSpace/mikktspace.c b/contrib/cgltf-tangents/MikkTSpace/mikktspace.c new file mode 100644 index 0000000..0342ae0 --- /dev/null +++ b/contrib/cgltf-tangents/MikkTSpace/mikktspace.c @@ -0,0 +1,1899 @@ +/** \file mikktspace/mikktspace.c + * \ingroup mikktspace + */ +/** + * Copyright (C) 2011 by Morten S. Mikkelsen + * + * This software is provided 'as-is', without any express or implied + * warranty. In no event will the authors be held liable for any damages + * arising from the use of this software. + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software + * in a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * 3. This notice may not be removed or altered from any source distribution. + */ + +#include +#include +#include +#include +#include +#include + +#include "mikktspace.h" + +#define TFALSE 0 +#define TTRUE 1 + +#ifndef M_PI +#define M_PI 3.1415926535897932384626433832795 +#endif + +#define INTERNAL_RND_SORT_SEED 39871946 + +// internal structure +typedef struct { + float x, y, z; +} SVec3; + +static tbool veq( const SVec3 v1, const SVec3 v2 ) +{ + return (v1.x == v2.x) && (v1.y == v2.y) && (v1.z == v2.z); +} + +static SVec3 vadd( const SVec3 v1, const SVec3 v2 ) +{ + SVec3 vRes; + + vRes.x = v1.x + v2.x; + vRes.y = v1.y + v2.y; + vRes.z = v1.z + v2.z; + + return vRes; +} + + +static SVec3 vsub( const SVec3 v1, const SVec3 v2 ) +{ + SVec3 vRes; + + vRes.x = v1.x - v2.x; + vRes.y = v1.y - v2.y; + vRes.z = v1.z - v2.z; + + return vRes; +} + +static SVec3 vscale(const float fS, const SVec3 v) +{ + SVec3 vRes; + + vRes.x = fS * v.x; + vRes.y = fS * v.y; + vRes.z = fS * v.z; + + return vRes; +} + +static float LengthSquared( const SVec3 v ) +{ + return v.x*v.x + v.y*v.y + v.z*v.z; +} + +static float Length( const SVec3 v ) +{ + return sqrtf(LengthSquared(v)); +} + +static SVec3 Normalize( const SVec3 v ) +{ + return vscale(1 / Length(v), v); +} + +static float vdot( const SVec3 v1, const SVec3 v2) +{ + return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z; +} + + +static tbool NotZero(const float fX) +{ + // could possibly use FLT_EPSILON instead + return fabsf(fX) > FLT_MIN; +} + +static tbool VNotZero(const SVec3 v) +{ + // might change this to an epsilon based test + return NotZero(v.x) || NotZero(v.y) || NotZero(v.z); +} + + + +typedef struct { + int iNrFaces; + int * pTriMembers; +} SSubGroup; + +typedef struct { + int iNrFaces; + int * pFaceIndices; + int iVertexRepresentitive; + tbool bOrientPreservering; +} SGroup; + +// +#define MARK_DEGENERATE 1 +#define QUAD_ONE_DEGEN_TRI 2 +#define GROUP_WITH_ANY 4 +#define ORIENT_PRESERVING 8 + + + +typedef struct { + int FaceNeighbors[3]; + SGroup * AssignedGroup[3]; + + // normalized first order face derivatives + SVec3 vOs, vOt; + float fMagS, fMagT; // original magnitudes + + // determines if the current and the next triangle are a quad. + int iOrgFaceNumber; + int iFlag, iTSpacesOffs; + unsigned char vert_num[4]; +} STriInfo; + +typedef struct { + SVec3 vOs; + float fMagS; + SVec3 vOt; + float fMagT; + int iCounter; // this is to average back into quads. + tbool bOrient; +} STSpace; + +static int GenerateInitialVerticesIndexList(STriInfo pTriInfos[], int piTriList_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn); +static void GenerateSharedVerticesIndexList(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn); +static void InitTriInfo(STriInfo pTriInfos[], const int piTriListIn[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn); +static int Build4RuleGroups(STriInfo pTriInfos[], SGroup pGroups[], int piGroupTrianglesBuffer[], const int piTriListIn[], const int iNrTrianglesIn); +static tbool GenerateTSpaces(STSpace psTspace[], const STriInfo pTriInfos[], const SGroup pGroups[], + const int iNrActiveGroups, const int piTriListIn[], const float fThresCos, + const SMikkTSpaceContext * pContext); + +static int MakeIndex(const int iFace, const int iVert) +{ + assert(iVert>=0 && iVert<4 && iFace>=0); + return (iFace<<2) | (iVert&0x3); +} + +static void IndexToData(int * piFace, int * piVert, const int iIndexIn) +{ + piVert[0] = iIndexIn&0x3; + piFace[0] = iIndexIn>>2; +} + +static STSpace AvgTSpace(const STSpace * pTS0, const STSpace * pTS1) +{ + STSpace ts_res; + + // this if is important. Due to floating point precision + // averaging when ts0==ts1 will cause a slight difference + // which results in tangent space splits later on + if (pTS0->fMagS==pTS1->fMagS && pTS0->fMagT==pTS1->fMagT && + veq(pTS0->vOs,pTS1->vOs) && veq(pTS0->vOt, pTS1->vOt)) + { + ts_res.fMagS = pTS0->fMagS; + ts_res.fMagT = pTS0->fMagT; + ts_res.vOs = pTS0->vOs; + ts_res.vOt = pTS0->vOt; + } + else + { + ts_res.fMagS = 0.5f*(pTS0->fMagS+pTS1->fMagS); + ts_res.fMagT = 0.5f*(pTS0->fMagT+pTS1->fMagT); + ts_res.vOs = vadd(pTS0->vOs,pTS1->vOs); + ts_res.vOt = vadd(pTS0->vOt,pTS1->vOt); + if ( VNotZero(ts_res.vOs) ) ts_res.vOs = Normalize(ts_res.vOs); + if ( VNotZero(ts_res.vOt) ) ts_res.vOt = Normalize(ts_res.vOt); + } + + return ts_res; +} + + + +static SVec3 GetPosition(const SMikkTSpaceContext * pContext, const int index); +static SVec3 GetNormal(const SMikkTSpaceContext * pContext, const int index); +static SVec3 GetTexCoord(const SMikkTSpaceContext * pContext, const int index); + + +// degen triangles +static void DegenPrologue(STriInfo pTriInfos[], int piTriList_out[], const int iNrTrianglesIn, const int iTotTris); +static void DegenEpilogue(STSpace psTspace[], STriInfo pTriInfos[], int piTriListIn[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn, const int iTotTris); + + +tbool genTangSpaceDefault(const SMikkTSpaceContext * pContext) +{ + return genTangSpace(pContext, 180.0f); +} + +tbool genTangSpace(const SMikkTSpaceContext * pContext, const float fAngularThreshold) +{ + // count nr_triangles + int * piTriListIn = NULL, * piGroupTrianglesBuffer = NULL; + STriInfo * pTriInfos = NULL; + SGroup * pGroups = NULL; + STSpace * psTspace = NULL; + int iNrTrianglesIn = 0, f=0, t=0, i=0; + int iNrTSPaces = 0, iTotTris = 0, iDegenTriangles = 0, iNrMaxGroups = 0; + int iNrActiveGroups = 0, index = 0; + const int iNrFaces = pContext->m_pInterface->m_getNumFaces(pContext); + tbool bRes = TFALSE; + const float fThresCos = (float) cos((fAngularThreshold*(float)M_PI)/180.0f); + + // verify all call-backs have been set + if ( pContext->m_pInterface->m_getNumFaces==NULL || + pContext->m_pInterface->m_getNumVerticesOfFace==NULL || + pContext->m_pInterface->m_getPosition==NULL || + pContext->m_pInterface->m_getNormal==NULL || + pContext->m_pInterface->m_getTexCoord==NULL ) + return TFALSE; + + // count triangles on supported faces + for (f=0; fm_pInterface->m_getNumVerticesOfFace(pContext, f); + if (verts==3) ++iNrTrianglesIn; + else if (verts==4) iNrTrianglesIn += 2; + } + if (iNrTrianglesIn<=0) return TFALSE; + + // allocate memory for an index list + piTriListIn = (int *) malloc(sizeof(int)*3*iNrTrianglesIn); + pTriInfos = (STriInfo *) malloc(sizeof(STriInfo)*iNrTrianglesIn); + if (piTriListIn==NULL || pTriInfos==NULL) + { + if (piTriListIn!=NULL) free(piTriListIn); + if (pTriInfos!=NULL) free(pTriInfos); + return TFALSE; + } + + // make an initial triangle --> face index list + iNrTSPaces = GenerateInitialVerticesIndexList(pTriInfos, piTriListIn, pContext, iNrTrianglesIn); + + // make a welded index list of identical positions and attributes (pos, norm, texc) + //printf("gen welded index list begin\n"); + GenerateSharedVerticesIndexList(piTriListIn, pContext, iNrTrianglesIn); + //printf("gen welded index list end\n"); + + // Mark all degenerate triangles + iTotTris = iNrTrianglesIn; + iDegenTriangles = 0; + for (t=0; tm_pInterface->m_getNumVerticesOfFace(pContext, f); + if (verts!=3 && verts!=4) continue; + + + // I've decided to let degenerate triangles and group-with-anythings + // vary between left/right hand coordinate systems at the vertices. + // All healthy triangles on the other hand are built to always be either or. + + /*// force the coordinate system orientation to be uniform for every face. + // (this is already the case for good triangles but not for + // degenerate ones and those with bGroupWithAnything==true) + bool bOrient = psTspace[index].bOrient; + if (psTspace[index].iCounter == 0) // tspace was not derived from a group + { + // look for a space created in GenerateTSpaces() by iCounter>0 + bool bNotFound = true; + int i=1; + while (i 0) bNotFound=false; + else ++i; + } + if (!bNotFound) bOrient = psTspace[index+i].bOrient; + }*/ + + // set data + for (i=0; ivOs.x, pTSpace->vOs.y, pTSpace->vOs.z}; + float bitang[] = {pTSpace->vOt.x, pTSpace->vOt.y, pTSpace->vOt.z}; + if (pContext->m_pInterface->m_setTSpace!=NULL) + pContext->m_pInterface->m_setTSpace(pContext, tang, bitang, pTSpace->fMagS, pTSpace->fMagT, pTSpace->bOrient, f, i); + if (pContext->m_pInterface->m_setTSpaceBasic!=NULL) + pContext->m_pInterface->m_setTSpaceBasic(pContext, tang, pTSpace->bOrient==TTRUE ? 1.0f : (-1.0f), f, i); + + ++index; + } + } + + free(psTspace); + + + return TTRUE; +} + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +typedef struct { + float vert[3]; + int index; +} STmpVert; + +static const int g_iCells = 2048; + +#ifdef _MSC_VER +# define NOINLINE __declspec(noinline) +#else +# define NOINLINE __attribute__ ((noinline)) +#endif + +// it is IMPORTANT that this function is called to evaluate the hash since +// inlining could potentially reorder instructions and generate different +// results for the same effective input value fVal. +static NOINLINE int FindGridCell(const float fMin, const float fMax, const float fVal) +{ + const float fIndex = g_iCells * ((fVal-fMin)/(fMax-fMin)); + const int iIndex = (int)fIndex; + return iIndex < g_iCells ? (iIndex >= 0 ? iIndex : 0) : (g_iCells - 1); +} + +static void MergeVertsFast(int piTriList_in_and_out[], STmpVert pTmpVert[], const SMikkTSpaceContext * pContext, const int iL_in, const int iR_in); +static void MergeVertsSlow(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int pTable[], const int iEntries); +static void GenerateSharedVerticesIndexListSlow(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn); + +static void GenerateSharedVerticesIndexList(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn) +{ + + // Generate bounding box + int * piHashTable=NULL, * piHashCount=NULL, * piHashOffsets=NULL, * piHashCount2=NULL; + STmpVert * pTmpVert = NULL; + int i=0, iChannel=0, k=0, e=0; + int iMaxCount=0; + SVec3 vMin = GetPosition(pContext, 0), vMax = vMin, vDim; + float fMin, fMax; + for (i=1; i<(iNrTrianglesIn*3); i++) + { + const int index = piTriList_in_and_out[i]; + + const SVec3 vP = GetPosition(pContext, index); + if (vMin.x > vP.x) vMin.x = vP.x; + else if (vMax.x < vP.x) vMax.x = vP.x; + if (vMin.y > vP.y) vMin.y = vP.y; + else if (vMax.y < vP.y) vMax.y = vP.y; + if (vMin.z > vP.z) vMin.z = vP.z; + else if (vMax.z < vP.z) vMax.z = vP.z; + } + + vDim = vsub(vMax,vMin); + iChannel = 0; + fMin = vMin.x; fMax=vMax.x; + if (vDim.y>vDim.x && vDim.y>vDim.z) + { + iChannel=1; + fMin = vMin.y; + fMax = vMax.y; + } + else if (vDim.z>vDim.x) + { + iChannel=2; + fMin = vMin.z; + fMax = vMax.z; + } + + // make allocations + piHashTable = (int *) malloc(sizeof(int)*iNrTrianglesIn*3); + piHashCount = (int *) malloc(sizeof(int)*g_iCells); + piHashOffsets = (int *) malloc(sizeof(int)*g_iCells); + piHashCount2 = (int *) malloc(sizeof(int)*g_iCells); + + if (piHashTable==NULL || piHashCount==NULL || piHashOffsets==NULL || piHashCount2==NULL) + { + if (piHashTable!=NULL) free(piHashTable); + if (piHashCount!=NULL) free(piHashCount); + if (piHashOffsets!=NULL) free(piHashOffsets); + if (piHashCount2!=NULL) free(piHashCount2); + GenerateSharedVerticesIndexListSlow(piTriList_in_and_out, pContext, iNrTrianglesIn); + return; + } + memset(piHashCount, 0, sizeof(int)*g_iCells); + memset(piHashCount2, 0, sizeof(int)*g_iCells); + + // count amount of elements in each cell unit + for (i=0; i<(iNrTrianglesIn*3); i++) + { + const int index = piTriList_in_and_out[i]; + const SVec3 vP = GetPosition(pContext, index); + const float fVal = iChannel==0 ? vP.x : (iChannel==1 ? vP.y : vP.z); + const int iCell = FindGridCell(fMin, fMax, fVal); + ++piHashCount[iCell]; + } + + // evaluate start index of each cell. + piHashOffsets[0]=0; + for (k=1; kpTmpVert[l].vert[c]) fvMin[c]=pTmpVert[l].vert[c]; + if (fvMax[c]dx && dy>dz) channel=1; + else if (dz>dx) channel=2; + + fSep = 0.5f*(fvMax[channel]+fvMin[channel]); + + // stop if all vertices are NaNs + if (!isfinite(fSep)) + return; + + // terminate recursion when the separation/average value + // is no longer strictly between fMin and fMax values. + if (fSep>=fvMax[channel] || fSep<=fvMin[channel]) + { + // complete the weld + for (l=iL_in; l<=iR_in; l++) + { + int i = pTmpVert[l].index; + const int index = piTriList_in_and_out[i]; + const SVec3 vP = GetPosition(pContext, index); + const SVec3 vN = GetNormal(pContext, index); + const SVec3 vT = GetTexCoord(pContext, index); + + tbool bNotFound = TTRUE; + int l2=iL_in, i2rec=-1; + while (l20); // at least 2 entries + + // separate (by fSep) all points between iL_in and iR_in in pTmpVert[] + while (iL < iR) + { + tbool bReadyLeftSwap = TFALSE, bReadyRightSwap = TFALSE; + while ((!bReadyLeftSwap) && iL=iL_in && iL<=iR_in); + bReadyLeftSwap = !(pTmpVert[iL].vert[channel]=iL_in && iR<=iR_in); + bReadyRightSwap = pTmpVert[iR].vert[channel]m_pInterface->m_getNumFaces(pContext); f++) + { + const int verts = pContext->m_pInterface->m_getNumVerticesOfFace(pContext, f); + if (verts!=3 && verts!=4) continue; + + pTriInfos[iDstTriIndex].iOrgFaceNumber = f; + pTriInfos[iDstTriIndex].iTSpacesOffs = iTSpacesOffs; + + if (verts==3) + { + unsigned char * pVerts = pTriInfos[iDstTriIndex].vert_num; + pVerts[0]=0; pVerts[1]=1; pVerts[2]=2; + piTriList_out[iDstTriIndex*3+0] = MakeIndex(f, 0); + piTriList_out[iDstTriIndex*3+1] = MakeIndex(f, 1); + piTriList_out[iDstTriIndex*3+2] = MakeIndex(f, 2); + ++iDstTriIndex; // next + } + else + { + { + pTriInfos[iDstTriIndex+1].iOrgFaceNumber = f; + pTriInfos[iDstTriIndex+1].iTSpacesOffs = iTSpacesOffs; + } + + { + // need an order independent way to evaluate + // tspace on quads. This is done by splitting + // along the shortest diagonal. + const int i0 = MakeIndex(f, 0); + const int i1 = MakeIndex(f, 1); + const int i2 = MakeIndex(f, 2); + const int i3 = MakeIndex(f, 3); + const SVec3 T0 = GetTexCoord(pContext, i0); + const SVec3 T1 = GetTexCoord(pContext, i1); + const SVec3 T2 = GetTexCoord(pContext, i2); + const SVec3 T3 = GetTexCoord(pContext, i3); + const float distSQ_02 = LengthSquared(vsub(T2,T0)); + const float distSQ_13 = LengthSquared(vsub(T3,T1)); + tbool bQuadDiagIs_02; + if (distSQ_02m_pInterface->m_getPosition(pContext, pos, iF, iI); + res.x=pos[0]; res.y=pos[1]; res.z=pos[2]; + return res; +} + +static SVec3 GetNormal(const SMikkTSpaceContext * pContext, const int index) +{ + int iF, iI; + SVec3 res; float norm[3]; + IndexToData(&iF, &iI, index); + pContext->m_pInterface->m_getNormal(pContext, norm, iF, iI); + res.x=norm[0]; res.y=norm[1]; res.z=norm[2]; + return res; +} + +static SVec3 GetTexCoord(const SMikkTSpaceContext * pContext, const int index) +{ + int iF, iI; + SVec3 res; float texc[2]; + IndexToData(&iF, &iI, index); + pContext->m_pInterface->m_getTexCoord(pContext, texc, iF, iI); + res.x=texc[0]; res.y=texc[1]; res.z=1.0f; + return res; +} + +///////////////////////////////////////////////////////////////////////////////////////////////////// +///////////////////////////////////////////////////////////////////////////////////////////////////// + +typedef union { + struct + { + int i0, i1, f; + }; + int array[3]; +} SEdge; + +static void BuildNeighborsFast(STriInfo pTriInfos[], SEdge * pEdges, const int piTriListIn[], const int iNrTrianglesIn); +static void BuildNeighborsSlow(STriInfo pTriInfos[], const int piTriListIn[], const int iNrTrianglesIn); + +// returns the texture area times 2 +static float CalcTexArea(const SMikkTSpaceContext * pContext, const int indices[]) +{ + const SVec3 t1 = GetTexCoord(pContext, indices[0]); + const SVec3 t2 = GetTexCoord(pContext, indices[1]); + const SVec3 t3 = GetTexCoord(pContext, indices[2]); + + const float t21x = t2.x-t1.x; + const float t21y = t2.y-t1.y; + const float t31x = t3.x-t1.x; + const float t31y = t3.y-t1.y; + + const float fSignedAreaSTx2 = t21x*t31y - t21y*t31x; + + return fSignedAreaSTx2<0 ? (-fSignedAreaSTx2) : fSignedAreaSTx2; +} + +static void InitTriInfo(STriInfo pTriInfos[], const int piTriListIn[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn) +{ + int f=0, i=0, t=0; + // pTriInfos[f].iFlag is cleared in GenerateInitialVerticesIndexList() which is called before this function. + + // generate neighbor info list + for (f=0; f0 ? ORIENT_PRESERVING : 0); + + if ( NotZero(fSignedAreaSTx2) ) + { + const float fAbsArea = fabsf(fSignedAreaSTx2); + const float fLenOs = Length(vOs); + const float fLenOt = Length(vOt); + const float fS = (pTriInfos[f].iFlag&ORIENT_PRESERVING)==0 ? (-1.0f) : 1.0f; + if ( NotZero(fLenOs) ) pTriInfos[f].vOs = vscale(fS/fLenOs, vOs); + if ( NotZero(fLenOt) ) pTriInfos[f].vOt = vscale(fS/fLenOt, vOt); + + // evaluate magnitudes prior to normalization of vOs and vOt + pTriInfos[f].fMagS = fLenOs / fAbsArea; + pTriInfos[f].fMagT = fLenOt / fAbsArea; + + // if this is a good triangle + if ( NotZero(pTriInfos[f].fMagS) && NotZero(pTriInfos[f].fMagT)) + pTriInfos[f].iFlag &= (~GROUP_WITH_ANY); + } + } + + // force otherwise healthy quads to a fixed orientation + while (t<(iNrTrianglesIn-1)) + { + const int iFO_a = pTriInfos[t].iOrgFaceNumber; + const int iFO_b = pTriInfos[t+1].iOrgFaceNumber; + if (iFO_a==iFO_b) // this is a quad + { + const tbool bIsDeg_a = (pTriInfos[t].iFlag&MARK_DEGENERATE)!=0 ? TTRUE : TFALSE; + const tbool bIsDeg_b = (pTriInfos[t+1].iFlag&MARK_DEGENERATE)!=0 ? TTRUE : TFALSE; + + // bad triangles should already have been removed by + // DegenPrologue(), but just in case check bIsDeg_a and bIsDeg_a are false + if ((bIsDeg_a||bIsDeg_b)==TFALSE) + { + const tbool bOrientA = (pTriInfos[t].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE; + const tbool bOrientB = (pTriInfos[t+1].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE; + // if this happens the quad has extremely bad mapping!! + if (bOrientA!=bOrientB) + { + //printf("found quad with bad mapping\n"); + tbool bChooseOrientFirstTri = TFALSE; + if ((pTriInfos[t+1].iFlag&GROUP_WITH_ANY)!=0) bChooseOrientFirstTri = TTRUE; + else if ( CalcTexArea(pContext, &piTriListIn[t*3+0]) >= CalcTexArea(pContext, &piTriListIn[(t+1)*3+0]) ) + bChooseOrientFirstTri = TTRUE; + + // force match + { + const int t0 = bChooseOrientFirstTri ? t : (t+1); + const int t1 = bChooseOrientFirstTri ? (t+1) : t; + pTriInfos[t1].iFlag &= (~ORIENT_PRESERVING); // clear first + pTriInfos[t1].iFlag |= (pTriInfos[t0].iFlag&ORIENT_PRESERVING); // copy bit + } + } + } + t += 2; + } + else + ++t; + } + + // match up edge pairs + { + SEdge * pEdges = (SEdge *) malloc(sizeof(SEdge)*iNrTrianglesIn*3); + if (pEdges==NULL) + BuildNeighborsSlow(pTriInfos, piTriListIn, iNrTrianglesIn); + else + { + BuildNeighborsFast(pTriInfos, pEdges, piTriListIn, iNrTrianglesIn); + + free(pEdges); + } + } +} + +///////////////////////////////////////////////////////////////////////////////////////////////////// +///////////////////////////////////////////////////////////////////////////////////////////////////// + +static tbool AssignRecur(const int piTriListIn[], STriInfo psTriInfos[], const int iMyTriIndex, SGroup * pGroup); +static void AddTriToGroup(SGroup * pGroup, const int iTriIndex); + +static int Build4RuleGroups(STriInfo pTriInfos[], SGroup pGroups[], int piGroupTrianglesBuffer[], const int piTriListIn[], const int iNrTrianglesIn) +{ + const int iNrMaxGroups = iNrTrianglesIn*3; + int iNrActiveGroups = 0; + int iOffset = 0, f=0, i=0; + (void)iNrMaxGroups; /* quiet warnings in non debug mode */ + for (f=0; fiVertexRepresentitive = vert_index; + pTriInfos[f].AssignedGroup[i]->bOrientPreservering = (pTriInfos[f].iFlag&ORIENT_PRESERVING)!=0; + pTriInfos[f].AssignedGroup[i]->iNrFaces = 0; + pTriInfos[f].AssignedGroup[i]->pFaceIndices = &piGroupTrianglesBuffer[iOffset]; + ++iNrActiveGroups; + + AddTriToGroup(pTriInfos[f].AssignedGroup[i], f); + bOrPre = (pTriInfos[f].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE; + neigh_indexL = pTriInfos[f].FaceNeighbors[i]; + neigh_indexR = pTriInfos[f].FaceNeighbors[i>0?(i-1):2]; + if (neigh_indexL>=0) // neighbor + { + const tbool bAnswer = + AssignRecur(piTriListIn, pTriInfos, neigh_indexL, + pTriInfos[f].AssignedGroup[i] ); + + const tbool bOrPre2 = (pTriInfos[neigh_indexL].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE; + const tbool bDiff = bOrPre!=bOrPre2 ? TTRUE : TFALSE; + assert(bAnswer || bDiff); + (void)bAnswer, (void)bDiff; /* quiet warnings in non debug mode */ + } + if (neigh_indexR>=0) // neighbor + { + const tbool bAnswer = + AssignRecur(piTriListIn, pTriInfos, neigh_indexR, + pTriInfos[f].AssignedGroup[i] ); + + const tbool bOrPre2 = (pTriInfos[neigh_indexR].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE; + const tbool bDiff = bOrPre!=bOrPre2 ? TTRUE : TFALSE; + assert(bAnswer || bDiff); + (void)bAnswer, (void)bDiff; /* quiet warnings in non debug mode */ + } + + // update offset + iOffset += pTriInfos[f].AssignedGroup[i]->iNrFaces; + // since the groups are disjoint a triangle can never + // belong to more than 3 groups. Subsequently something + // is completely screwed if this assertion ever hits. + assert(iOffset <= iNrMaxGroups); + } + } + } + + return iNrActiveGroups; +} + +static void AddTriToGroup(SGroup * pGroup, const int iTriIndex) +{ + pGroup->pFaceIndices[pGroup->iNrFaces] = iTriIndex; + ++pGroup->iNrFaces; +} + +static tbool AssignRecur(const int piTriListIn[], STriInfo psTriInfos[], + const int iMyTriIndex, SGroup * pGroup) +{ + STriInfo * pMyTriInfo = &psTriInfos[iMyTriIndex]; + + // track down vertex + const int iVertRep = pGroup->iVertexRepresentitive; + const int * pVerts = &piTriListIn[3*iMyTriIndex+0]; + int i=-1; + if (pVerts[0]==iVertRep) i=0; + else if (pVerts[1]==iVertRep) i=1; + else if (pVerts[2]==iVertRep) i=2; + assert(i>=0 && i<3); + + // early out + if (pMyTriInfo->AssignedGroup[i] == pGroup) return TTRUE; + else if (pMyTriInfo->AssignedGroup[i]!=NULL) return TFALSE; + if ((pMyTriInfo->iFlag&GROUP_WITH_ANY)!=0) + { + // first to group with a group-with-anything triangle + // determines it's orientation. + // This is the only existing order dependency in the code!! + if ( pMyTriInfo->AssignedGroup[0] == NULL && + pMyTriInfo->AssignedGroup[1] == NULL && + pMyTriInfo->AssignedGroup[2] == NULL ) + { + pMyTriInfo->iFlag &= (~ORIENT_PRESERVING); + pMyTriInfo->iFlag |= (pGroup->bOrientPreservering ? ORIENT_PRESERVING : 0); + } + } + { + const tbool bOrient = (pMyTriInfo->iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE; + if (bOrient != pGroup->bOrientPreservering) return TFALSE; + } + + AddTriToGroup(pGroup, iMyTriIndex); + pMyTriInfo->AssignedGroup[i] = pGroup; + + { + const int neigh_indexL = pMyTriInfo->FaceNeighbors[i]; + const int neigh_indexR = pMyTriInfo->FaceNeighbors[i>0?(i-1):2]; + if (neigh_indexL>=0) + AssignRecur(piTriListIn, psTriInfos, neigh_indexL, pGroup); + if (neigh_indexR>=0) + AssignRecur(piTriListIn, psTriInfos, neigh_indexR, pGroup); + } + + + + return TTRUE; +} + +///////////////////////////////////////////////////////////////////////////////////////////////////// +///////////////////////////////////////////////////////////////////////////////////////////////////// + +static tbool CompareSubGroups(const SSubGroup * pg1, const SSubGroup * pg2); +static void QuickSort(int* pSortBuffer, int iLeft, int iRight, unsigned int uSeed); +static STSpace EvalTspace(int face_indices[], const int iFaces, const int piTriListIn[], const STriInfo pTriInfos[], const SMikkTSpaceContext * pContext, const int iVertexRepresentitive); + +static tbool GenerateTSpaces(STSpace psTspace[], const STriInfo pTriInfos[], const SGroup pGroups[], + const int iNrActiveGroups, const int piTriListIn[], const float fThresCos, + const SMikkTSpaceContext * pContext) +{ + STSpace * pSubGroupTspace = NULL; + SSubGroup * pUniSubGroups = NULL; + int * pTmpMembers = NULL; + int iMaxNrFaces=0, iUniqueTspaces=0, g=0, i=0; + for (g=0; giNrFaces; i++) // triangles + { + const int f = pGroup->pFaceIndices[i]; // triangle number + int index=-1, iVertIndex=-1, iOF_1=-1, iMembers=0, j=0, l=0; + SSubGroup tmp_group; + tbool bFound; + SVec3 n, vOs, vOt; + if (pTriInfos[f].AssignedGroup[0]==pGroup) index=0; + else if (pTriInfos[f].AssignedGroup[1]==pGroup) index=1; + else if (pTriInfos[f].AssignedGroup[2]==pGroup) index=2; + assert(index>=0 && index<3); + + iVertIndex = piTriListIn[f*3+index]; + assert(iVertIndex==pGroup->iVertexRepresentitive); + + // is normalized already + n = GetNormal(pContext, iVertIndex); + + // project + vOs = vsub(pTriInfos[f].vOs, vscale(vdot(n,pTriInfos[f].vOs), n)); + vOt = vsub(pTriInfos[f].vOt, vscale(vdot(n,pTriInfos[f].vOt), n)); + if ( VNotZero(vOs) ) vOs = Normalize(vOs); + if ( VNotZero(vOt) ) vOt = Normalize(vOt); + + // original face number + iOF_1 = pTriInfos[f].iOrgFaceNumber; + + iMembers = 0; + for (j=0; jiNrFaces; j++) + { + const int t = pGroup->pFaceIndices[j]; // triangle number + const int iOF_2 = pTriInfos[t].iOrgFaceNumber; + + // project + SVec3 vOs2 = vsub(pTriInfos[t].vOs, vscale(vdot(n,pTriInfos[t].vOs), n)); + SVec3 vOt2 = vsub(pTriInfos[t].vOt, vscale(vdot(n,pTriInfos[t].vOt), n)); + if ( VNotZero(vOs2) ) vOs2 = Normalize(vOs2); + if ( VNotZero(vOt2) ) vOt2 = Normalize(vOt2); + + { + const tbool bAny = ( (pTriInfos[f].iFlag | pTriInfos[t].iFlag) & GROUP_WITH_ANY )!=0 ? TTRUE : TFALSE; + // make sure triangles which belong to the same quad are joined. + const tbool bSameOrgFace = iOF_1==iOF_2 ? TTRUE : TFALSE; + + const float fCosS = vdot(vOs,vOs2); + const float fCosT = vdot(vOt,vOt2); + + assert(f!=t || bSameOrgFace); // sanity check + if (bAny || bSameOrgFace || (fCosS>fThresCos && fCosT>fThresCos)) + pTmpMembers[iMembers++] = t; + } + } + + // sort pTmpMembers + tmp_group.iNrFaces = iMembers; + tmp_group.pTriMembers = pTmpMembers; + if (iMembers>1) + { + unsigned int uSeed = INTERNAL_RND_SORT_SEED; // could replace with a random seed? + QuickSort(pTmpMembers, 0, iMembers-1, uSeed); + } + + // look for an existing match + bFound = TFALSE; + l=0; + while (liVertexRepresentitive); + ++iUniqueSubGroups; + } + + // output tspace + { + const int iOffs = pTriInfos[f].iTSpacesOffs; + const int iVert = pTriInfos[f].vert_num[index]; + STSpace * pTS_out = &psTspace[iOffs+iVert]; + assert(pTS_out->iCounter<2); + assert(((pTriInfos[f].iFlag&ORIENT_PRESERVING)!=0) == pGroup->bOrientPreservering); + if (pTS_out->iCounter==1) + { + *pTS_out = AvgTSpace(pTS_out, &pSubGroupTspace[l]); + pTS_out->iCounter = 2; // update counter + pTS_out->bOrient = pGroup->bOrientPreservering; + } + else + { + assert(pTS_out->iCounter==0); + *pTS_out = pSubGroupTspace[l]; + pTS_out->iCounter = 1; // update counter + pTS_out->bOrient = pGroup->bOrientPreservering; + } + } + } + + // clean up and offset iUniqueTspaces + for (s=0; s=0 && i<3); + + // project + index = piTriListIn[3*f+i]; + n = GetNormal(pContext, index); + vOs = vsub(pTriInfos[f].vOs, vscale(vdot(n,pTriInfos[f].vOs), n)); + vOt = vsub(pTriInfos[f].vOt, vscale(vdot(n,pTriInfos[f].vOt), n)); + if ( VNotZero(vOs) ) vOs = Normalize(vOs); + if ( VNotZero(vOt) ) vOt = Normalize(vOt); + + i2 = piTriListIn[3*f + (i<2?(i+1):0)]; + i1 = piTriListIn[3*f + i]; + i0 = piTriListIn[3*f + (i>0?(i-1):2)]; + + p0 = GetPosition(pContext, i0); + p1 = GetPosition(pContext, i1); + p2 = GetPosition(pContext, i2); + v1 = vsub(p0,p1); + v2 = vsub(p2,p1); + + // project + v1 = vsub(v1, vscale(vdot(n,v1),n)); if ( VNotZero(v1) ) v1 = Normalize(v1); + v2 = vsub(v2, vscale(vdot(n,v2),n)); if ( VNotZero(v2) ) v2 = Normalize(v2); + + // weight contribution by the angle + // between the two edge vectors + fCos = vdot(v1,v2); fCos=fCos>1?1:(fCos<(-1) ? (-1) : fCos); + fAngle = (float) acos(fCos); + fMagS = pTriInfos[f].fMagS; + fMagT = pTriInfos[f].fMagT; + + res.vOs=vadd(res.vOs, vscale(fAngle,vOs)); + res.vOt=vadd(res.vOt,vscale(fAngle,vOt)); + res.fMagS+=(fAngle*fMagS); + res.fMagT+=(fAngle*fMagT); + fAngleSum += fAngle; + } + } + + // normalize + if ( VNotZero(res.vOs) ) res.vOs = Normalize(res.vOs); + if ( VNotZero(res.vOt) ) res.vOt = Normalize(res.vOt); + if (fAngleSum>0) + { + res.fMagS /= fAngleSum; + res.fMagT /= fAngleSum; + } + + return res; +} + +static tbool CompareSubGroups(const SSubGroup * pg1, const SSubGroup * pg2) +{ + tbool bStillSame=TTRUE; + int i=0; + if (pg1->iNrFaces!=pg2->iNrFaces) return TFALSE; + while (iiNrFaces && bStillSame) + { + bStillSame = pg1->pTriMembers[i]==pg2->pTriMembers[i] ? TTRUE : TFALSE; + if (bStillSame) ++i; + } + return bStillSame; +} + +static void QuickSort(int* pSortBuffer, int iLeft, int iRight, unsigned int uSeed) +{ + int iL, iR, n, index, iMid, iTmp; + + // Random + unsigned int t=uSeed&31; + t=(uSeed<>(32-t)); + uSeed=uSeed+t+3; + // Random end + + iL=iLeft; iR=iRight; + n = (iR-iL)+1; + assert(n>=0); + index = (int) (uSeed%n); + + iMid=pSortBuffer[index + iL]; + + + do + { + while (pSortBuffer[iL] < iMid) + ++iL; + while (pSortBuffer[iR] > iMid) + --iR; + + if (iL <= iR) + { + iTmp = pSortBuffer[iL]; + pSortBuffer[iL] = pSortBuffer[iR]; + pSortBuffer[iR] = iTmp; + ++iL; --iR; + } + } + while (iL <= iR); + + if (iLeft < iR) + QuickSort(pSortBuffer, iLeft, iR, uSeed); + if (iL < iRight) + QuickSort(pSortBuffer, iL, iRight, uSeed); +} + +///////////////////////////////////////////////////////////////////////////////////////////// +///////////////////////////////////////////////////////////////////////////////////////////// + +static void QuickSortEdges(SEdge * pSortBuffer, int iLeft, int iRight, const int channel, unsigned int uSeed); +static void GetEdge(int * i0_out, int * i1_out, int * edgenum_out, const int indices[], const int i0_in, const int i1_in); + +static void BuildNeighborsFast(STriInfo pTriInfos[], SEdge * pEdges, const int piTriListIn[], const int iNrTrianglesIn) +{ + // build array of edges + unsigned int uSeed = INTERNAL_RND_SORT_SEED; // could replace with a random seed? + int iEntries=0, iCurStartIndex=-1, f=0, i=0; + for (f=0; f pSortBuffer[iRight].array[channel]) + { + sTmp = pSortBuffer[iLeft]; + pSortBuffer[iLeft] = pSortBuffer[iRight]; + pSortBuffer[iRight] = sTmp; + } + return; + } + + // Random + t=uSeed&31; + t=(uSeed<>(32-t)); + uSeed=uSeed+t+3; + // Random end + + iL = iLeft; + iR = iRight; + n = (iR-iL)+1; + assert(n>=0); + index = (int) (uSeed%n); + + iMid=pSortBuffer[index + iL].array[channel]; + + do + { + while (pSortBuffer[iL].array[channel] < iMid) + ++iL; + while (pSortBuffer[iR].array[channel] > iMid) + --iR; + + if (iL <= iR) + { + sTmp = pSortBuffer[iL]; + pSortBuffer[iL] = pSortBuffer[iR]; + pSortBuffer[iR] = sTmp; + ++iL; --iR; + } + } + while (iL <= iR); + + if (iLeft < iR) + QuickSortEdges(pSortBuffer, iLeft, iR, channel, uSeed); + if (iL < iRight) + QuickSortEdges(pSortBuffer, iL, iRight, channel, uSeed); +} + +// resolve ordering and edge number +static void GetEdge(int * i0_out, int * i1_out, int * edgenum_out, const int indices[], const int i0_in, const int i1_in) +{ + *edgenum_out = -1; + + // test if first index is on the edge + if (indices[0]==i0_in || indices[0]==i1_in) + { + // test if second index is on the edge + if (indices[1]==i0_in || indices[1]==i1_in) + { + edgenum_out[0]=0; // first edge + i0_out[0]=indices[0]; + i1_out[0]=indices[1]; + } + else + { + edgenum_out[0]=2; // third edge + i0_out[0]=indices[2]; + i1_out[0]=indices[0]; + } + } + else + { + // only second and third index is on the edge + edgenum_out[0]=1; // second edge + i0_out[0]=indices[1]; + i1_out[0]=indices[2]; + } +} + + +///////////////////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////// Degenerate triangles //////////////////////////////////// + +static void DegenPrologue(STriInfo pTriInfos[], int piTriList_out[], const int iNrTrianglesIn, const int iTotTris) +{ + int iNextGoodTriangleSearchIndex=-1; + tbool bStillFindingGoodOnes; + + // locate quads with only one good triangle + int t=0; + while (t<(iTotTris-1)) + { + const int iFO_a = pTriInfos[t].iOrgFaceNumber; + const int iFO_b = pTriInfos[t+1].iOrgFaceNumber; + if (iFO_a==iFO_b) // this is a quad + { + const tbool bIsDeg_a = (pTriInfos[t].iFlag&MARK_DEGENERATE)!=0 ? TTRUE : TFALSE; + const tbool bIsDeg_b = (pTriInfos[t+1].iFlag&MARK_DEGENERATE)!=0 ? TTRUE : TFALSE; + if ((bIsDeg_a^bIsDeg_b)!=0) + { + pTriInfos[t].iFlag |= QUAD_ONE_DEGEN_TRI; + pTriInfos[t+1].iFlag |= QUAD_ONE_DEGEN_TRI; + } + t += 2; + } + else + ++t; + } + + // reorder list so all degen triangles are moved to the back + // without reordering the good triangles + iNextGoodTriangleSearchIndex = 1; + t=0; + bStillFindingGoodOnes = TTRUE; + while (t (t+1)); + + // swap triangle t0 and t1 + if (!bJustADegenerate) + { + int i=0; + for (i=0; i<3; i++) + { + const int index = piTriList_out[t0*3+i]; + piTriList_out[t0*3+i] = piTriList_out[t1*3+i]; + piTriList_out[t1*3+i] = index; + } + { + const STriInfo tri_info = pTriInfos[t0]; + pTriInfos[t0] = pTriInfos[t1]; + pTriInfos[t1] = tri_info; + } + } + else + bStillFindingGoodOnes = TFALSE; // this is not supposed to happen + } + + if (bStillFindingGoodOnes) ++t; + } + + assert(bStillFindingGoodOnes); // code will still work. + assert(iNrTrianglesIn == t); +} + +static void DegenEpilogue(STSpace psTspace[], STriInfo pTriInfos[], int piTriListIn[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn, const int iTotTris) +{ + int t=0, i=0; + // deal with degenerate triangles + // punishment for degenerate triangles is O(N^2) + for (t=iNrTrianglesIn; t http://image.diku.dk/projects/media/morten.mikkelsen.08.pdf + * Note that though the tangent spaces at the vertices are generated in an order-independent way, + * by this implementation, the interpolated tangent space is still affected by which diagonal is + * chosen to split each quad. A sensible solution is to have your tools pipeline always + * split quads by the shortest diagonal. This choice is order-independent and works with mirroring. + * If these have the same length then compare the diagonals defined by the texture coordinates. + * XNormal which is a tool for baking normal maps allows you to write your own tangent space plugin + * and also quad triangulator plugin. + */ + + +typedef int tbool; +typedef struct SMikkTSpaceContext SMikkTSpaceContext; + +typedef struct { + // Returns the number of faces (triangles/quads) on the mesh to be processed. + int (*m_getNumFaces)(const SMikkTSpaceContext * pContext); + + // Returns the number of vertices on face number iFace + // iFace is a number in the range {0, 1, ..., getNumFaces()-1} + int (*m_getNumVerticesOfFace)(const SMikkTSpaceContext * pContext, const int iFace); + + // returns the position/normal/texcoord of the referenced face of vertex number iVert. + // iVert is in the range {0,1,2} for triangles and {0,1,2,3} for quads. + void (*m_getPosition)(const SMikkTSpaceContext * pContext, float fvPosOut[], const int iFace, const int iVert); + void (*m_getNormal)(const SMikkTSpaceContext * pContext, float fvNormOut[], const int iFace, const int iVert); + void (*m_getTexCoord)(const SMikkTSpaceContext * pContext, float fvTexcOut[], const int iFace, const int iVert); + + // either (or both) of the two setTSpace callbacks can be set. + // The call-back m_setTSpaceBasic() is sufficient for basic normal mapping. + + // This function is used to return the tangent and fSign to the application. + // fvTangent is a unit length vector. + // For normal maps it is sufficient to use the following simplified version of the bitangent which is generated at pixel/vertex level. + // bitangent = fSign * cross(vN, tangent); + // Note that the results are returned unindexed. It is possible to generate a new index list + // But averaging/overwriting tangent spaces by using an already existing index list WILL produce INCRORRECT results. + // DO NOT! use an already existing index list. + void (*m_setTSpaceBasic)(const SMikkTSpaceContext * pContext, const float fvTangent[], const float fSign, const int iFace, const int iVert); + + // This function is used to return tangent space results to the application. + // fvTangent and fvBiTangent are unit length vectors and fMagS and fMagT are their + // true magnitudes which can be used for relief mapping effects. + // fvBiTangent is the "real" bitangent and thus may not be perpendicular to fvTangent. + // However, both are perpendicular to the vertex normal. + // For normal maps it is sufficient to use the following simplified version of the bitangent which is generated at pixel/vertex level. + // fSign = bIsOrientationPreserving ? 1.0f : (-1.0f); + // bitangent = fSign * cross(vN, tangent); + // Note that the results are returned unindexed. It is possible to generate a new index list + // But averaging/overwriting tangent spaces by using an already existing index list WILL produce INCRORRECT results. + // DO NOT! use an already existing index list. + void (*m_setTSpace)(const SMikkTSpaceContext * pContext, const float fvTangent[], const float fvBiTangent[], const float fMagS, const float fMagT, + const tbool bIsOrientationPreserving, const int iFace, const int iVert); +} SMikkTSpaceInterface; + +struct SMikkTSpaceContext +{ + SMikkTSpaceInterface * m_pInterface; // initialized with callback functions + void * m_pUserData; // pointer to client side mesh data etc. (passed as the first parameter with every interface call) +}; + +// these are both thread safe! +tbool genTangSpaceDefault(const SMikkTSpaceContext * pContext); // Default (recommended) fAngularThreshold is 180 degrees (which means threshold disabled) +tbool genTangSpace(const SMikkTSpaceContext * pContext, const float fAngularThreshold); + + +// To avoid visual errors (distortions/unwanted hard edges in lighting), when using sampled normal maps, the +// normal map sampler must use the exact inverse of the pixel shader transformation. +// The most efficient transformation we can possibly do in the pixel shader is +// achieved by using, directly, the "unnormalized" interpolated tangent, bitangent and vertex normal: vT, vB and vN. +// pixel shader (fast transform out) +// vNout = normalize( vNt.x * vT + vNt.y * vB + vNt.z * vN ); +// where vNt is the tangent space normal. The normal map sampler must likewise use the +// interpolated and "unnormalized" tangent, bitangent and vertex normal to be compliant with the pixel shader. +// sampler does (exact inverse of pixel shader): +// float3 row0 = cross(vB, vN); +// float3 row1 = cross(vN, vT); +// float3 row2 = cross(vT, vB); +// float fSign = dot(vT, row0)<0 ? -1 : 1; +// vNt = normalize( fSign * float3(dot(vNout,row0), dot(vNout,row1), dot(vNout,row2)) ); +// where vNout is the sampled normal in some chosen 3D space. +// +// Should you choose to reconstruct the bitangent in the pixel shader instead +// of the vertex shader, as explained earlier, then be sure to do this in the normal map sampler also. +// Finally, beware of quad triangulations. If the normal map sampler doesn't use the same triangulation of +// quads as your renderer then problems will occur since the interpolated tangent spaces will differ +// eventhough the vertex level tangent spaces match. This can be solved either by triangulating before +// sampling/exporting or by using the order-independent choice of diagonal for splitting quads suggested earlier. +// However, this must be used both by the sampler and your tools/rendering pipeline. + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/contrib/cgltf-tangents/README.md b/contrib/cgltf-tangents/README.md new file mode 100644 index 0000000..2a68b27 --- /dev/null +++ b/contrib/cgltf-tangents/README.md @@ -0,0 +1,42 @@ +# cgltf-tangents + +A library to compute missing tangent vectors in glTF models using MikkTSpace. + +## Example + +``` +// Load the glTF scene and buffers as usual. +cgltf_result result = cgltf_parse_file(&options, filepath, &data); +cgltf_load_buffers(&options, data, filepath); + +// Compute missing tangents. +cgltfTangentBuffer* tangent_buffers = 0; +cgltf_size num_tangent_buffers = 0; +cgltf_compute_tangents(&options, data, &tangent_buffers, &num_tangent_buffers); +``` + +## About + +This is a single-header/source library that combines +[MikkTSpace](https://github.com/mmikk/MikkTSpace) and +[cgltf](https://github.com/jkuhlmann/cgltf) to compute missing tangent vectors +for models. + +Mesh primitives in glTF may have a normal map but not necessarily tangent +vectors. An example is the +[DamagedHelmet](https://github.com/KhronosGroup/glTF-Sample-Models/tree/master/2.0/DamagedHelmet/glTF) +sample. From the +[spec](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#meshes): + +*"When tangents are not specified, client implementations SHOULD calculate +tangents using default MikkTSpace algorithms with the specified vertex +positions, normals, and texture coordinates associated with the normal texture."* + +cgltf-tangents takes an input glTF scene and scans it for mesh primitives that +have a normal map but no tangents. cgltf-tangents then invokes MikkTSpace to +compute tangents for those mesh primitives and outputs an array of tangent +buffers. The client can then upload these buffers to GPU memory for rendering. + +See `test/` for a complete example. + +MikkTSpace is packaged here for convenience. cgltf must be obtained separately. diff --git a/contrib/cgltf-tangents/cgltf_tangents.c b/contrib/cgltf-tangents/cgltf_tangents.c new file mode 100644 index 0000000..80b1e56 --- /dev/null +++ b/contrib/cgltf-tangents/cgltf_tangents.c @@ -0,0 +1,618 @@ +/* +Copyright 2022 Marc Sunet + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation and/or +other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include "cgltf_tangents.h" +#include "cgltf.h" + +#include "MikkTSpace/mikktspace.h" + +#include +#include +#include +#include +#include + +#ifdef CGLTF_TANGENTS_DEBUG +#include +#define DLOG printf +#else +#define DLOG(...) +#endif + +#include // TODO: Remove me. + +#define CGLTF_OPTIONS_MALLOC(size) \ + options->memory.alloc(options->memory.user_data, size) + +#define CGLTF_OPTIONS_FREE(ptr) \ + options->memory.free(options->memory.user_data, ptr) + +static void* cgltf_default_alloc(void* user, cgltf_size size) { + (void)user; + return malloc(size); +} + +static void cgltf_default_free(void* user, void* ptr) { + (void)user; + free(ptr); +} + +static const cgltf_size NUM_TANGENT_COMPONENTS = 4; // X,Y,Z,fSign + +static float normalize_i8(int8_t x) { return (float)x / 128.0; } +static float normalize_u8(uint8_t x) { return (float)x / 255.0; } +static float normalize_i16(int16_t x) { return (float)x / 32768.0; } +static float normalize_u16(uint16_t x) { return (float)x / 65535.0; } +static float normalize_u32(uint32_t x) { return (float)x / 4294967295.0; } + +static cgltf_size num_vertex_attrib_components(cgltf_type type) { + switch (type) { + case cgltf_type_scalar: + return 1; + case cgltf_type_vec2: + return 2; + case cgltf_type_vec3: + return 3; + case cgltf_type_vec4: + return 4; + default: + assert(false); + return 0; + } +} + +static cgltf_size cgltf_component_type_size_bytes(cgltf_component_type type) { + switch (type) { + case cgltf_component_type_r_8: + return 1; + case cgltf_component_type_r_8u: + return 1; + case cgltf_component_type_r_16: + return 2; + case cgltf_component_type_r_16u: + return 2; + case cgltf_component_type_r_32u: + return 4; + case cgltf_component_type_r_32f: + return 4; + default: + assert(false); + return 0; + } +} + +static cgltf_size default_stride(cgltf_type type, + cgltf_component_type component_type) { + return num_vertex_attrib_components(type) * + cgltf_component_type_size_bytes(component_type); +} + +// ----------------------------------------------------------------------------- +// MikkTSpace interface + +// An array of values for a given vertex attribute or for vertex indices. +// For positions and normals, glTF mandates floats. +// Texcoords and indices can be different types and vary in size: 8-bit, 16-bit, +// or 32-bit. +// We store void* pointers so that we can do byte pointer arithmetic. +typedef struct Buffer { + const void* start; // X-coordinate of the first attribute. + const void* end; // One byte past the end of the buffer. + cgltf_size stride_bytes; // Stride in bytes between each value. + cgltf_component_type type; // Type of each value in the buffer. +} Buffer; + +// User data for mesh processing. +// See: https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#meshes +// Buffer pointers have the accessor + view offsets baked in so that we do the +// addition only once. +typedef struct SMikkUserData { + const cgltf_primitive* primitive; + // Index buffer may be empty (mesh primitive has no indices). + Buffer indices; + // Vertex attributes. + Buffer positions; + Buffer normals; + Buffer texcoords; + // Output tangents. + void* tangents; +} SMikkUserData; + +static cgltf_size get_vertex_index(const SMikkUserData* data, cgltf_size iFace, + cgltf_size iVert) { + const cgltf_primitive* primitive = data->primitive; + + // First compute a vertex index as if the mesh primitive had no indices. + cgltf_size vertex_idx = 0; + switch (primitive->type) { + case cgltf_primitive_type_triangles: + vertex_idx = iFace * 3 + iVert; + break; + case cgltf_primitive_type_triangle_strip: + // For triangle strips: + // face 0 -> verts 0, 1, 2 + // face 1 -> verts 1, 3, 2 (1, 2, 3 flipped) + // face 2 -> verts 2, 3, 4 + // face 3 -> verts 3, 5, 4 (3, 4, 5 flipped) + // ... + // face N=2k -> verts N, N+1, N+2 + // face N=2k+1 -> verts N, N+2, N+1 + if (iFace & 1) { + // Flip the winding of odd faces so that the is consistent with the even + // ones. + // iVert = 0 -> vert 0 + // iVert = 1 -> vert 2 + // iVert = 2 -> vert 1 + vertex_idx = iFace + (2 - iVert); + } else { + vertex_idx = iFace + iVert; + } + break; + case cgltf_primitive_type_triangle_fan: + // For triangle fans: + // face 0 -> verts 0, 1, 2 + // face 1 -> verts 0, 2, 3 + // face 2 -> verts 0, 3, 4 + // face 3 -> verts 0, 4, 5 + // ... + // face N -> verts 0, N=1, N=2 + if (iVert == 0) { + vertex_idx = 0; + } else { + vertex_idx = iFace + iVert; + } + break; + default: + assert(false); + break; + } + + // If the mesh primitive has vertex indices, then vertex_idx is actually the + // index of the index. Index the index buffer with vertex_idx to find the + // real vertex index. + if (primitive->indices != NULL) { + const void* p_idx = + data->indices.start + vertex_idx * data->indices.stride_bytes; + switch (data->indices.type) { + case cgltf_component_type_r_8: + vertex_idx = *((int8_t*)p_idx); + break; + case cgltf_component_type_r_8u: + vertex_idx = *((uint8_t*)p_idx); + break; + case cgltf_component_type_r_16: + vertex_idx = *((int16_t*)p_idx); + break; + case cgltf_component_type_r_16u: + vertex_idx = *((uint16_t*)p_idx); + break; + case cgltf_component_type_r_32u: + vertex_idx = *((uint32_t*)p_idx); + break; + default: + assert(false); + break; + } + } + + return vertex_idx; +} + +static const void* get_vertex(const Buffer* buffer, cgltf_size index) { + // Stride is the offset in bytes between vertex attributes. + const void* vertex = buffer->start + buffer->stride_bytes * index; + assert(vertex < buffer->end); + return vertex; +} + +static const void* get_position(const SMikkUserData* data, cgltf_size index) { + return get_vertex(&data->positions, index); +} + +static const void* get_normal(const SMikkUserData* data, cgltf_size index) { + return get_vertex(&data->normals, index); +} + +static const void* get_texcoord(const SMikkUserData* data, cgltf_size index) { + return get_vertex(&data->texcoords, index); +} + +static float* get_tangent(void* buffer, cgltf_size index) { + // Tangents are tightly packed. + return (float*)(buffer) + NUM_TANGENT_COMPONENTS * index; +} + +static int SMikk_get_num_faces(const SMikkTSpaceContext* pContext) { + SMikkUserData* data = (SMikkUserData*)pContext->m_pUserData; + const cgltf_primitive* primitive = data->primitive; + + // Find the number of effective vertices (vertices or indices) in the mesh + // primitive. + // + // https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#meshes + // + // "All attribute accessors for a given primitive MUST have the same count. + // When indices property is not defined, attribute accessors' count indicates + // the number of vertices to render; when indices property is defined, it + // indicates the upper (exclusive) bound on the index values in the indices + // accessor, i.e., all index values MUST be less than attribute accessors' + // count." + const cgltf_size num_verts = (primitive->indices != NULL) + ? primitive->indices->count + : primitive->attributes_count; + + // Determine the number of faces given the number of vertices. + // + // We use the fact that glTF only supports triangles for faces. + // https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#meshes + switch (primitive->type) { + case cgltf_primitive_type_triangles: + return (int)num_verts / 3; + case cgltf_primitive_type_triangle_strip: + case cgltf_primitive_type_triangle_fan: + return (int)num_verts - 2; + default: + return 0; + } +} + +int SMikk_get_num_vertices_of_face(const SMikkTSpaceContext* pContext, + const int iFace) { + // Triangles are the only faces supported by glTF. + // https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#meshes + return 3; +} + +void SMikk_get_position(const SMikkTSpaceContext* pContext, float fvPosOut[], + const int iFace, const int iVert) { + const SMikkUserData* data = (SMikkUserData*)pContext->m_pUserData; + const cgltf_primitive* primitive = data->primitive; + + const cgltf_size idx = get_vertex_index(data, iFace, iVert); + const float* coord = get_position(data, idx); + fvPosOut[0] = *coord++; + fvPosOut[1] = *coord++; + fvPosOut[2] = *coord; + DLOG("Position (face: %d, vert: %d): %f, %f, %f; idx: %lu\n", iFace, iVert, + fvPosOut[0], fvPosOut[1], fvPosOut[2], idx); +} + +void SMikk_get_normal(const SMikkTSpaceContext* pContext, float fvNormOut[], + const int iFace, const int iVert) { + const SMikkUserData* data = (SMikkUserData*)pContext->m_pUserData; + const cgltf_primitive* primitive = data->primitive; + + const cgltf_size idx = get_vertex_index(data, iFace, iVert); + const float* coord = get_normal(data, idx); + fvNormOut[0] = *coord++; + fvNormOut[1] = *coord++; + fvNormOut[2] = *coord; + DLOG("Normal (face: %d, vert: %d): %f, %f, %f\n", iFace, iVert, fvNormOut[0], + fvNormOut[1], fvNormOut[2]); +} + +void SMikk_get_texcoord(const SMikkTSpaceContext* pContext, float fvTexcOut[], + const int iFace, const int iVert) { + const SMikkUserData* data = (SMikkUserData*)pContext->m_pUserData; + const cgltf_primitive* primitive = data->primitive; + + const cgltf_size idx = get_vertex_index(data, iFace, iVert); + const void* coord = get_texcoord(data, idx); + switch (data->texcoords.type) { + case cgltf_component_type_r_8: { + const int8_t* c = coord; + fvTexcOut[0] = normalize_i8(*c++); + fvTexcOut[1] = normalize_i8(*c); + break; + } + case cgltf_component_type_r_8u: { + const uint8_t* c = coord; + fvTexcOut[0] = normalize_u8(*c++); + fvTexcOut[1] = normalize_u8(*c); + break; + } + case cgltf_component_type_r_16: { + const int16_t* c = coord; + fvTexcOut[0] = normalize_i16(*c++); + fvTexcOut[1] = normalize_i16(*c); + break; + } + case cgltf_component_type_r_16u: { + const uint16_t* c = coord; + fvTexcOut[0] = normalize_u16(*c++); + fvTexcOut[1] = normalize_u16(*c); + break; + } + case cgltf_component_type_r_32u: { + const uint32_t* c = coord; + fvTexcOut[0] = normalize_u32(*c++); + fvTexcOut[1] = normalize_u32(*c); + break; + } + case cgltf_component_type_r_32f: { + const float* c = coord; + fvTexcOut[0] = *c++; + fvTexcOut[1] = *c; + break; + } + default: + assert(false); + break; + } + DLOG("Texcoord (face: %d, vert: %d): %f, %f\n", iFace, iVert, fvTexcOut[0], + fvTexcOut[1]); +} + +void SMikk_set_TSpace_basic(const SMikkTSpaceContext* pContext, + const float fvTangent[], const float fSign, + const int iFace, const int iVert) { + SMikkUserData* data = (SMikkUserData*)pContext->m_pUserData; + const cgltf_primitive* primitive = data->primitive; + + const cgltf_size idx = get_vertex_index(data, iFace, iVert); + float* coord = get_tangent(data->tangents, idx); + *coord++ = fvTangent[0]; + *coord++ = fvTangent[1]; + *coord++ = fvTangent[2]; + *coord = fSign; + DLOG("Tangent (face: %d, vert: %d): %f, %f, %f; sign: %f\n", iFace, iVert, + fvTangent[0], fvTangent[1], fvTangent[2], fSign); +} + +// ----------------------------------------------------------------------------- + +static bool has_normal_map(const cgltf_primitive* primitive) { + return (primitive->material != NULL) && + (primitive->material->normal_texture.texture != NULL); +} + +static const cgltf_attribute* find_attribute(const cgltf_primitive* primitive, + cgltf_attribute_type type) { + for (cgltf_size i = 0; i < primitive->attributes_count; ++i) { + const cgltf_attribute* attrib = &primitive->attributes[i]; + if (attrib->type == type) { + return attrib; + } + } + return NULL; +} + +static bool has_attribute(const cgltf_primitive* primitive, + cgltf_attribute_type type) { + return find_attribute(primitive, type) != NULL; +} + +static bool has_positions3d(const cgltf_primitive* primitive) { + const cgltf_attribute* attrib = + find_attribute(primitive, cgltf_attribute_type_position); + if (attrib) { + return attrib->data->type == cgltf_type_vec3; + } + return false; +} + +static bool has_normals(const cgltf_primitive* primitive) { + return has_attribute(primitive, cgltf_attribute_type_normal); +} + +static bool has_texcoords(const cgltf_primitive* primitive) { + return has_attribute(primitive, cgltf_attribute_type_texcoord); +} + +static bool has_tangents(const cgltf_primitive* primitive) { + return has_attribute(primitive, cgltf_attribute_type_tangent); +} + +static bool has_indices(const cgltf_primitive* primitive) { + return primitive->indices != 0; +} + +static cgltfTangentBuffer compute_tangents(const cgltf_options* options, + const cgltf_data* data, + cgltf_primitive* primitive) { + cgltfTangentBuffer buffer = {0}; + SMikkUserData user = {0}; + cgltf_size num_verts = 0; + + user.primitive = primitive; + + if (primitive->indices != NULL) { + const cgltf_accessor* accessor = primitive->indices; + const cgltf_buffer_view* view = accessor->buffer_view; + const cgltf_size offset_bytes = accessor->offset + view->offset; + const void* buffer_data = view->buffer->data + offset_bytes; + const void* buffer_end = view->buffer->data + view->offset + view->size; + + user.indices.start = buffer_data; + user.indices.end = buffer_end; + // Indices are tightly packed, stride 0. + user.indices.stride_bytes = + default_stride(accessor->type, accessor->component_type); + user.indices.type = accessor->component_type; + } + + for (cgltf_size i = 0; i < primitive->attributes_count; ++i) { + const cgltf_attribute* attrib = &primitive->attributes[i]; + + if ((attrib->type == cgltf_attribute_type_position) || + (attrib->type == cgltf_attribute_type_normal) || + (attrib->type == cgltf_attribute_type_texcoord)) { + const cgltf_accessor* accessor = attrib->data; + const cgltf_buffer_view* view = accessor->buffer_view; + const cgltf_buffer* buffer = view->buffer; + const cgltf_size offset_bytes = accessor->offset + view->offset; + const cgltf_size stride_bytes = + view->stride > 0 + ? view->stride + : default_stride(accessor->type, accessor->component_type); + // const cgltf_size size_bytes = view->size; + const void* buffer_data = view->buffer->data + offset_bytes; + const void* buffer_end = view->buffer->data + view->offset + view->size; + + Buffer* attrib_buffer = 0; + + if (attrib->type == cgltf_attribute_type_position) { + // glTF currently mandates vec3 for positions. Caller should ensure + // this. + assert(accessor->type == cgltf_type_vec3); + num_verts = attrib->data->count; + attrib_buffer = &user.positions; + } else if (attrib->type == cgltf_attribute_type_normal) { + attrib_buffer = &user.normals; + } else if (attrib->type == cgltf_attribute_type_texcoord) { + attrib_buffer = &user.texcoords; + } + + attrib_buffer->start = buffer_data; + attrib_buffer->end = buffer_end; + attrib_buffer->stride_bytes = stride_bytes; + attrib_buffer->type = accessor->component_type; + } + } + + assert(user.positions.start); + assert(user.positions.end); + assert(user.normals.start); + assert(user.normals.end); + assert(user.texcoords.start); + assert(user.texcoords.end); + assert(num_verts > 0); + + const cgltf_size tangents_size_bytes = + num_verts * NUM_TANGENT_COMPONENTS * sizeof(float); + + user.tangents = CGLTF_OPTIONS_MALLOC(tangents_size_bytes); + if (!user.tangents) { + return buffer; + } + + SMikkTSpaceInterface interface = (SMikkTSpaceInterface){ + .m_getNumFaces = SMikk_get_num_faces, + .m_getNumVerticesOfFace = SMikk_get_num_vertices_of_face, + .m_getPosition = SMikk_get_position, + .m_getNormal = SMikk_get_normal, + .m_getTexCoord = SMikk_get_texcoord, + .m_setTSpaceBasic = SMikk_set_TSpace_basic, + }; + const SMikkTSpaceContext context = (SMikkTSpaceContext){ + .m_pInterface = &interface, + .m_pUserData = &user, + }; + if (!genTangSpaceDefault(&context)) { + return buffer; + } + + buffer.data = user.tangents; + buffer.size_bytes = tangents_size_bytes; + buffer.primitive = primitive; + + return buffer; +} + +static void process_primitive(const cgltf_options* options, + const cgltf_data* data, + cgltf_primitive* primitive, + cgltfTangentBuffer* tangent_buffers, + cgltf_size* num_tangent_buffers) { + DLOG("Processing primitive\n"); + cgltf_size cur_buffer = 0; + // TODO: MikkTSpace should not be used with models with vertex indices. One + // workaround is to unindex the mesh, compute tangents, and then re-index it. + if (((primitive->type == cgltf_primitive_type_triangle_fan) || + (primitive->type == cgltf_primitive_type_triangle_strip) || + (primitive->type == cgltf_primitive_type_triangles)) && + has_normal_map(primitive) && !has_tangents(primitive) && + has_positions3d(primitive) && has_normals(primitive) && + has_texcoords(primitive) && !has_indices(primitive)) { + *num_tangent_buffers += 1; + if (tangent_buffers) { + DLOG("Model with normal map missing tangents detected\n"); + tangent_buffers[cur_buffer] = compute_tangents(options, data, primitive); + if (tangent_buffers[cur_buffer].data) { + DLOG("Tangents computed\n"); + } + cur_buffer++; + } + } +} + +cgltf_result cgltf_compute_tangents(const cgltf_options* input_options, + const cgltf_data* data, + cgltfTangentBuffer** tangent_buffers, + cgltf_size* num_tangent_buffers) { + if ((input_options == NULL) || (data == NULL)) { + return cgltf_result_invalid_options; + } + + DLOG("cgltf_compute_tangents\n"); + + cgltf_options options = *input_options; + if (options.memory.alloc == NULL) { + options.memory.alloc = &cgltf_default_alloc; + } + if (options.memory.free == NULL) { + options.memory.free = &cgltf_default_free; + } + + // First pass: compute the number of tangent buffers to be created. + *num_tangent_buffers = 0; + for (cgltf_size mesh_idx = 0; mesh_idx < data->meshes_count; ++mesh_idx) { + const cgltf_mesh* mesh = &data->meshes[mesh_idx]; + + for (cgltf_size prim_idx = 0; prim_idx < mesh->primitives_count; + ++prim_idx) { + // Pass in null for the tangent buffers to just compute the number of + // buffers. + process_primitive(&options, data, &mesh->primitives[prim_idx], 0, + num_tangent_buffers); + } + } + DLOG("Number of primitives to be patched: %lu\n", *num_tangent_buffers); + + // Second pass: compute the tangents. + if (*num_tangent_buffers > 0) { + *tangent_buffers = + options.memory.alloc(options.memory.user_data, + *num_tangent_buffers * sizeof(cgltfTangentBuffer)); + if (!*tangent_buffers) { + return cgltf_result_out_of_memory; + } + + cgltf_size tangent_buffers_computed = 0; + + for (cgltf_size mesh_idx = 0; mesh_idx < data->meshes_count; ++mesh_idx) { + const cgltf_mesh* mesh = &data->meshes[mesh_idx]; + + for (cgltf_size prim_idx = 0; prim_idx < mesh->primitives_count; + ++prim_idx) { + process_primitive(&options, data, &mesh->primitives[prim_idx], + *tangent_buffers, &tangent_buffers_computed); + } + } + + assert(tangent_buffers_computed == *num_tangent_buffers); + } + + return cgltf_result_success; +} diff --git a/contrib/cgltf-tangents/cgltf_tangents.h b/contrib/cgltf-tangents/cgltf_tangents.h new file mode 100644 index 0000000..79e3502 --- /dev/null +++ b/contrib/cgltf-tangents/cgltf_tangents.h @@ -0,0 +1,67 @@ +/* +Copyright 2022 Marc Sunet + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation and/or +other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#ifndef CGLTF_TANGENTS_H_INCLUDED__ +#define CGLTF_TANGENTS_H_INCLUDED__ + +#include + +/// A buffer that holds tangent vectors. +/// +/// Tangent vectors are tightly packed in the array. +/// +/// Tangent vectors have 4 coordinates: (X,Y,Z) for the vector, W for the sign. +/// The usual rules of MikkTSpace apply, namely that the bitangent should be +/// computed as: +/// +/// bitangent = tangent.w * cross(normal, tangent.xyz); +/// +/// Refer to the MikkTSpace documentation for more details. +/// +/// The primitive pointer points to the mesh primitive for which the tangents in +/// this buffer were computed. When your application loads mesh primitives, it +/// can scan the cgltfTangetBuffer array outputed by cgltf_compute_tangents() to +/// see whether tangents were computed for the mesh primitive. +typedef struct cgltfTangentBuffer { + void* data; // X-coordinate of the first tangent vector. + cgltf_size size_bytes; // Total Size of data in bytes. + cgltf_primitive* primitive; // The primitive these tangents belong to. +} cgltfTangentBuffer; + +/// Compute tangent vectors for normal-mapped mesh primitives missing them. +/// +/// cgltf_options can be zeroed out but must be non-null. +/// +/// cgltf_data is the scene previously loaded by cgltf. +/// +/// out_tangent_buffers is an output array of tangent buffers, one buffer per +/// mesh primitive for which tangents were computed. +/// +/// out_num_tangent_buffers is the number of tangent buffers in the output +/// array. +cgltf_result cgltf_compute_tangents(const cgltf_options*, const cgltf_data*, + cgltfTangentBuffer** out_tangent_buffers, + cgltf_size* out_num_tangent_buffers); + +#endif // CGLTF_TANGENTS_H_INCLUDED__ diff --git a/contrib/cgltf-tangents/test/CMakeLists.txt b/contrib/cgltf-tangents/test/CMakeLists.txt new file mode 100644 index 0000000..422c950 --- /dev/null +++ b/contrib/cgltf-tangents/test/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 3.0) + +project (cgltf-test) + +add_executable(cgltf-test + main.c) + +target_link_libraries(cgltf-test + cgltf + cgltf-tangents + -lm) diff --git a/contrib/cgltf-tangents/test/main.c b/contrib/cgltf-tangents/test/main.c new file mode 100644 index 0000000..0d70008 --- /dev/null +++ b/contrib/cgltf-tangents/test/main.c @@ -0,0 +1,86 @@ +/* +Copyright 2022 Marc Sunet + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation and/or +other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#include +#define CGLTF_IMPLEMENTATION +#include + +#include + +void print_tangent_buffer(const cgltfTangentBuffer* buffer, int max_vectors) { + printf("Tangent buffer for primitive (%p) (%lu bytes):\n", buffer->primitive, + buffer->size_bytes); + + const float* xyzw = (const float*)buffer->data; + const float* end = (const float*)(buffer->data + buffer->size_bytes); + + for (int i = 0; i < max_vectors && xyzw < end; ++i, xyzw += 4) { + printf("(%3.2f, %3.2f, %3.2f, sign: %3.2f)\n", *xyzw, *(xyzw + 1), + *(xyzw + 2), *(xyzw + 3)); + } + printf("--------------------"); +} + +void usage(const char* argv0) { + fprintf(stderr, "Usage: %s \n", argv0); +} + +int main(int argc, const char** argv) { + cgltf_options options = {0}; + cgltf_data* data = NULL; + + if (argc != 2) { + usage(argv[0]); + return 0; + } + + const char* filepath = argv[1]; + + cgltf_result result = cgltf_parse_file(&options, filepath, &data); + if (result != cgltf_result_success) { + cgltf_free(data); + return 1; + } + + // Must call cgltf_load_buffers() to load buffer data. + result = cgltf_load_buffers(&options, data, filepath); + if (result != cgltf_result_success) { + cgltf_free(data); + return 2; + } + + cgltfTangentBuffer* tangent_buffers = 0; + cgltf_size num_tangent_buffers = 0; + cgltf_compute_tangents(&options, data, &tangent_buffers, + &num_tangent_buffers); + + // cgltf scene not needed beyond this point. + cgltf_free(data); + + for (cgltf_size i = 0; i < num_tangent_buffers; ++i) { + print_tangent_buffer(tangent_buffers, 10); + } + + return 0; +} diff --git a/contrib/cgltf/CMakeLists.txt b/contrib/cgltf/CMakeLists.txt new file mode 100644 index 0000000..0ac840a --- /dev/null +++ b/contrib/cgltf/CMakeLists.txt @@ -0,0 +1,8 @@ +cmake_minimum_required(VERSION 3.16) + +project(cgltf) + +add_library(cgltf INTERFACE) + +target_include_directories(cgltf INTERFACE + ${CMAKE_CURRENT_SOURCE_DIR}) diff --git a/contrib/cgltf/LICENSE b/contrib/cgltf/LICENSE new file mode 100644 index 0000000..0afe8c7 --- /dev/null +++ b/contrib/cgltf/LICENSE @@ -0,0 +1,7 @@ +Copyright (c) 2018 Johannes Kuhlmann + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/contrib/cgltf/README.md b/contrib/cgltf/README.md new file mode 100644 index 0000000..3b49d52 --- /dev/null +++ b/contrib/cgltf/README.md @@ -0,0 +1,154 @@ +# :diamond_shape_with_a_dot_inside: cgltf +**Single-file/stb-style C glTF loader and writer** + +[![Build Status](https://travis-ci.org/jkuhlmann/cgltf.svg?branch=master)](https://travis-ci.org/jkuhlmann/cgltf) + +Used in: [bgfx](https://github.com/bkaradzic/bgfx), [Filament](https://github.com/google/filament), [meshoptimizer](https://github.com/zeux/meshoptimizer), [raylib](https://github.com/raysan5/raylib), and more! + +## Usage: Loading +Loading from file: +```c +#define CGLTF_IMPLEMENTATION +#include "cgltf.h" + +cgltf_options options = {0}; +cgltf_data* data = NULL; +cgltf_result result = cgltf_parse_file(&options, "scene.gltf", &data); +if (result == cgltf_result_success) +{ + /* TODO make awesome stuff */ + cgltf_free(data); +} +``` + +Loading from memory: +```c +#define CGLTF_IMPLEMENTATION +#include "cgltf.h" + +void* buf; /* Pointer to glb or gltf file data */ +size_t size; /* Size of the file data */ + +cgltf_options options = {0}; +cgltf_data* data = NULL; +cgltf_result result = cgltf_parse(&options, buf, size, &data); +if (result == cgltf_result_success) +{ + /* TODO make awesome stuff */ + cgltf_free(data); +} +``` + +Note that cgltf does not load the contents of extra files such as buffers or images into memory by default. You'll need to read these files yourself using URIs from `data.buffers[]` or `data.images[]` respectively. +For buffer data, you can alternatively call `cgltf_load_buffers`, which will use `FILE*` APIs to open and read buffer files. + +**For more in-depth documentation and a description of the public interface refer to the top of the `cgltf.h` file.** + +## Usage: Writing +When writing glTF data, you need a valid `cgltf_data` structure that represents a valid glTF document. You can construct such a structure yourself or load it using the loader functions described above. The writer functions do not deallocate any memory. So, you either have to do it manually or call `cgltf_free()` if you got the data by loading it from a glTF document. + +Writing to file: +```c +#define CGLTF_IMPLEMENTATION +#define CGLTF_WRITE_IMPLEMENTATION +#include "cgltf_write.h" + +cgltf_options options = {0}; +cgltf_data* data = /* TODO must be valid data */; +cgltf_result result = cgltf_write_file(&options, "out.gltf", data); +if (result != cgltf_result_success) +{ + /* TODO handle error */ +} +``` + +Writing to memory: +```c +#define CGLTF_IMPLEMENTATION +#define CGLTF_WRITE_IMPLEMENTATION +#include "cgltf_write.h" +cgltf_options options = {0}; +cgltf_data* data = /* TODO must be valid data */; + +cgltf_size size = cgltf_write(&options, NULL, 0, data); + +char* buf = malloc(size); + +cgltf_size written = cgltf_write(&options, buf, size, data); +if (written != size) +{ + /* TODO handle error */ +} +``` + +Note that cgltf does not write the contents of extra files such as buffers or images. You'll need to write this data yourself. + +Writing does not yet support "extras" data. + +**For more in-depth documentation and a description of the public interface refer to the top of the `cgltf_write.h` file.** + + +## Features +cgltf supports core glTF 2.0: +- glb (binary files) and gltf (JSON files) +- meshes (including accessors, buffer views, buffers) +- materials (including textures, samplers, images) +- scenes and nodes +- skins +- animations +- cameras +- morph targets +- extras data + +cgltf also supports some glTF extensions: +- KHR_draco_mesh_compression (requires a library like [Google's Draco](https://github.com/google/draco) for decompression though) +- KHR_lights_punctual +- KHR_materials_clearcoat +- KHR_materials_ior +- KHR_materials_pbrSpecularGlossiness +- KHR_materials_specular +- KHR_materials_transmission +- KHR_materials_unlit +- KHR_texture_transform + +cgltf does **not** yet support unlisted extensions. However, unlisted extensions can be accessed via "extensions" member on objects. + +## Building +The easiest approach is to integrate the `cgltf.h` header file into your project. If you are unfamiliar with single-file C libraries (also known as stb-style libraries), this is how it goes: + +1. Include `cgltf.h` where you need the functionality. +1. Have exactly one source file that defines `CGLTF_IMPLEMENTATION` before including `cgltf.h`. +1. Use the cgltf functions as described above. + +Support for writing can be found in a separate file called `cgltf_write.h` (which includes `cgltf.h`). Building it works analogously using the `CGLTF_WRITE_IMPLEMENTATION` define. + +## Contributing +Everyone is welcome to contribute to the library. If you find any problems, you can submit them using [GitHub's issue system](https://github.com/jkuhlmann/cgltf/issues). If you want to contribute code, you should fork the project and then send a pull request. + + +## Dependencies +None. + +C headers being used by implementation: +``` +#include +#include +#include +#include +#include +#include +``` + +Note, this library has a copy of the [JSMN JSON parser](https://github.com/zserge/jsmn) embedded in its source. + +## Testing +There is a Python script in the `test/` folder that retrieves the glTF 2.0 sample files from the glTF-Sample-Models repository (https://github.com/KhronosGroup/glTF-Sample-Models/tree/master/2.0) and runs the library against all gltf and glb files. + +Here's one way to build and run the test: + + cd test ; mkdir build ; cd build ; cmake .. -DCMAKE_BUILD_TYPE=Debug + make -j + cd .. + ./test_all.py + +There is also a llvm-fuzz test in `fuzz/`. See http://llvm.org/docs/LibFuzzer.html for more information. diff --git a/contrib/cgltf/cgltf.h b/contrib/cgltf/cgltf.h new file mode 100644 index 0000000..077cf36 --- /dev/null +++ b/contrib/cgltf/cgltf.h @@ -0,0 +1,5746 @@ +/** + * cgltf - a single-file glTF 2.0 parser written in C99. + * + * Version: 1.7 + * + * Website: https://github.com/jkuhlmann/cgltf + * + * Distributed under the MIT License, see notice at the end of this file. + * + * Building: + * Include this file where you need the struct and function + * declarations. Have exactly one source file where you define + * `CGLTF_IMPLEMENTATION` before including this file to get the + * function definitions. + * + * Reference: + * `cgltf_result cgltf_parse(const cgltf_options*, const void*, + * cgltf_size, cgltf_data**)` parses both glTF and GLB data. If + * this function returns `cgltf_result_success`, you have to call + * `cgltf_free()` on the created `cgltf_data*` variable. + * Note that contents of external files for buffers and images are not + * automatically loaded. You'll need to read these files yourself using + * URIs in the `cgltf_data` structure. + * + * `cgltf_options` is the struct passed to `cgltf_parse()` to control + * parts of the parsing process. You can use it to force the file type + * and provide memory allocation as well as file operation callbacks. + * Should be zero-initialized to trigger default behavior. + * + * `cgltf_data` is the struct allocated and filled by `cgltf_parse()`. + * It generally mirrors the glTF format as described by the spec (see + * https://github.com/KhronosGroup/glTF/tree/master/specification/2.0). + * + * `void cgltf_free(cgltf_data*)` frees the allocated `cgltf_data` + * variable. + * + * `cgltf_result cgltf_load_buffers(const cgltf_options*, cgltf_data*, + * const char* gltf_path)` can be optionally called to open and read buffer + * files using the `FILE*` APIs. The `gltf_path` argument is the path to + * the original glTF file, which allows the parser to resolve the path to + * buffer files. + * + * `cgltf_result cgltf_load_buffer_base64(const cgltf_options* options, + * cgltf_size size, const char* base64, void** out_data)` decodes + * base64-encoded data content. Used internally by `cgltf_load_buffers()` + * and may be useful if you're not dealing with normal files. + * + * `cgltf_result cgltf_parse_file(const cgltf_options* options, const + * char* path, cgltf_data** out_data)` can be used to open the given + * file using `FILE*` APIs and parse the data using `cgltf_parse()`. + * + * `cgltf_result cgltf_validate(cgltf_data*)` can be used to do additional + * checks to make sure the parsed glTF data is valid. + * + * `cgltf_node_transform_local` converts the translation / rotation / scale properties of a node + * into a mat4. + * + * `cgltf_node_transform_world` calls `cgltf_node_transform_local` on every ancestor in order + * to compute the root-to-node transformation. + * + * `cgltf_accessor_unpack_floats` reads in the data from an accessor, applies sparse data (if any), + * and converts them to floating point. Assumes that `cgltf_load_buffers` has already been called. + * By passing null for the output pointer, users can find out how many floats are required in the + * output buffer. + * + * `cgltf_accessor_num_components` is a tiny utility that tells you the dimensionality of + * a certain accessor type. This can be used before `cgltf_accessor_unpack_floats` to help allocate + * the necessary amount of memory. + * + * `cgltf_accessor_read_float` reads a certain element from a non-sparse accessor and converts it to + * floating point, assuming that `cgltf_load_buffers` has already been called. The passed-in element + * size is the number of floats in the output buffer, which should be in the range [1, 16]. Returns + * false if the passed-in element_size is too small, or if the accessor is sparse. + * + * `cgltf_accessor_read_uint` is similar to its floating-point counterpart, but limited to reading + * vector types and does not support matrix types. The passed-in element size is the number of uints + * in the output buffer, which should be in the range [1, 4]. Returns false if the passed-in + * element_size is too small, or if the accessor is sparse. + * + * `cgltf_accessor_read_index` is similar to its floating-point counterpart, but it returns size_t + * and only works with single-component data types. + * + * `cgltf_result cgltf_copy_extras_json(const cgltf_data*, const cgltf_extras*, + * char* dest, cgltf_size* dest_size)` allows users to retrieve the "extras" data that + * can be attached to many glTF objects (which can be arbitrary JSON data). The + * `cgltf_extras` struct stores the offsets of the start and end of the extras JSON data + * as it appears in the complete glTF JSON data. This function copies the extras data + * into the provided buffer. If `dest` is NULL, the length of the data is written into + * `dest_size`. You can then parse this data using your own JSON parser + * or, if you've included the cgltf implementation using the integrated JSMN JSON parser. + */ +#ifndef CGLTF_H_INCLUDED__ +#define CGLTF_H_INCLUDED__ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef size_t cgltf_size; +typedef float cgltf_float; +typedef int cgltf_int; +typedef unsigned int cgltf_uint; +typedef int cgltf_bool; + +typedef enum cgltf_file_type +{ + cgltf_file_type_invalid, + cgltf_file_type_gltf, + cgltf_file_type_glb, +} cgltf_file_type; + +typedef enum cgltf_result +{ + cgltf_result_success, + cgltf_result_data_too_short, + cgltf_result_unknown_format, + cgltf_result_invalid_json, + cgltf_result_invalid_gltf, + cgltf_result_invalid_options, + cgltf_result_file_not_found, + cgltf_result_io_error, + cgltf_result_out_of_memory, + cgltf_result_legacy_gltf, +} cgltf_result; + +typedef struct cgltf_memory_options +{ + void* (*alloc)(void* user, cgltf_size size); + void (*free) (void* user, void* ptr); + void* user_data; +} cgltf_memory_options; + +typedef struct cgltf_file_options +{ + cgltf_result(*read)(const struct cgltf_memory_options* memory_options, const struct cgltf_file_options* file_options, const char* path, cgltf_size* size, void** data); + void (*release)(const struct cgltf_memory_options* memory_options, const struct cgltf_file_options* file_options, void* data); + void* user_data; +} cgltf_file_options; + +typedef struct cgltf_options +{ + cgltf_file_type type; /* invalid == auto detect */ + cgltf_size json_token_count; /* 0 == auto */ + cgltf_memory_options memory; + cgltf_file_options file; +} cgltf_options; + +typedef enum cgltf_buffer_view_type +{ + cgltf_buffer_view_type_invalid, + cgltf_buffer_view_type_indices, + cgltf_buffer_view_type_vertices, +} cgltf_buffer_view_type; + +typedef enum cgltf_attribute_type +{ + cgltf_attribute_type_invalid, + cgltf_attribute_type_position, + cgltf_attribute_type_normal, + cgltf_attribute_type_tangent, + cgltf_attribute_type_texcoord, + cgltf_attribute_type_color, + cgltf_attribute_type_joints, + cgltf_attribute_type_weights, +} cgltf_attribute_type; + +typedef enum cgltf_component_type +{ + cgltf_component_type_invalid, + cgltf_component_type_r_8, /* BYTE */ + cgltf_component_type_r_8u, /* UNSIGNED_BYTE */ + cgltf_component_type_r_16, /* SHORT */ + cgltf_component_type_r_16u, /* UNSIGNED_SHORT */ + cgltf_component_type_r_32u, /* UNSIGNED_INT */ + cgltf_component_type_r_32f, /* FLOAT */ +} cgltf_component_type; + +typedef enum cgltf_type +{ + cgltf_type_invalid, + cgltf_type_scalar, + cgltf_type_vec2, + cgltf_type_vec3, + cgltf_type_vec4, + cgltf_type_mat2, + cgltf_type_mat3, + cgltf_type_mat4, +} cgltf_type; + +typedef enum cgltf_primitive_type +{ + cgltf_primitive_type_points, + cgltf_primitive_type_lines, + cgltf_primitive_type_line_loop, + cgltf_primitive_type_line_strip, + cgltf_primitive_type_triangles, + cgltf_primitive_type_triangle_strip, + cgltf_primitive_type_triangle_fan, +} cgltf_primitive_type; + +typedef enum cgltf_alpha_mode +{ + cgltf_alpha_mode_opaque, + cgltf_alpha_mode_mask, + cgltf_alpha_mode_blend, +} cgltf_alpha_mode; + +typedef enum cgltf_animation_path_type { + cgltf_animation_path_type_invalid, + cgltf_animation_path_type_translation, + cgltf_animation_path_type_rotation, + cgltf_animation_path_type_scale, + cgltf_animation_path_type_weights, +} cgltf_animation_path_type; + +typedef enum cgltf_interpolation_type { + cgltf_interpolation_type_linear, + cgltf_interpolation_type_step, + cgltf_interpolation_type_cubic_spline, +} cgltf_interpolation_type; + +typedef enum cgltf_camera_type { + cgltf_camera_type_invalid, + cgltf_camera_type_perspective, + cgltf_camera_type_orthographic, +} cgltf_camera_type; + +typedef enum cgltf_light_type { + cgltf_light_type_invalid, + cgltf_light_type_directional, + cgltf_light_type_point, + cgltf_light_type_spot, +} cgltf_light_type; + +typedef struct cgltf_extras { + cgltf_size start_offset; + cgltf_size end_offset; +} cgltf_extras; + +typedef struct cgltf_extension { + char* name; + char* data; +} cgltf_extension; + +typedef struct cgltf_buffer +{ + cgltf_size size; + char* uri; + void* data; /* loaded by cgltf_load_buffers */ + cgltf_extras extras; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_buffer; + +typedef struct cgltf_buffer_view +{ + cgltf_buffer* buffer; + cgltf_size offset; + cgltf_size size; + cgltf_size stride; /* 0 == automatically determined by accessor */ + cgltf_buffer_view_type type; + cgltf_extras extras; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_buffer_view; + +typedef struct cgltf_accessor_sparse +{ + cgltf_size count; + cgltf_buffer_view* indices_buffer_view; + cgltf_size indices_byte_offset; + cgltf_component_type indices_component_type; + cgltf_buffer_view* values_buffer_view; + cgltf_size values_byte_offset; + cgltf_extras extras; + cgltf_extras indices_extras; + cgltf_extras values_extras; + cgltf_size extensions_count; + cgltf_extension* extensions; + cgltf_size indices_extensions_count; + cgltf_extension* indices_extensions; + cgltf_size values_extensions_count; + cgltf_extension* values_extensions; +} cgltf_accessor_sparse; + +typedef struct cgltf_accessor +{ + cgltf_component_type component_type; + cgltf_bool normalized; + cgltf_type type; + cgltf_size offset; + cgltf_size count; + cgltf_size stride; + cgltf_buffer_view* buffer_view; + cgltf_bool has_min; + cgltf_float min[16]; + cgltf_bool has_max; + cgltf_float max[16]; + cgltf_bool is_sparse; + cgltf_accessor_sparse sparse; + cgltf_extras extras; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_accessor; + +typedef struct cgltf_attribute +{ + char* name; + cgltf_attribute_type type; + cgltf_int index; + cgltf_accessor* data; +} cgltf_attribute; + +typedef struct cgltf_image +{ + char* name; + char* uri; + cgltf_buffer_view* buffer_view; + char* mime_type; + cgltf_extras extras; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_image; + +typedef struct cgltf_sampler +{ + cgltf_int mag_filter; + cgltf_int min_filter; + cgltf_int wrap_s; + cgltf_int wrap_t; + cgltf_extras extras; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_sampler; + +typedef struct cgltf_texture +{ + char* name; + cgltf_image* image; + cgltf_sampler* sampler; + cgltf_extras extras; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_texture; + +typedef struct cgltf_texture_transform +{ + cgltf_float offset[2]; + cgltf_float rotation; + cgltf_float scale[2]; + cgltf_int texcoord; +} cgltf_texture_transform; + +typedef struct cgltf_texture_view +{ + cgltf_texture* texture; + cgltf_int texcoord; + cgltf_float scale; /* equivalent to strength for occlusion_texture */ + cgltf_bool has_transform; + cgltf_texture_transform transform; + cgltf_extras extras; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_texture_view; + +typedef struct cgltf_pbr_metallic_roughness +{ + cgltf_texture_view base_color_texture; + cgltf_texture_view metallic_roughness_texture; + + cgltf_float base_color_factor[4]; + cgltf_float metallic_factor; + cgltf_float roughness_factor; + + cgltf_extras extras; +} cgltf_pbr_metallic_roughness; + +typedef struct cgltf_pbr_specular_glossiness +{ + cgltf_texture_view diffuse_texture; + cgltf_texture_view specular_glossiness_texture; + + cgltf_float diffuse_factor[4]; + cgltf_float specular_factor[3]; + cgltf_float glossiness_factor; +} cgltf_pbr_specular_glossiness; + +typedef struct cgltf_clearcoat +{ + cgltf_texture_view clearcoat_texture; + cgltf_texture_view clearcoat_roughness_texture; + cgltf_texture_view clearcoat_normal_texture; + + cgltf_float clearcoat_factor; + cgltf_float clearcoat_roughness_factor; +} cgltf_clearcoat; + +typedef struct cgltf_transmission +{ + cgltf_texture_view transmission_texture; + cgltf_float transmission_factor; +} cgltf_transmission; + +typedef struct cgltf_ior +{ + cgltf_float ior; +} cgltf_ior; + +typedef struct cgltf_specular +{ + cgltf_texture_view specular_texture; + cgltf_float specular_color_factor[3]; + cgltf_float specular_factor; +} cgltf_specular; + +typedef struct cgltf_material +{ + char* name; + cgltf_bool has_pbr_metallic_roughness; + cgltf_bool has_pbr_specular_glossiness; + cgltf_bool has_clearcoat; + cgltf_bool has_transmission; + cgltf_bool has_ior; + cgltf_bool has_specular; + cgltf_pbr_metallic_roughness pbr_metallic_roughness; + cgltf_pbr_specular_glossiness pbr_specular_glossiness; + cgltf_clearcoat clearcoat; + cgltf_ior ior; + cgltf_specular specular; + cgltf_transmission transmission; + cgltf_texture_view normal_texture; + cgltf_texture_view occlusion_texture; + cgltf_texture_view emissive_texture; + cgltf_float emissive_factor[3]; + cgltf_alpha_mode alpha_mode; + cgltf_float alpha_cutoff; + cgltf_bool double_sided; + cgltf_bool unlit; + cgltf_extras extras; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_material; + +typedef struct cgltf_morph_target { + cgltf_attribute* attributes; + cgltf_size attributes_count; +} cgltf_morph_target; + +typedef struct cgltf_draco_mesh_compression { + cgltf_buffer_view* buffer_view; + cgltf_attribute* attributes; + cgltf_size attributes_count; +} cgltf_draco_mesh_compression; + +typedef struct cgltf_primitive { + cgltf_primitive_type type; + cgltf_accessor* indices; + cgltf_material* material; + cgltf_attribute* attributes; + cgltf_size attributes_count; + cgltf_morph_target* targets; + cgltf_size targets_count; + cgltf_extras extras; + cgltf_bool has_draco_mesh_compression; + cgltf_draco_mesh_compression draco_mesh_compression; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_primitive; + +typedef struct cgltf_mesh { + char* name; + cgltf_primitive* primitives; + cgltf_size primitives_count; + cgltf_float* weights; + cgltf_size weights_count; + char** target_names; + cgltf_size target_names_count; + cgltf_extras extras; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_mesh; + +typedef struct cgltf_node cgltf_node; + +typedef struct cgltf_skin { + char* name; + cgltf_node** joints; + cgltf_size joints_count; + cgltf_node* skeleton; + cgltf_accessor* inverse_bind_matrices; + cgltf_extras extras; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_skin; + +typedef struct cgltf_camera_perspective { + cgltf_float aspect_ratio; + cgltf_float yfov; + cgltf_float zfar; + cgltf_float znear; + cgltf_extras extras; +} cgltf_camera_perspective; + +typedef struct cgltf_camera_orthographic { + cgltf_float xmag; + cgltf_float ymag; + cgltf_float zfar; + cgltf_float znear; + cgltf_extras extras; +} cgltf_camera_orthographic; + +typedef struct cgltf_camera { + char* name; + cgltf_camera_type type; + union { + cgltf_camera_perspective perspective; + cgltf_camera_orthographic orthographic; + } data; + cgltf_extras extras; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_camera; + +typedef struct cgltf_light { + char* name; + cgltf_float color[3]; + cgltf_float intensity; + cgltf_light_type type; + cgltf_float range; + cgltf_float spot_inner_cone_angle; + cgltf_float spot_outer_cone_angle; +} cgltf_light; + +struct cgltf_node { + char* name; + cgltf_node* parent; + cgltf_node** children; + cgltf_size children_count; + cgltf_skin* skin; + cgltf_mesh* mesh; + cgltf_camera* camera; + cgltf_light* light; + cgltf_float* weights; + cgltf_size weights_count; + cgltf_bool has_translation; + cgltf_bool has_rotation; + cgltf_bool has_scale; + cgltf_bool has_matrix; + cgltf_float translation[3]; + cgltf_float rotation[4]; + cgltf_float scale[3]; + cgltf_float matrix[16]; + cgltf_extras extras; + cgltf_size extensions_count; + cgltf_extension* extensions; +}; + +typedef struct cgltf_scene { + char* name; + cgltf_node** nodes; + cgltf_size nodes_count; + cgltf_extras extras; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_scene; + +typedef struct cgltf_animation_sampler { + cgltf_accessor* input; + cgltf_accessor* output; + cgltf_interpolation_type interpolation; + cgltf_extras extras; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_animation_sampler; + +typedef struct cgltf_animation_channel { + cgltf_animation_sampler* sampler; + cgltf_node* target_node; + cgltf_animation_path_type target_path; + cgltf_extras extras; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_animation_channel; + +typedef struct cgltf_animation { + char* name; + cgltf_animation_sampler* samplers; + cgltf_size samplers_count; + cgltf_animation_channel* channels; + cgltf_size channels_count; + cgltf_extras extras; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_animation; + +typedef struct cgltf_asset { + char* copyright; + char* generator; + char* version; + char* min_version; + cgltf_extras extras; + cgltf_size extensions_count; + cgltf_extension* extensions; +} cgltf_asset; + +typedef struct cgltf_data +{ + cgltf_file_type file_type; + void* file_data; + + cgltf_asset asset; + + cgltf_mesh* meshes; + cgltf_size meshes_count; + + cgltf_material* materials; + cgltf_size materials_count; + + cgltf_accessor* accessors; + cgltf_size accessors_count; + + cgltf_buffer_view* buffer_views; + cgltf_size buffer_views_count; + + cgltf_buffer* buffers; + cgltf_size buffers_count; + + cgltf_image* images; + cgltf_size images_count; + + cgltf_texture* textures; + cgltf_size textures_count; + + cgltf_sampler* samplers; + cgltf_size samplers_count; + + cgltf_skin* skins; + cgltf_size skins_count; + + cgltf_camera* cameras; + cgltf_size cameras_count; + + cgltf_light* lights; + cgltf_size lights_count; + + cgltf_node* nodes; + cgltf_size nodes_count; + + cgltf_scene* scenes; + cgltf_size scenes_count; + + cgltf_scene* scene; + + cgltf_animation* animations; + cgltf_size animations_count; + + cgltf_extras extras; + + cgltf_size data_extensions_count; + cgltf_extension* data_extensions; + + char** extensions_used; + cgltf_size extensions_used_count; + + char** extensions_required; + cgltf_size extensions_required_count; + + const char* json; + cgltf_size json_size; + + const void* bin; + cgltf_size bin_size; + + cgltf_memory_options memory; + cgltf_file_options file; +} cgltf_data; + +cgltf_result cgltf_parse( + const cgltf_options* options, + const void* data, + cgltf_size size, + cgltf_data** out_data); + +cgltf_result cgltf_parse_file( + const cgltf_options* options, + const char* path, + cgltf_data** out_data); + +cgltf_result cgltf_load_buffers( + const cgltf_options* options, + cgltf_data* data, + const char* gltf_path); + +cgltf_result cgltf_load_buffer_base64(const cgltf_options* options, cgltf_size size, const char* base64, void** out_data); + +void cgltf_decode_uri(char* uri); + +cgltf_result cgltf_validate(cgltf_data* data); + +void cgltf_free(cgltf_data* data); + +void cgltf_node_transform_local(const cgltf_node* node, cgltf_float* out_matrix); +void cgltf_node_transform_world(const cgltf_node* node, cgltf_float* out_matrix); + +cgltf_bool cgltf_accessor_read_float(const cgltf_accessor* accessor, cgltf_size index, cgltf_float* out, cgltf_size element_size); +cgltf_bool cgltf_accessor_read_uint(const cgltf_accessor* accessor, cgltf_size index, cgltf_uint* out, cgltf_size element_size); +cgltf_size cgltf_accessor_read_index(const cgltf_accessor* accessor, cgltf_size index); + +cgltf_size cgltf_num_components(cgltf_type type); + +cgltf_size cgltf_accessor_unpack_floats(const cgltf_accessor* accessor, cgltf_float* out, cgltf_size float_count); + +cgltf_result cgltf_copy_extras_json(const cgltf_data* data, const cgltf_extras* extras, char* dest, cgltf_size* dest_size); + +#ifdef __cplusplus +} +#endif + +#endif /* #ifndef CGLTF_H_INCLUDED__ */ + +/* + * + * Stop now, if you are only interested in the API. + * Below, you find the implementation. + * + */ + +#if defined(__INTELLISENSE__) || defined(__JETBRAINS_IDE__) +/* This makes MSVC/CLion intellisense work. */ +#define CGLTF_IMPLEMENTATION +#endif + +#ifdef CGLTF_IMPLEMENTATION + +#include /* For uint8_t, uint32_t */ +#include /* For strncpy */ +#include /* For fopen */ +#include /* For UINT_MAX etc */ + +#if !defined(CGLTF_MALLOC) || !defined(CGLTF_FREE) || !defined(CGLTF_ATOI) || !defined(CGLTF_ATOF) +#include /* For malloc, free, atoi, atof */ +#endif + +/* JSMN_PARENT_LINKS is necessary to make parsing large structures linear in input size */ +#define JSMN_PARENT_LINKS + +/* JSMN_STRICT is necessary to reject invalid JSON documents */ +#define JSMN_STRICT + +/* + * -- jsmn.h start -- + * Source: https://github.com/zserge/jsmn + * License: MIT + */ +typedef enum { + JSMN_UNDEFINED = 0, + JSMN_OBJECT = 1, + JSMN_ARRAY = 2, + JSMN_STRING = 3, + JSMN_PRIMITIVE = 4 +} jsmntype_t; +enum jsmnerr { + /* Not enough tokens were provided */ + JSMN_ERROR_NOMEM = -1, + /* Invalid character inside JSON string */ + JSMN_ERROR_INVAL = -2, + /* The string is not a full JSON packet, more bytes expected */ + JSMN_ERROR_PART = -3 +}; +typedef struct { + jsmntype_t type; + int start; + int end; + int size; +#ifdef JSMN_PARENT_LINKS + int parent; +#endif +} jsmntok_t; +typedef struct { + unsigned int pos; /* offset in the JSON string */ + unsigned int toknext; /* next token to allocate */ + int toksuper; /* superior token node, e.g parent object or array */ +} jsmn_parser; +static void jsmn_init(jsmn_parser *parser); +static int jsmn_parse(jsmn_parser *parser, const char *js, size_t len, jsmntok_t *tokens, size_t num_tokens); +/* + * -- jsmn.h end -- + */ + + +static const cgltf_size GlbHeaderSize = 12; +static const cgltf_size GlbChunkHeaderSize = 8; +static const uint32_t GlbVersion = 2; +static const uint32_t GlbMagic = 0x46546C67; +static const uint32_t GlbMagicJsonChunk = 0x4E4F534A; +static const uint32_t GlbMagicBinChunk = 0x004E4942; + +#ifndef CGLTF_MALLOC +#define CGLTF_MALLOC(size) malloc(size) +#endif +#ifndef CGLTF_FREE +#define CGLTF_FREE(ptr) free(ptr) +#endif +#ifndef CGLTF_ATOI +#define CGLTF_ATOI(str) atoi(str) +#endif +#ifndef CGLTF_ATOF +#define CGLTF_ATOF(str) atof(str) +#endif + +static void* cgltf_default_alloc(void* user, cgltf_size size) +{ + (void)user; + return CGLTF_MALLOC(size); +} + +static void cgltf_default_free(void* user, void* ptr) +{ + (void)user; + CGLTF_FREE(ptr); +} + +static void* cgltf_calloc(cgltf_options* options, size_t element_size, cgltf_size count) +{ + if (SIZE_MAX / element_size < count) + { + return NULL; + } + void* result = options->memory.alloc(options->memory.user_data, element_size * count); + if (!result) + { + return NULL; + } + memset(result, 0, element_size * count); + return result; +} + +static cgltf_result cgltf_default_file_read(const struct cgltf_memory_options* memory_options, const struct cgltf_file_options* file_options, const char* path, cgltf_size* size, void** data) +{ + (void)file_options; + void* (*memory_alloc)(void*, cgltf_size) = memory_options->alloc ? memory_options->alloc : &cgltf_default_alloc; + void (*memory_free)(void*, void*) = memory_options->free ? memory_options->free : &cgltf_default_free; + + FILE* file = fopen(path, "rb"); + if (!file) + { + return cgltf_result_file_not_found; + } + + cgltf_size file_size = size ? *size : 0; + + if (file_size == 0) + { + fseek(file, 0, SEEK_END); + + long length = ftell(file); + if (length < 0) + { + fclose(file); + return cgltf_result_io_error; + } + + fseek(file, 0, SEEK_SET); + file_size = (cgltf_size)length; + } + + char* file_data = (char*)memory_alloc(memory_options->user_data, file_size); + if (!file_data) + { + fclose(file); + return cgltf_result_out_of_memory; + } + + cgltf_size read_size = fread(file_data, 1, file_size, file); + + fclose(file); + + if (read_size != file_size) + { + memory_free(memory_options->user_data, file_data); + return cgltf_result_io_error; + } + + if (size) + { + *size = file_size; + } + if (data) + { + *data = file_data; + } + + return cgltf_result_success; +} + +static void cgltf_default_file_release(const struct cgltf_memory_options* memory_options, const struct cgltf_file_options* file_options, void* data) +{ + (void)file_options; + void (*memfree)(void*, void*) = memory_options->free ? memory_options->free : &cgltf_default_free; + memfree(memory_options->user_data, data); +} + +static cgltf_result cgltf_parse_json(cgltf_options* options, const uint8_t* json_chunk, cgltf_size size, cgltf_data** out_data); + +cgltf_result cgltf_parse(const cgltf_options* options, const void* data, cgltf_size size, cgltf_data** out_data) +{ + if (size < GlbHeaderSize) + { + return cgltf_result_data_too_short; + } + + if (options == NULL) + { + return cgltf_result_invalid_options; + } + + cgltf_options fixed_options = *options; + if (fixed_options.memory.alloc == NULL) + { + fixed_options.memory.alloc = &cgltf_default_alloc; + } + if (fixed_options.memory.free == NULL) + { + fixed_options.memory.free = &cgltf_default_free; + } + + uint32_t tmp; + // Magic + memcpy(&tmp, data, 4); + if (tmp != GlbMagic) + { + if (fixed_options.type == cgltf_file_type_invalid) + { + fixed_options.type = cgltf_file_type_gltf; + } + else if (fixed_options.type == cgltf_file_type_glb) + { + return cgltf_result_unknown_format; + } + } + + if (fixed_options.type == cgltf_file_type_gltf) + { + cgltf_result json_result = cgltf_parse_json(&fixed_options, (const uint8_t*)data, size, out_data); + if (json_result != cgltf_result_success) + { + return json_result; + } + + (*out_data)->file_type = cgltf_file_type_gltf; + + return cgltf_result_success; + } + + const uint8_t* ptr = (const uint8_t*)data; + // Version + memcpy(&tmp, ptr + 4, 4); + uint32_t version = tmp; + if (version != GlbVersion) + { + return version < GlbVersion ? cgltf_result_legacy_gltf : cgltf_result_unknown_format; + } + + // Total length + memcpy(&tmp, ptr + 8, 4); + if (tmp > size) + { + return cgltf_result_data_too_short; + } + + const uint8_t* json_chunk = ptr + GlbHeaderSize; + + if (GlbHeaderSize + GlbChunkHeaderSize > size) + { + return cgltf_result_data_too_short; + } + + // JSON chunk: length + uint32_t json_length; + memcpy(&json_length, json_chunk, 4); + if (GlbHeaderSize + GlbChunkHeaderSize + json_length > size) + { + return cgltf_result_data_too_short; + } + + // JSON chunk: magic + memcpy(&tmp, json_chunk + 4, 4); + if (tmp != GlbMagicJsonChunk) + { + return cgltf_result_unknown_format; + } + + json_chunk += GlbChunkHeaderSize; + + const void* bin = 0; + cgltf_size bin_size = 0; + + if (GlbHeaderSize + GlbChunkHeaderSize + json_length + GlbChunkHeaderSize <= size) + { + // We can read another chunk + const uint8_t* bin_chunk = json_chunk + json_length; + + // Bin chunk: length + uint32_t bin_length; + memcpy(&bin_length, bin_chunk, 4); + if (GlbHeaderSize + GlbChunkHeaderSize + json_length + GlbChunkHeaderSize + bin_length > size) + { + return cgltf_result_data_too_short; + } + + // Bin chunk: magic + memcpy(&tmp, bin_chunk + 4, 4); + if (tmp != GlbMagicBinChunk) + { + return cgltf_result_unknown_format; + } + + bin_chunk += GlbChunkHeaderSize; + + bin = bin_chunk; + bin_size = bin_length; + } + + cgltf_result json_result = cgltf_parse_json(&fixed_options, json_chunk, json_length, out_data); + if (json_result != cgltf_result_success) + { + return json_result; + } + + (*out_data)->file_type = cgltf_file_type_glb; + (*out_data)->bin = bin; + (*out_data)->bin_size = bin_size; + + return cgltf_result_success; +} + +cgltf_result cgltf_parse_file(const cgltf_options* options, const char* path, cgltf_data** out_data) +{ + if (options == NULL) + { + return cgltf_result_invalid_options; + } + + void (*memory_free)(void*, void*) = options->memory.free ? options->memory.free : &cgltf_default_free; + cgltf_result (*file_read)(const struct cgltf_memory_options*, const struct cgltf_file_options*, const char*, cgltf_size*, void**) = options->file.read ? options->file.read : &cgltf_default_file_read; + + void* file_data = NULL; + cgltf_size file_size = 0; + cgltf_result result = file_read(&options->memory, &options->file, path, &file_size, &file_data); + if (result != cgltf_result_success) + { + return result; + } + + result = cgltf_parse(options, file_data, file_size, out_data); + + if (result != cgltf_result_success) + { + memory_free(options->memory.user_data, file_data); + return result; + } + + (*out_data)->file_data = file_data; + + return cgltf_result_success; +} + +static void cgltf_combine_paths(char* path, const char* base, const char* uri) +{ + const char* s0 = strrchr(base, '/'); + const char* s1 = strrchr(base, '\\'); + const char* slash = s0 ? (s1 && s1 > s0 ? s1 : s0) : s1; + + if (slash) + { + size_t prefix = slash - base + 1; + + strncpy(path, base, prefix); + strcpy(path + prefix, uri); + } + else + { + strcpy(path, uri); + } +} + +static cgltf_result cgltf_load_buffer_file(const cgltf_options* options, cgltf_size size, const char* uri, const char* gltf_path, void** out_data) +{ + void* (*memory_alloc)(void*, cgltf_size) = options->memory.alloc ? options->memory.alloc : &cgltf_default_alloc; + void (*memory_free)(void*, void*) = options->memory.free ? options->memory.free : &cgltf_default_free; + cgltf_result (*file_read)(const struct cgltf_memory_options*, const struct cgltf_file_options*, const char*, cgltf_size*, void**) = options->file.read ? options->file.read : &cgltf_default_file_read; + + char* path = (char*)memory_alloc(options->memory.user_data, strlen(uri) + strlen(gltf_path) + 1); + if (!path) + { + return cgltf_result_out_of_memory; + } + + cgltf_combine_paths(path, gltf_path, uri); + + // after combining, the tail of the resulting path is a uri; decode_uri converts it into path + cgltf_decode_uri(path + strlen(path) - strlen(uri)); + + void* file_data = NULL; + cgltf_result result = file_read(&options->memory, &options->file, path, &size, &file_data); + + memory_free(options->memory.user_data, path); + + *out_data = (result == cgltf_result_success) ? file_data : NULL; + + return result; +} + +cgltf_result cgltf_load_buffer_base64(const cgltf_options* options, cgltf_size size, const char* base64, void** out_data) +{ + void* (*memory_alloc)(void*, cgltf_size) = options->memory.alloc ? options->memory.alloc : &cgltf_default_alloc; + void (*memory_free)(void*, void*) = options->memory.free ? options->memory.free : &cgltf_default_free; + + unsigned char* data = (unsigned char*)memory_alloc(options->memory.user_data, size); + if (!data) + { + return cgltf_result_out_of_memory; + } + + unsigned int buffer = 0; + unsigned int buffer_bits = 0; + + for (cgltf_size i = 0; i < size; ++i) + { + while (buffer_bits < 8) + { + char ch = *base64++; + + int index = + (unsigned)(ch - 'A') < 26 ? (ch - 'A') : + (unsigned)(ch - 'a') < 26 ? (ch - 'a') + 26 : + (unsigned)(ch - '0') < 10 ? (ch - '0') + 52 : + ch == '+' ? 62 : + ch == '/' ? 63 : + -1; + + if (index < 0) + { + memory_free(options->memory.user_data, data); + return cgltf_result_io_error; + } + + buffer = (buffer << 6) | index; + buffer_bits += 6; + } + + data[i] = (unsigned char)(buffer >> (buffer_bits - 8)); + buffer_bits -= 8; + } + + *out_data = data; + + return cgltf_result_success; +} + +static int cgltf_unhex(char ch) +{ + return + (unsigned)(ch - '0') < 10 ? (ch - '0') : + (unsigned)(ch - 'A') < 6 ? (ch - 'A') + 10 : + (unsigned)(ch - 'a') < 6 ? (ch - 'a') + 10 : + -1; +} + +void cgltf_decode_uri(char* uri) +{ + char* write = uri; + char* i = uri; + + while (*i) + { + if (*i == '%') + { + int ch1 = cgltf_unhex(i[1]); + + if (ch1 >= 0) + { + int ch2 = cgltf_unhex(i[2]); + + if (ch2 >= 0) + { + *write++ = (char)(ch1 * 16 + ch2); + i += 3; + continue; + } + } + } + + *write++ = *i++; + } + + *write = 0; +} + +cgltf_result cgltf_load_buffers(const cgltf_options* options, cgltf_data* data, const char* gltf_path) +{ + if (options == NULL) + { + return cgltf_result_invalid_options; + } + + if (data->buffers_count && data->buffers[0].data == NULL && data->buffers[0].uri == NULL && data->bin) + { + if (data->bin_size < data->buffers[0].size) + { + return cgltf_result_data_too_short; + } + + data->buffers[0].data = (void*)data->bin; + } + + for (cgltf_size i = 0; i < data->buffers_count; ++i) + { + if (data->buffers[i].data) + { + continue; + } + + const char* uri = data->buffers[i].uri; + + if (uri == NULL) + { + continue; + } + + if (strncmp(uri, "data:", 5) == 0) + { + const char* comma = strchr(uri, ','); + + if (comma && comma - uri >= 7 && strncmp(comma - 7, ";base64", 7) == 0) + { + cgltf_result res = cgltf_load_buffer_base64(options, data->buffers[i].size, comma + 1, &data->buffers[i].data); + + if (res != cgltf_result_success) + { + return res; + } + } + else + { + return cgltf_result_unknown_format; + } + } + else if (strstr(uri, "://") == NULL && gltf_path) + { + cgltf_result res = cgltf_load_buffer_file(options, data->buffers[i].size, uri, gltf_path, &data->buffers[i].data); + + if (res != cgltf_result_success) + { + return res; + } + } + else + { + return cgltf_result_unknown_format; + } + } + + return cgltf_result_success; +} + +static cgltf_size cgltf_calc_size(cgltf_type type, cgltf_component_type component_type); + +static cgltf_size cgltf_calc_index_bound(cgltf_buffer_view* buffer_view, cgltf_size offset, cgltf_component_type component_type, cgltf_size count) +{ + char* data = (char*)buffer_view->buffer->data + offset + buffer_view->offset; + cgltf_size bound = 0; + + switch (component_type) + { + case cgltf_component_type_r_8u: + for (size_t i = 0; i < count; ++i) + { + cgltf_size v = ((unsigned char*)data)[i]; + bound = bound > v ? bound : v; + } + break; + + case cgltf_component_type_r_16u: + for (size_t i = 0; i < count; ++i) + { + cgltf_size v = ((unsigned short*)data)[i]; + bound = bound > v ? bound : v; + } + break; + + case cgltf_component_type_r_32u: + for (size_t i = 0; i < count; ++i) + { + cgltf_size v = ((unsigned int*)data)[i]; + bound = bound > v ? bound : v; + } + break; + + default: + ; + } + + return bound; +} + +cgltf_result cgltf_validate(cgltf_data* data) +{ + for (cgltf_size i = 0; i < data->accessors_count; ++i) + { + cgltf_accessor* accessor = &data->accessors[i]; + + cgltf_size element_size = cgltf_calc_size(accessor->type, accessor->component_type); + + if (accessor->buffer_view) + { + cgltf_size req_size = accessor->offset + accessor->stride * (accessor->count - 1) + element_size; + + if (accessor->buffer_view->size < req_size) + { + return cgltf_result_data_too_short; + } + } + + if (accessor->is_sparse) + { + cgltf_accessor_sparse* sparse = &accessor->sparse; + + cgltf_size indices_component_size = cgltf_calc_size(cgltf_type_scalar, sparse->indices_component_type); + cgltf_size indices_req_size = sparse->indices_byte_offset + indices_component_size * sparse->count; + cgltf_size values_req_size = sparse->values_byte_offset + element_size * sparse->count; + + if (sparse->indices_buffer_view->size < indices_req_size || + sparse->values_buffer_view->size < values_req_size) + { + return cgltf_result_data_too_short; + } + + if (sparse->indices_component_type != cgltf_component_type_r_8u && + sparse->indices_component_type != cgltf_component_type_r_16u && + sparse->indices_component_type != cgltf_component_type_r_32u) + { + return cgltf_result_invalid_gltf; + } + + if (sparse->indices_buffer_view->buffer->data) + { + cgltf_size index_bound = cgltf_calc_index_bound(sparse->indices_buffer_view, sparse->indices_byte_offset, sparse->indices_component_type, sparse->count); + + if (index_bound >= accessor->count) + { + return cgltf_result_data_too_short; + } + } + } + } + + for (cgltf_size i = 0; i < data->buffer_views_count; ++i) + { + cgltf_size req_size = data->buffer_views[i].offset + data->buffer_views[i].size; + + if (data->buffer_views[i].buffer && data->buffer_views[i].buffer->size < req_size) + { + return cgltf_result_data_too_short; + } + } + + for (cgltf_size i = 0; i < data->meshes_count; ++i) + { + if (data->meshes[i].weights) + { + if (data->meshes[i].primitives_count && data->meshes[i].primitives[0].targets_count != data->meshes[i].weights_count) + { + return cgltf_result_invalid_gltf; + } + } + + if (data->meshes[i].target_names) + { + if (data->meshes[i].primitives_count && data->meshes[i].primitives[0].targets_count != data->meshes[i].target_names_count) + { + return cgltf_result_invalid_gltf; + } + } + + for (cgltf_size j = 0; j < data->meshes[i].primitives_count; ++j) + { + if (data->meshes[i].primitives[j].targets_count != data->meshes[i].primitives[0].targets_count) + { + return cgltf_result_invalid_gltf; + } + + if (data->meshes[i].primitives[j].attributes_count) + { + cgltf_accessor* first = data->meshes[i].primitives[j].attributes[0].data; + + for (cgltf_size k = 0; k < data->meshes[i].primitives[j].attributes_count; ++k) + { + if (data->meshes[i].primitives[j].attributes[k].data->count != first->count) + { + return cgltf_result_invalid_gltf; + } + } + + for (cgltf_size k = 0; k < data->meshes[i].primitives[j].targets_count; ++k) + { + for (cgltf_size m = 0; m < data->meshes[i].primitives[j].targets[k].attributes_count; ++m) + { + if (data->meshes[i].primitives[j].targets[k].attributes[m].data->count != first->count) + { + return cgltf_result_invalid_gltf; + } + } + } + + cgltf_accessor* indices = data->meshes[i].primitives[j].indices; + + if (indices && + indices->component_type != cgltf_component_type_r_8u && + indices->component_type != cgltf_component_type_r_16u && + indices->component_type != cgltf_component_type_r_32u) + { + return cgltf_result_invalid_gltf; + } + + if (indices && indices->buffer_view && indices->buffer_view->buffer->data) + { + cgltf_size index_bound = cgltf_calc_index_bound(indices->buffer_view, indices->offset, indices->component_type, indices->count); + + if (index_bound >= first->count) + { + return cgltf_result_data_too_short; + } + } + } + } + } + + for (cgltf_size i = 0; i < data->nodes_count; ++i) + { + if (data->nodes[i].weights && data->nodes[i].mesh) + { + if (data->nodes[i].mesh->primitives_count && data->nodes[i].mesh->primitives[0].targets_count != data->nodes[i].weights_count) + { + return cgltf_result_invalid_gltf; + } + } + } + + for (cgltf_size i = 0; i < data->nodes_count; ++i) + { + cgltf_node* p1 = data->nodes[i].parent; + cgltf_node* p2 = p1 ? p1->parent : NULL; + + while (p1 && p2) + { + if (p1 == p2) + { + return cgltf_result_invalid_gltf; + } + + p1 = p1->parent; + p2 = p2->parent ? p2->parent->parent : NULL; + } + } + + for (cgltf_size i = 0; i < data->scenes_count; ++i) + { + for (cgltf_size j = 0; j < data->scenes[i].nodes_count; ++j) + { + if (data->scenes[i].nodes[j]->parent) + { + return cgltf_result_invalid_gltf; + } + } + } + + for (cgltf_size i = 0; i < data->animations_count; ++i) + { + for (cgltf_size j = 0; j < data->animations[i].channels_count; ++j) + { + cgltf_animation_channel* channel = &data->animations[i].channels[j]; + + if (!channel->target_node) + { + continue; + } + + cgltf_size components = 1; + + if (channel->target_path == cgltf_animation_path_type_weights) + { + if (!channel->target_node->mesh || !channel->target_node->mesh->primitives_count) + { + return cgltf_result_invalid_gltf; + } + + components = channel->target_node->mesh->primitives[0].targets_count; + } + + cgltf_size values = channel->sampler->interpolation == cgltf_interpolation_type_cubic_spline ? 3 : 1; + + if (channel->sampler->input->count * components * values != channel->sampler->output->count) + { + return cgltf_result_data_too_short; + } + } + } + + return cgltf_result_success; +} + +cgltf_result cgltf_copy_extras_json(const cgltf_data* data, const cgltf_extras* extras, char* dest, cgltf_size* dest_size) +{ + cgltf_size json_size = extras->end_offset - extras->start_offset; + + if (!dest) + { + if (dest_size) + { + *dest_size = json_size + 1; + return cgltf_result_success; + } + return cgltf_result_invalid_options; + } + + if (*dest_size + 1 < json_size) + { + strncpy(dest, data->json + extras->start_offset, *dest_size - 1); + dest[*dest_size - 1] = 0; + } + else + { + strncpy(dest, data->json + extras->start_offset, json_size); + dest[json_size] = 0; + } + + return cgltf_result_success; +} + +void cgltf_free_extensions(cgltf_data* data, cgltf_extension* extensions, cgltf_size extensions_count) +{ + for (cgltf_size i = 0; i < extensions_count; ++i) + { + data->memory.free(data->memory.user_data, extensions[i].name); + data->memory.free(data->memory.user_data, extensions[i].data); + } + data->memory.free(data->memory.user_data, extensions); +} + +void cgltf_free(cgltf_data* data) +{ + if (!data) + { + return; + } + + void (*file_release)(const struct cgltf_memory_options*, const struct cgltf_file_options*, void* data) = data->file.release ? data->file.release : cgltf_default_file_release; + + data->memory.free(data->memory.user_data, data->asset.copyright); + data->memory.free(data->memory.user_data, data->asset.generator); + data->memory.free(data->memory.user_data, data->asset.version); + data->memory.free(data->memory.user_data, data->asset.min_version); + + cgltf_free_extensions(data, data->asset.extensions, data->asset.extensions_count); + + for (cgltf_size i = 0; i < data->accessors_count; ++i) + { + if(data->accessors[i].is_sparse) + { + cgltf_free_extensions(data, data->accessors[i].sparse.extensions, data->accessors[i].sparse.extensions_count); + cgltf_free_extensions(data, data->accessors[i].sparse.indices_extensions, data->accessors[i].sparse.indices_extensions_count); + cgltf_free_extensions(data, data->accessors[i].sparse.values_extensions, data->accessors[i].sparse.values_extensions_count); + } + cgltf_free_extensions(data, data->accessors[i].extensions, data->accessors[i].extensions_count); + } + data->memory.free(data->memory.user_data, data->accessors); + + for (cgltf_size i = 0; i < data->buffer_views_count; ++i) + { + cgltf_free_extensions(data, data->buffer_views[i].extensions, data->buffer_views[i].extensions_count); + } + data->memory.free(data->memory.user_data, data->buffer_views); + + for (cgltf_size i = 0; i < data->buffers_count; ++i) + { + if (data->buffers[i].data != data->bin) + { + file_release(&data->memory, &data->file, data->buffers[i].data); + } + data->memory.free(data->memory.user_data, data->buffers[i].uri); + + cgltf_free_extensions(data, data->buffers[i].extensions, data->buffers[i].extensions_count); + } + + data->memory.free(data->memory.user_data, data->buffers); + + for (cgltf_size i = 0; i < data->meshes_count; ++i) + { + data->memory.free(data->memory.user_data, data->meshes[i].name); + + for (cgltf_size j = 0; j < data->meshes[i].primitives_count; ++j) + { + for (cgltf_size k = 0; k < data->meshes[i].primitives[j].attributes_count; ++k) + { + data->memory.free(data->memory.user_data, data->meshes[i].primitives[j].attributes[k].name); + } + + data->memory.free(data->memory.user_data, data->meshes[i].primitives[j].attributes); + + for (cgltf_size k = 0; k < data->meshes[i].primitives[j].targets_count; ++k) + { + for (cgltf_size m = 0; m < data->meshes[i].primitives[j].targets[k].attributes_count; ++m) + { + data->memory.free(data->memory.user_data, data->meshes[i].primitives[j].targets[k].attributes[m].name); + } + + data->memory.free(data->memory.user_data, data->meshes[i].primitives[j].targets[k].attributes); + } + + data->memory.free(data->memory.user_data, data->meshes[i].primitives[j].targets); + + if (data->meshes[i].primitives[j].has_draco_mesh_compression) + { + for (cgltf_size k = 0; k < data->meshes[i].primitives[j].draco_mesh_compression.attributes_count; ++k) + { + data->memory.free(data->memory.user_data, data->meshes[i].primitives[j].draco_mesh_compression.attributes[k].name); + } + + data->memory.free(data->memory.user_data, data->meshes[i].primitives[j].draco_mesh_compression.attributes); + } + + cgltf_free_extensions(data, data->meshes[i].primitives[j].extensions, data->meshes[i].primitives[j].extensions_count); + } + + data->memory.free(data->memory.user_data, data->meshes[i].primitives); + data->memory.free(data->memory.user_data, data->meshes[i].weights); + + for (cgltf_size j = 0; j < data->meshes[i].target_names_count; ++j) + { + data->memory.free(data->memory.user_data, data->meshes[i].target_names[j]); + } + + cgltf_free_extensions(data, data->meshes[i].extensions, data->meshes[i].extensions_count); + + data->memory.free(data->memory.user_data, data->meshes[i].target_names); + } + + data->memory.free(data->memory.user_data, data->meshes); + + for (cgltf_size i = 0; i < data->materials_count; ++i) + { + data->memory.free(data->memory.user_data, data->materials[i].name); + + if(data->materials[i].has_pbr_metallic_roughness) + { + cgltf_free_extensions(data, data->materials[i].pbr_metallic_roughness.metallic_roughness_texture.extensions, data->materials[i].pbr_metallic_roughness.metallic_roughness_texture.extensions_count); + cgltf_free_extensions(data, data->materials[i].pbr_metallic_roughness.base_color_texture.extensions, data->materials[i].pbr_metallic_roughness.base_color_texture.extensions_count); + } + if(data->materials[i].has_pbr_specular_glossiness) + { + cgltf_free_extensions(data, data->materials[i].pbr_specular_glossiness.diffuse_texture.extensions, data->materials[i].pbr_specular_glossiness.diffuse_texture.extensions_count); + cgltf_free_extensions(data, data->materials[i].pbr_specular_glossiness.specular_glossiness_texture.extensions, data->materials[i].pbr_specular_glossiness.specular_glossiness_texture.extensions_count); + } + if(data->materials[i].has_clearcoat) + { + cgltf_free_extensions(data, data->materials[i].clearcoat.clearcoat_texture.extensions, data->materials[i].clearcoat.clearcoat_texture.extensions_count); + cgltf_free_extensions(data, data->materials[i].clearcoat.clearcoat_roughness_texture.extensions, data->materials[i].clearcoat.clearcoat_roughness_texture.extensions_count); + cgltf_free_extensions(data, data->materials[i].clearcoat.clearcoat_normal_texture.extensions, data->materials[i].clearcoat.clearcoat_normal_texture.extensions_count); + } + if(data->materials[i].has_specular) + { + cgltf_free_extensions(data, data->materials[i].specular.specular_texture.extensions, data->materials[i].specular.specular_texture.extensions_count); + } + if(data->materials[i].has_transmission) + { + cgltf_free_extensions(data, data->materials[i].transmission.transmission_texture.extensions, data->materials[i].transmission.transmission_texture.extensions_count); + } + + cgltf_free_extensions(data, data->materials[i].normal_texture.extensions, data->materials[i].normal_texture.extensions_count); + cgltf_free_extensions(data, data->materials[i].occlusion_texture.extensions, data->materials[i].occlusion_texture.extensions_count); + cgltf_free_extensions(data, data->materials[i].emissive_texture.extensions, data->materials[i].emissive_texture.extensions_count); + + cgltf_free_extensions(data, data->materials[i].extensions, data->materials[i].extensions_count); + } + + data->memory.free(data->memory.user_data, data->materials); + + for (cgltf_size i = 0; i < data->images_count; ++i) + { + data->memory.free(data->memory.user_data, data->images[i].name); + data->memory.free(data->memory.user_data, data->images[i].uri); + data->memory.free(data->memory.user_data, data->images[i].mime_type); + + cgltf_free_extensions(data, data->images[i].extensions, data->images[i].extensions_count); + } + + data->memory.free(data->memory.user_data, data->images); + + for (cgltf_size i = 0; i < data->textures_count; ++i) + { + data->memory.free(data->memory.user_data, data->textures[i].name); + cgltf_free_extensions(data, data->textures[i].extensions, data->textures[i].extensions_count); + } + + data->memory.free(data->memory.user_data, data->textures); + + for (cgltf_size i = 0; i < data->samplers_count; ++i) + { + cgltf_free_extensions(data, data->samplers[i].extensions, data->samplers[i].extensions_count); + } + + data->memory.free(data->memory.user_data, data->samplers); + + for (cgltf_size i = 0; i < data->skins_count; ++i) + { + data->memory.free(data->memory.user_data, data->skins[i].name); + data->memory.free(data->memory.user_data, data->skins[i].joints); + + cgltf_free_extensions(data, data->skins[i].extensions, data->skins[i].extensions_count); + } + + data->memory.free(data->memory.user_data, data->skins); + + for (cgltf_size i = 0; i < data->cameras_count; ++i) + { + data->memory.free(data->memory.user_data, data->cameras[i].name); + cgltf_free_extensions(data, data->cameras[i].extensions, data->cameras[i].extensions_count); + } + + data->memory.free(data->memory.user_data, data->cameras); + + for (cgltf_size i = 0; i < data->lights_count; ++i) + { + data->memory.free(data->memory.user_data, data->lights[i].name); + } + + data->memory.free(data->memory.user_data, data->lights); + + for (cgltf_size i = 0; i < data->nodes_count; ++i) + { + data->memory.free(data->memory.user_data, data->nodes[i].name); + data->memory.free(data->memory.user_data, data->nodes[i].children); + data->memory.free(data->memory.user_data, data->nodes[i].weights); + cgltf_free_extensions(data, data->nodes[i].extensions, data->nodes[i].extensions_count); + } + + data->memory.free(data->memory.user_data, data->nodes); + + for (cgltf_size i = 0; i < data->scenes_count; ++i) + { + data->memory.free(data->memory.user_data, data->scenes[i].name); + data->memory.free(data->memory.user_data, data->scenes[i].nodes); + + cgltf_free_extensions(data, data->scenes[i].extensions, data->scenes[i].extensions_count); + } + + data->memory.free(data->memory.user_data, data->scenes); + + for (cgltf_size i = 0; i < data->animations_count; ++i) + { + data->memory.free(data->memory.user_data, data->animations[i].name); + for (cgltf_size j = 0; j < data->animations[i].samplers_count; ++j) + { + cgltf_free_extensions(data, data->animations[i].samplers[j].extensions, data->animations[i].samplers[j].extensions_count); + } + data->memory.free(data->memory.user_data, data->animations[i].samplers); + + for (cgltf_size j = 0; j < data->animations[i].channels_count; ++j) + { + cgltf_free_extensions(data, data->animations[i].channels[j].extensions, data->animations[i].channels[j].extensions_count); + } + data->memory.free(data->memory.user_data, data->animations[i].channels); + + cgltf_free_extensions(data, data->animations[i].extensions, data->animations[i].extensions_count); + } + + data->memory.free(data->memory.user_data, data->animations); + + cgltf_free_extensions(data, data->data_extensions, data->data_extensions_count); + + for (cgltf_size i = 0; i < data->extensions_used_count; ++i) + { + data->memory.free(data->memory.user_data, data->extensions_used[i]); + } + + data->memory.free(data->memory.user_data, data->extensions_used); + + for (cgltf_size i = 0; i < data->extensions_required_count; ++i) + { + data->memory.free(data->memory.user_data, data->extensions_required[i]); + } + + data->memory.free(data->memory.user_data, data->extensions_required); + + file_release(&data->memory, &data->file, data->file_data); + + data->memory.free(data->memory.user_data, data); +} + +void cgltf_node_transform_local(const cgltf_node* node, cgltf_float* out_matrix) +{ + cgltf_float* lm = out_matrix; + + if (node->has_matrix) + { + memcpy(lm, node->matrix, sizeof(float) * 16); + } + else + { + float tx = node->translation[0]; + float ty = node->translation[1]; + float tz = node->translation[2]; + + float qx = node->rotation[0]; + float qy = node->rotation[1]; + float qz = node->rotation[2]; + float qw = node->rotation[3]; + + float sx = node->scale[0]; + float sy = node->scale[1]; + float sz = node->scale[2]; + + lm[0] = (1 - 2 * qy*qy - 2 * qz*qz) * sx; + lm[1] = (2 * qx*qy + 2 * qz*qw) * sx; + lm[2] = (2 * qx*qz - 2 * qy*qw) * sx; + lm[3] = 0.f; + + lm[4] = (2 * qx*qy - 2 * qz*qw) * sy; + lm[5] = (1 - 2 * qx*qx - 2 * qz*qz) * sy; + lm[6] = (2 * qy*qz + 2 * qx*qw) * sy; + lm[7] = 0.f; + + lm[8] = (2 * qx*qz + 2 * qy*qw) * sz; + lm[9] = (2 * qy*qz - 2 * qx*qw) * sz; + lm[10] = (1 - 2 * qx*qx - 2 * qy*qy) * sz; + lm[11] = 0.f; + + lm[12] = tx; + lm[13] = ty; + lm[14] = tz; + lm[15] = 1.f; + } +} + +void cgltf_node_transform_world(const cgltf_node* node, cgltf_float* out_matrix) +{ + cgltf_float* lm = out_matrix; + cgltf_node_transform_local(node, lm); + + const cgltf_node* parent = node->parent; + + while (parent) + { + float pm[16]; + cgltf_node_transform_local(parent, pm); + + for (int i = 0; i < 4; ++i) + { + float l0 = lm[i * 4 + 0]; + float l1 = lm[i * 4 + 1]; + float l2 = lm[i * 4 + 2]; + + float r0 = l0 * pm[0] + l1 * pm[4] + l2 * pm[8]; + float r1 = l0 * pm[1] + l1 * pm[5] + l2 * pm[9]; + float r2 = l0 * pm[2] + l1 * pm[6] + l2 * pm[10]; + + lm[i * 4 + 0] = r0; + lm[i * 4 + 1] = r1; + lm[i * 4 + 2] = r2; + } + + lm[12] += pm[12]; + lm[13] += pm[13]; + lm[14] += pm[14]; + + parent = parent->parent; + } +} + +static cgltf_size cgltf_component_read_index(const void* in, cgltf_component_type component_type) +{ + switch (component_type) + { + case cgltf_component_type_r_16: + return *((const int16_t*) in); + case cgltf_component_type_r_16u: + return *((const uint16_t*) in); + case cgltf_component_type_r_32u: + return *((const uint32_t*) in); + case cgltf_component_type_r_32f: + return (cgltf_size)*((const float*) in); + case cgltf_component_type_r_8: + return *((const int8_t*) in); + case cgltf_component_type_r_8u: + return *((const uint8_t*) in); + default: + return 0; + } +} + +static cgltf_float cgltf_component_read_float(const void* in, cgltf_component_type component_type, cgltf_bool normalized) +{ + if (component_type == cgltf_component_type_r_32f) + { + return *((const float*) in); + } + + if (normalized) + { + switch (component_type) + { + // note: glTF spec doesn't currently define normalized conversions for 32-bit integers + case cgltf_component_type_r_16: + return *((const int16_t*) in) / (cgltf_float)32767; + case cgltf_component_type_r_16u: + return *((const uint16_t*) in) / (cgltf_float)65535; + case cgltf_component_type_r_8: + return *((const int8_t*) in) / (cgltf_float)127; + case cgltf_component_type_r_8u: + return *((const uint8_t*) in) / (cgltf_float)255; + default: + return 0; + } + } + + return (cgltf_float)cgltf_component_read_index(in, component_type); +} + +static cgltf_size cgltf_component_size(cgltf_component_type component_type); + +static cgltf_bool cgltf_element_read_float(const uint8_t* element, cgltf_type type, cgltf_component_type component_type, cgltf_bool normalized, cgltf_float* out, cgltf_size element_size) +{ + cgltf_size num_components = cgltf_num_components(type); + + if (element_size < num_components) { + return 0; + } + + // There are three special cases for component extraction, see #data-alignment in the 2.0 spec. + + cgltf_size component_size = cgltf_component_size(component_type); + + if (type == cgltf_type_mat2 && component_size == 1) + { + out[0] = cgltf_component_read_float(element, component_type, normalized); + out[1] = cgltf_component_read_float(element + 1, component_type, normalized); + out[2] = cgltf_component_read_float(element + 4, component_type, normalized); + out[3] = cgltf_component_read_float(element + 5, component_type, normalized); + return 1; + } + + if (type == cgltf_type_mat3 && component_size == 1) + { + out[0] = cgltf_component_read_float(element, component_type, normalized); + out[1] = cgltf_component_read_float(element + 1, component_type, normalized); + out[2] = cgltf_component_read_float(element + 2, component_type, normalized); + out[3] = cgltf_component_read_float(element + 4, component_type, normalized); + out[4] = cgltf_component_read_float(element + 5, component_type, normalized); + out[5] = cgltf_component_read_float(element + 6, component_type, normalized); + out[6] = cgltf_component_read_float(element + 8, component_type, normalized); + out[7] = cgltf_component_read_float(element + 9, component_type, normalized); + out[8] = cgltf_component_read_float(element + 10, component_type, normalized); + return 1; + } + + if (type == cgltf_type_mat3 && component_size == 2) + { + out[0] = cgltf_component_read_float(element, component_type, normalized); + out[1] = cgltf_component_read_float(element + 2, component_type, normalized); + out[2] = cgltf_component_read_float(element + 4, component_type, normalized); + out[3] = cgltf_component_read_float(element + 8, component_type, normalized); + out[4] = cgltf_component_read_float(element + 10, component_type, normalized); + out[5] = cgltf_component_read_float(element + 12, component_type, normalized); + out[6] = cgltf_component_read_float(element + 16, component_type, normalized); + out[7] = cgltf_component_read_float(element + 18, component_type, normalized); + out[8] = cgltf_component_read_float(element + 20, component_type, normalized); + return 1; + } + + for (cgltf_size i = 0; i < num_components; ++i) + { + out[i] = cgltf_component_read_float(element + component_size * i, component_type, normalized); + } + return 1; +} + +cgltf_bool cgltf_accessor_read_float(const cgltf_accessor* accessor, cgltf_size index, cgltf_float* out, cgltf_size element_size) +{ + if (accessor->is_sparse) + { + return 0; + } + if (accessor->buffer_view == NULL) + { + memset(out, 0, element_size * sizeof(cgltf_float)); + return 1; + } + if (accessor->buffer_view->buffer->data == NULL) + { + return 0; + } + cgltf_size offset = accessor->offset + accessor->buffer_view->offset; + const uint8_t* element = (const uint8_t*) accessor->buffer_view->buffer->data; + element += offset + accessor->stride * index; + return cgltf_element_read_float(element, accessor->type, accessor->component_type, accessor->normalized, out, element_size); +} + +cgltf_size cgltf_accessor_unpack_floats(const cgltf_accessor* accessor, cgltf_float* out, cgltf_size float_count) +{ + cgltf_size floats_per_element = cgltf_num_components(accessor->type); + cgltf_size available_floats = accessor->count * floats_per_element; + if (out == NULL) + { + return available_floats; + } + + float_count = available_floats < float_count ? available_floats : float_count; + cgltf_size element_count = float_count / floats_per_element; + + // First pass: convert each element in the base accessor. + cgltf_float* dest = out; + cgltf_accessor dense = *accessor; + dense.is_sparse = 0; + for (cgltf_size index = 0; index < element_count; index++, dest += floats_per_element) + { + if (!cgltf_accessor_read_float(&dense, index, dest, floats_per_element)) + { + return 0; + } + } + + // Second pass: write out each element in the sparse accessor. + if (accessor->is_sparse) + { + const cgltf_accessor_sparse* sparse = &dense.sparse; + + if (sparse->indices_buffer_view->buffer->data == NULL || sparse->values_buffer_view->buffer->data == NULL) + { + return 0; + } + + const uint8_t* index_data = (const uint8_t*) sparse->indices_buffer_view->buffer->data; + index_data += sparse->indices_byte_offset + sparse->indices_buffer_view->offset; + cgltf_size index_stride = cgltf_component_size(sparse->indices_component_type); + const uint8_t* reader_head = (const uint8_t*) sparse->values_buffer_view->buffer->data; + reader_head += sparse->values_byte_offset + sparse->values_buffer_view->offset; + for (cgltf_size reader_index = 0; reader_index < sparse->count; reader_index++, index_data += index_stride) + { + size_t writer_index = cgltf_component_read_index(index_data, sparse->indices_component_type); + float* writer_head = out + writer_index * floats_per_element; + + if (!cgltf_element_read_float(reader_head, dense.type, dense.component_type, dense.normalized, writer_head, floats_per_element)) + { + return 0; + } + + reader_head += dense.stride; + } + } + + return element_count * floats_per_element; +} + +static cgltf_uint cgltf_component_read_uint(const void* in, cgltf_component_type component_type) +{ + switch (component_type) + { + case cgltf_component_type_r_8: + return *((const int8_t*) in); + + case cgltf_component_type_r_8u: + return *((const uint8_t*) in); + + case cgltf_component_type_r_16: + return *((const int16_t*) in); + + case cgltf_component_type_r_16u: + return *((const uint16_t*) in); + + case cgltf_component_type_r_32u: + return *((const uint32_t*) in); + + default: + return 0; + } +} + +static cgltf_bool cgltf_element_read_uint(const uint8_t* element, cgltf_type type, cgltf_component_type component_type, cgltf_uint* out, cgltf_size element_size) +{ + cgltf_size num_components = cgltf_num_components(type); + + if (element_size < num_components) + { + return 0; + } + + // Reading integer matrices is not a valid use case + if (type == cgltf_type_mat2 || type == cgltf_type_mat3 || type == cgltf_type_mat4) + { + return 0; + } + + cgltf_size component_size = cgltf_component_size(component_type); + + for (cgltf_size i = 0; i < num_components; ++i) + { + out[i] = cgltf_component_read_uint(element + component_size * i, component_type); + } + return 1; +} + +cgltf_bool cgltf_accessor_read_uint(const cgltf_accessor* accessor, cgltf_size index, cgltf_uint* out, cgltf_size element_size) +{ + if (accessor->is_sparse) + { + return 0; + } + if (accessor->buffer_view == NULL) + { + memset(out, 0, element_size * sizeof( cgltf_uint )); + return 1; + } + if (accessor->buffer_view->buffer->data == NULL) + { + return 0; + } + cgltf_size offset = accessor->offset + accessor->buffer_view->offset; + const uint8_t* element = (const uint8_t*) accessor->buffer_view->buffer->data; + element += offset + accessor->stride * index; + return cgltf_element_read_uint(element, accessor->type, accessor->component_type, out, element_size); +} + +cgltf_size cgltf_accessor_read_index(const cgltf_accessor* accessor, cgltf_size index) +{ + if (accessor->is_sparse) + { + return 0; // This is an error case, but we can't communicate the error with existing interface. + } + if (accessor->buffer_view == NULL) + { + return 0; + } + if (accessor->buffer_view->buffer->data == NULL) + { + return 0; // This is an error case, but we can't communicate the error with existing interface. + } + + cgltf_size offset = accessor->offset + accessor->buffer_view->offset; + const uint8_t* element = (const uint8_t*) accessor->buffer_view->buffer->data; + element += offset + accessor->stride * index; + return cgltf_component_read_index(element, accessor->component_type); +} + +#define CGLTF_ERROR_JSON -1 +#define CGLTF_ERROR_NOMEM -2 +#define CGLTF_ERROR_LEGACY -3 + +#define CGLTF_CHECK_TOKTYPE(tok_, type_) if ((tok_).type != (type_)) { return CGLTF_ERROR_JSON; } +#define CGLTF_CHECK_KEY(tok_) if ((tok_).type != JSMN_STRING || (tok_).size == 0) { return CGLTF_ERROR_JSON; } /* checking size for 0 verifies that a value follows the key */ + +#define CGLTF_PTRINDEX(type, idx) (type*)((cgltf_size)idx + 1) +#define CGLTF_PTRFIXUP(var, data, size) if (var) { if ((cgltf_size)var > size) { return CGLTF_ERROR_JSON; } var = &data[(cgltf_size)var-1]; } +#define CGLTF_PTRFIXUP_REQ(var, data, size) if (!var || (cgltf_size)var > size) { return CGLTF_ERROR_JSON; } var = &data[(cgltf_size)var-1]; + +static int cgltf_json_strcmp(jsmntok_t const* tok, const uint8_t* json_chunk, const char* str) +{ + CGLTF_CHECK_TOKTYPE(*tok, JSMN_STRING); + size_t const str_len = strlen(str); + size_t const name_length = tok->end - tok->start; + return (str_len == name_length) ? strncmp((const char*)json_chunk + tok->start, str, str_len) : 128; +} + +static int cgltf_json_to_int(jsmntok_t const* tok, const uint8_t* json_chunk) +{ + CGLTF_CHECK_TOKTYPE(*tok, JSMN_PRIMITIVE); + char tmp[128]; + int size = (cgltf_size)(tok->end - tok->start) < sizeof(tmp) ? tok->end - tok->start : (int)(sizeof(tmp) - 1); + strncpy(tmp, (const char*)json_chunk + tok->start, size); + tmp[size] = 0; + return CGLTF_ATOI(tmp); +} + +static cgltf_float cgltf_json_to_float(jsmntok_t const* tok, const uint8_t* json_chunk) +{ + CGLTF_CHECK_TOKTYPE(*tok, JSMN_PRIMITIVE); + char tmp[128]; + int size = (cgltf_size)(tok->end - tok->start) < sizeof(tmp) ? tok->end - tok->start : (int)(sizeof(tmp) - 1); + strncpy(tmp, (const char*)json_chunk + tok->start, size); + tmp[size] = 0; + return (cgltf_float)CGLTF_ATOF(tmp); +} + +static cgltf_bool cgltf_json_to_bool(jsmntok_t const* tok, const uint8_t* json_chunk) +{ + int size = tok->end - tok->start; + return size == 4 && memcmp(json_chunk + tok->start, "true", 4) == 0; +} + +static int cgltf_skip_json(jsmntok_t const* tokens, int i) +{ + int end = i + 1; + + while (i < end) + { + switch (tokens[i].type) + { + case JSMN_OBJECT: + end += tokens[i].size * 2; + break; + + case JSMN_ARRAY: + end += tokens[i].size; + break; + + case JSMN_PRIMITIVE: + case JSMN_STRING: + break; + + default: + return -1; + } + + i++; + } + + return i; +} + +static void cgltf_fill_float_array(float* out_array, int size, float value) +{ + for (int j = 0; j < size; ++j) + { + out_array[j] = value; + } +} + +static int cgltf_parse_json_float_array(jsmntok_t const* tokens, int i, const uint8_t* json_chunk, float* out_array, int size) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_ARRAY); + if (tokens[i].size != size) + { + return CGLTF_ERROR_JSON; + } + ++i; + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE); + out_array[j] = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + return i; +} + +static int cgltf_parse_json_string(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, char** out_string) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_STRING); + if (*out_string) + { + return CGLTF_ERROR_JSON; + } + int size = tokens[i].end - tokens[i].start; + char* result = (char*)options->memory.alloc(options->memory.user_data, size + 1); + if (!result) + { + return CGLTF_ERROR_NOMEM; + } + strncpy(result, (const char*)json_chunk + tokens[i].start, size); + result[size] = 0; + *out_string = result; + return i + 1; +} + +static int cgltf_parse_json_array(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, size_t element_size, void** out_array, cgltf_size* out_size) +{ + (void)json_chunk; + if (tokens[i].type != JSMN_ARRAY) + { + return tokens[i].type == JSMN_OBJECT ? CGLTF_ERROR_LEGACY : CGLTF_ERROR_JSON; + } + if (*out_array) + { + return CGLTF_ERROR_JSON; + } + int size = tokens[i].size; + void* result = cgltf_calloc(options, element_size, size); + if (!result) + { + return CGLTF_ERROR_NOMEM; + } + *out_array = result; + *out_size = size; + return i + 1; +} + +static int cgltf_parse_json_string_array(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, char*** out_array, cgltf_size* out_size) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_ARRAY); + i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(char*), (void**)out_array, out_size); + if (i < 0) + { + return i; + } + + for (cgltf_size j = 0; j < *out_size; ++j) + { + i = cgltf_parse_json_string(options, tokens, i, json_chunk, j + (*out_array)); + if (i < 0) + { + return i; + } + } + return i; +} + +static void cgltf_parse_attribute_type(const char* name, cgltf_attribute_type* out_type, int* out_index) +{ + const char* us = strchr(name, '_'); + size_t len = us ? (size_t)(us - name) : strlen(name); + + if (len == 8 && strncmp(name, "POSITION", 8) == 0) + { + *out_type = cgltf_attribute_type_position; + } + else if (len == 6 && strncmp(name, "NORMAL", 6) == 0) + { + *out_type = cgltf_attribute_type_normal; + } + else if (len == 7 && strncmp(name, "TANGENT", 7) == 0) + { + *out_type = cgltf_attribute_type_tangent; + } + else if (len == 8 && strncmp(name, "TEXCOORD", 8) == 0) + { + *out_type = cgltf_attribute_type_texcoord; + } + else if (len == 5 && strncmp(name, "COLOR", 5) == 0) + { + *out_type = cgltf_attribute_type_color; + } + else if (len == 6 && strncmp(name, "JOINTS", 6) == 0) + { + *out_type = cgltf_attribute_type_joints; + } + else if (len == 7 && strncmp(name, "WEIGHTS", 7) == 0) + { + *out_type = cgltf_attribute_type_weights; + } + else + { + *out_type = cgltf_attribute_type_invalid; + } + + if (us && *out_type != cgltf_attribute_type_invalid) + { + *out_index = CGLTF_ATOI(us + 1); + } +} + +static int cgltf_parse_json_attribute_list(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_attribute** out_attributes, cgltf_size* out_attributes_count) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + if (*out_attributes) + { + return CGLTF_ERROR_JSON; + } + + *out_attributes_count = tokens[i].size; + *out_attributes = (cgltf_attribute*)cgltf_calloc(options, sizeof(cgltf_attribute), *out_attributes_count); + ++i; + + if (!*out_attributes) + { + return CGLTF_ERROR_NOMEM; + } + + for (cgltf_size j = 0; j < *out_attributes_count; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + i = cgltf_parse_json_string(options, tokens, i, json_chunk, &(*out_attributes)[j].name); + if (i < 0) + { + return CGLTF_ERROR_JSON; + } + + cgltf_parse_attribute_type((*out_attributes)[j].name, &(*out_attributes)[j].type, &(*out_attributes)[j].index); + + (*out_attributes)[j].data = CGLTF_PTRINDEX(cgltf_accessor, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + + return i; +} + +static int cgltf_parse_json_extras(jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_extras* out_extras) +{ + (void)json_chunk; + out_extras->start_offset = tokens[i].start; + out_extras->end_offset = tokens[i].end; + i = cgltf_skip_json(tokens, i); + return i; +} + +static int cgltf_parse_json_unprocessed_extension(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_extension* out_extension) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_STRING); + CGLTF_CHECK_TOKTYPE(tokens[i+1], JSMN_OBJECT); + if (out_extension->name) + { + return CGLTF_ERROR_JSON; + } + + cgltf_size name_length = tokens[i].end - tokens[i].start; + out_extension->name = (char*)options->memory.alloc(options->memory.user_data, name_length + 1); + if (!out_extension->name) + { + return CGLTF_ERROR_NOMEM; + } + strncpy(out_extension->name, (const char*)json_chunk + tokens[i].start, name_length); + out_extension->name[name_length] = 0; + i++; + + size_t start = tokens[i].start; + size_t size = tokens[i].end - start; + out_extension->data = (char*)options->memory.alloc(options->memory.user_data, size + 1); + if (!out_extension->data) + { + return CGLTF_ERROR_NOMEM; + } + strncpy(out_extension->data, (const char*)json_chunk + start, size); + out_extension->data[size] = '\0'; + + i = cgltf_skip_json(tokens, i); + + return i; +} + +static int cgltf_parse_json_unprocessed_extensions(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_size* out_extensions_count, cgltf_extension** out_extensions) +{ + ++i; + + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + if(*out_extensions) + { + return CGLTF_ERROR_JSON; + } + + int extensions_size = tokens[i].size; + *out_extensions_count = 0; + *out_extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size); + + if (!*out_extensions) + { + return CGLTF_ERROR_NOMEM; + } + + ++i; + + for (int j = 0; j < extensions_size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + cgltf_size extension_index = (*out_extensions_count)++; + cgltf_extension* extension = &((*out_extensions)[extension_index]); + i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, extension); + + if (i < 0) + { + return i; + } + } + return i; +} + +static int cgltf_parse_json_draco_mesh_compression(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_draco_mesh_compression* out_draco_mesh_compression) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "attributes") == 0) + { + i = cgltf_parse_json_attribute_list(options, tokens, i + 1, json_chunk, &out_draco_mesh_compression->attributes, &out_draco_mesh_compression->attributes_count); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "bufferView") == 0) + { + ++i; + out_draco_mesh_compression->buffer_view = CGLTF_PTRINDEX(cgltf_buffer_view, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + } + + return i; +} + +static int cgltf_parse_json_primitive(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_primitive* out_prim) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + out_prim->type = cgltf_primitive_type_triangles; + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "mode") == 0) + { + ++i; + out_prim->type + = (cgltf_primitive_type) + cgltf_json_to_int(tokens+i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "indices") == 0) + { + ++i; + out_prim->indices = CGLTF_PTRINDEX(cgltf_accessor, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "material") == 0) + { + ++i; + out_prim->material = CGLTF_PTRINDEX(cgltf_material, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "attributes") == 0) + { + i = cgltf_parse_json_attribute_list(options, tokens, i + 1, json_chunk, &out_prim->attributes, &out_prim->attributes_count); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "targets") == 0) + { + i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_morph_target), (void**)&out_prim->targets, &out_prim->targets_count); + if (i < 0) + { + return i; + } + + for (cgltf_size k = 0; k < out_prim->targets_count; ++k) + { + i = cgltf_parse_json_attribute_list(options, tokens, i, json_chunk, &out_prim->targets[k].attributes, &out_prim->targets[k].attributes_count); + if (i < 0) + { + return i; + } + } + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_prim->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + ++i; + + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + if(out_prim->extensions) + { + return CGLTF_ERROR_JSON; + } + + int extensions_size = tokens[i].size; + out_prim->extensions_count = 0; + out_prim->extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size); + + if (!out_prim->extensions) + { + return CGLTF_ERROR_NOMEM; + } + + ++i; + for (int k = 0; k < extensions_size; ++k) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_draco_mesh_compression") == 0) + { + out_prim->has_draco_mesh_compression = 1; + i = cgltf_parse_json_draco_mesh_compression(options, tokens, i + 1, json_chunk, &out_prim->draco_mesh_compression); + } + else + { + i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, &(out_prim->extensions[out_prim->extensions_count++])); + } + + if (i < 0) + { + return i; + } + } + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_mesh(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_mesh* out_mesh) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_mesh->name); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "primitives") == 0) + { + i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_primitive), (void**)&out_mesh->primitives, &out_mesh->primitives_count); + if (i < 0) + { + return i; + } + + for (cgltf_size prim_index = 0; prim_index < out_mesh->primitives_count; ++prim_index) + { + i = cgltf_parse_json_primitive(options, tokens, i, json_chunk, &out_mesh->primitives[prim_index]); + if (i < 0) + { + return i; + } + } + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "weights") == 0) + { + i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_float), (void**)&out_mesh->weights, &out_mesh->weights_count); + if (i < 0) + { + return i; + } + + i = cgltf_parse_json_float_array(tokens, i - 1, json_chunk, out_mesh->weights, (int)out_mesh->weights_count); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + ++i; + + out_mesh->extras.start_offset = tokens[i].start; + out_mesh->extras.end_offset = tokens[i].end; + + if (tokens[i].type == JSMN_OBJECT) + { + int extras_size = tokens[i].size; + ++i; + + for (int k = 0; k < extras_size; ++k) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "targetNames") == 0) + { + i = cgltf_parse_json_string_array(options, tokens, i + 1, json_chunk, &out_mesh->target_names, &out_mesh->target_names_count); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + } + else + { + i = cgltf_skip_json(tokens, i); + } + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_mesh->extensions_count, &out_mesh->extensions); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_meshes(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) +{ + i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_mesh), (void**)&out_data->meshes, &out_data->meshes_count); + if (i < 0) + { + return i; + } + + for (cgltf_size j = 0; j < out_data->meshes_count; ++j) + { + i = cgltf_parse_json_mesh(options, tokens, i, json_chunk, &out_data->meshes[j]); + if (i < 0) + { + return i; + } + } + return i; +} + +static cgltf_component_type cgltf_json_to_component_type(jsmntok_t const* tok, const uint8_t* json_chunk) +{ + int type = cgltf_json_to_int(tok, json_chunk); + + switch (type) + { + case 5120: + return cgltf_component_type_r_8; + case 5121: + return cgltf_component_type_r_8u; + case 5122: + return cgltf_component_type_r_16; + case 5123: + return cgltf_component_type_r_16u; + case 5125: + return cgltf_component_type_r_32u; + case 5126: + return cgltf_component_type_r_32f; + default: + return cgltf_component_type_invalid; + } +} + +static int cgltf_parse_json_accessor_sparse(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_accessor_sparse* out_sparse) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "count") == 0) + { + ++i; + out_sparse->count = cgltf_json_to_int(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "indices") == 0) + { + ++i; + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int indices_size = tokens[i].size; + ++i; + + for (int k = 0; k < indices_size; ++k) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "bufferView") == 0) + { + ++i; + out_sparse->indices_buffer_view = CGLTF_PTRINDEX(cgltf_buffer_view, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteOffset") == 0) + { + ++i; + out_sparse->indices_byte_offset = cgltf_json_to_int(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "componentType") == 0) + { + ++i; + out_sparse->indices_component_type = cgltf_json_to_component_type(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_sparse->indices_extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_sparse->indices_extensions_count, &out_sparse->indices_extensions); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "values") == 0) + { + ++i; + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int values_size = tokens[i].size; + ++i; + + for (int k = 0; k < values_size; ++k) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "bufferView") == 0) + { + ++i; + out_sparse->values_buffer_view = CGLTF_PTRINDEX(cgltf_buffer_view, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteOffset") == 0) + { + ++i; + out_sparse->values_byte_offset = cgltf_json_to_int(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_sparse->values_extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_sparse->values_extensions_count, &out_sparse->values_extensions); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_sparse->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_sparse->extensions_count, &out_sparse->extensions); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_accessor(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_accessor* out_accessor) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "bufferView") == 0) + { + ++i; + out_accessor->buffer_view = CGLTF_PTRINDEX(cgltf_buffer_view, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteOffset") == 0) + { + ++i; + out_accessor->offset = + cgltf_json_to_int(tokens+i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "componentType") == 0) + { + ++i; + out_accessor->component_type = cgltf_json_to_component_type(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "normalized") == 0) + { + ++i; + out_accessor->normalized = cgltf_json_to_bool(tokens+i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "count") == 0) + { + ++i; + out_accessor->count = + cgltf_json_to_int(tokens+i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "type") == 0) + { + ++i; + if (cgltf_json_strcmp(tokens+i, json_chunk, "SCALAR") == 0) + { + out_accessor->type = cgltf_type_scalar; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "VEC2") == 0) + { + out_accessor->type = cgltf_type_vec2; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "VEC3") == 0) + { + out_accessor->type = cgltf_type_vec3; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "VEC4") == 0) + { + out_accessor->type = cgltf_type_vec4; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "MAT2") == 0) + { + out_accessor->type = cgltf_type_mat2; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "MAT3") == 0) + { + out_accessor->type = cgltf_type_mat3; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "MAT4") == 0) + { + out_accessor->type = cgltf_type_mat4; + } + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "min") == 0) + { + ++i; + out_accessor->has_min = 1; + // note: we can't parse the precise number of elements since type may not have been computed yet + int min_size = tokens[i].size > 16 ? 16 : tokens[i].size; + i = cgltf_parse_json_float_array(tokens, i, json_chunk, out_accessor->min, min_size); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "max") == 0) + { + ++i; + out_accessor->has_max = 1; + // note: we can't parse the precise number of elements since type may not have been computed yet + int max_size = tokens[i].size > 16 ? 16 : tokens[i].size; + i = cgltf_parse_json_float_array(tokens, i, json_chunk, out_accessor->max, max_size); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "sparse") == 0) + { + out_accessor->is_sparse = 1; + i = cgltf_parse_json_accessor_sparse(options, tokens, i + 1, json_chunk, &out_accessor->sparse); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_accessor->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_accessor->extensions_count, &out_accessor->extensions); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_texture_transform(jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_texture_transform* out_texture_transform) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "offset") == 0) + { + i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_texture_transform->offset, 2); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "rotation") == 0) + { + ++i; + out_texture_transform->rotation = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "scale") == 0) + { + i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_texture_transform->scale, 2); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "texCoord") == 0) + { + ++i; + out_texture_transform->texcoord = cgltf_json_to_int(tokens + i, json_chunk); + ++i; + } + else + { + i = cgltf_skip_json(tokens, i + 1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_texture_view(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_texture_view* out_texture_view) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + out_texture_view->scale = 1.0f; + cgltf_fill_float_array(out_texture_view->transform.scale, 2, 1.0f); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "index") == 0) + { + ++i; + out_texture_view->texture = CGLTF_PTRINDEX(cgltf_texture, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "texCoord") == 0) + { + ++i; + out_texture_view->texcoord = cgltf_json_to_int(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "scale") == 0) + { + ++i; + out_texture_view->scale = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "strength") == 0) + { + ++i; + out_texture_view->scale = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_texture_view->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + ++i; + + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + if(out_texture_view->extensions) + { + return CGLTF_ERROR_JSON; + } + + int extensions_size = tokens[i].size; + out_texture_view->extensions_count = 0; + out_texture_view->extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size); + + if (!out_texture_view->extensions) + { + return CGLTF_ERROR_NOMEM; + } + + ++i; + + for (int k = 0; k < extensions_size; ++k) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_texture_transform") == 0) + { + out_texture_view->has_transform = 1; + i = cgltf_parse_json_texture_transform(tokens, i + 1, json_chunk, &out_texture_view->transform); + } + else + { + i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, &(out_texture_view->extensions[out_texture_view->extensions_count++])); + } + + if (i < 0) + { + return i; + } + } + } + else + { + i = cgltf_skip_json(tokens, i + 1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_pbr_metallic_roughness(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_pbr_metallic_roughness* out_pbr) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "metallicFactor") == 0) + { + ++i; + out_pbr->metallic_factor = + cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "roughnessFactor") == 0) + { + ++i; + out_pbr->roughness_factor = + cgltf_json_to_float(tokens+i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "baseColorFactor") == 0) + { + i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_pbr->base_color_factor, 4); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "baseColorTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, + &out_pbr->base_color_texture); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "metallicRoughnessTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, + &out_pbr->metallic_roughness_texture); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_pbr->extras); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_pbr_specular_glossiness(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_pbr_specular_glossiness* out_pbr) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "diffuseFactor") == 0) + { + i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_pbr->diffuse_factor, 4); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "specularFactor") == 0) + { + i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_pbr->specular_factor, 3); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "glossinessFactor") == 0) + { + ++i; + out_pbr->glossiness_factor = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "diffuseTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_pbr->diffuse_texture); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "specularGlossinessTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_pbr->specular_glossiness_texture); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_clearcoat(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_clearcoat* out_clearcoat) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "clearcoatFactor") == 0) + { + ++i; + out_clearcoat->clearcoat_factor = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "clearcoatRoughnessFactor") == 0) + { + ++i; + out_clearcoat->clearcoat_roughness_factor = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "clearcoatTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_clearcoat->clearcoat_texture); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "clearcoatRoughnessTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_clearcoat->clearcoat_roughness_texture); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "clearcoatNormalTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_clearcoat->clearcoat_normal_texture); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_ior(jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_ior* out_ior) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + int size = tokens[i].size; + ++i; + + // Default values + out_ior->ior = 1.5f; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "ior") == 0) + { + ++i; + out_ior->ior = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_specular(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_specular* out_specular) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + int size = tokens[i].size; + ++i; + + // Default values + out_specular->specular_factor = 1.0f; + cgltf_fill_float_array(out_specular->specular_color_factor, 3, 1.0f); + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "specularFactor") == 0) + { + ++i; + out_specular->specular_factor = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "specularColorFactor") == 0) + { + i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_specular->specular_color_factor, 3); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "specularTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_specular->specular_texture); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_transmission(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_transmission* out_transmission) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "transmissionFactor") == 0) + { + ++i; + out_transmission->transmission_factor = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "transmissionTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_transmission->transmission_texture); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_image(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_image* out_image) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "uri") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_image->uri); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "bufferView") == 0) + { + ++i; + out_image->buffer_view = CGLTF_PTRINDEX(cgltf_buffer_view, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "mimeType") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_image->mime_type); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "name") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_image->name); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_image->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_image->extensions_count, &out_image->extensions); + } + else + { + i = cgltf_skip_json(tokens, i + 1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_sampler(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_sampler* out_sampler) +{ + (void)options; + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + out_sampler->wrap_s = 10497; + out_sampler->wrap_t = 10497; + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "magFilter") == 0) + { + ++i; + out_sampler->mag_filter + = cgltf_json_to_int(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "minFilter") == 0) + { + ++i; + out_sampler->min_filter + = cgltf_json_to_int(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "wrapS") == 0) + { + ++i; + out_sampler->wrap_s + = cgltf_json_to_int(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "wrapT") == 0) + { + ++i; + out_sampler->wrap_t + = cgltf_json_to_int(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_sampler->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_sampler->extensions_count, &out_sampler->extensions); + } + else + { + i = cgltf_skip_json(tokens, i + 1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_texture(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_texture* out_texture) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_texture->name); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "sampler") == 0) + { + ++i; + out_texture->sampler = CGLTF_PTRINDEX(cgltf_sampler, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "source") == 0) + { + ++i; + out_texture->image = CGLTF_PTRINDEX(cgltf_image, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_texture->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_texture->extensions_count, &out_texture->extensions); + } + else + { + i = cgltf_skip_json(tokens, i + 1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_material(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_material* out_material) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + cgltf_fill_float_array(out_material->pbr_metallic_roughness.base_color_factor, 4, 1.0f); + out_material->pbr_metallic_roughness.metallic_factor = 1.0f; + out_material->pbr_metallic_roughness.roughness_factor = 1.0f; + + cgltf_fill_float_array(out_material->pbr_specular_glossiness.diffuse_factor, 4, 1.0f); + cgltf_fill_float_array(out_material->pbr_specular_glossiness.specular_factor, 3, 1.0f); + out_material->pbr_specular_glossiness.glossiness_factor = 1.0f; + + out_material->alpha_cutoff = 0.5f; + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_material->name); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "pbrMetallicRoughness") == 0) + { + out_material->has_pbr_metallic_roughness = 1; + i = cgltf_parse_json_pbr_metallic_roughness(options, tokens, i + 1, json_chunk, &out_material->pbr_metallic_roughness); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "emissiveFactor") == 0) + { + i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_material->emissive_factor, 3); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "normalTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, + &out_material->normal_texture); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "occlusionTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, + &out_material->occlusion_texture); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "emissiveTexture") == 0) + { + i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, + &out_material->emissive_texture); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "alphaMode") == 0) + { + ++i; + if (cgltf_json_strcmp(tokens + i, json_chunk, "OPAQUE") == 0) + { + out_material->alpha_mode = cgltf_alpha_mode_opaque; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "MASK") == 0) + { + out_material->alpha_mode = cgltf_alpha_mode_mask; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "BLEND") == 0) + { + out_material->alpha_mode = cgltf_alpha_mode_blend; + } + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "alphaCutoff") == 0) + { + ++i; + out_material->alpha_cutoff = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "doubleSided") == 0) + { + ++i; + out_material->double_sided = + cgltf_json_to_bool(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_material->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + ++i; + + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + if(out_material->extensions) + { + return CGLTF_ERROR_JSON; + } + + int extensions_size = tokens[i].size; + ++i; + out_material->extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size); + out_material->extensions_count= 0; + + if (!out_material->extensions) + { + return CGLTF_ERROR_NOMEM; + } + + for (int k = 0; k < extensions_size; ++k) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_pbrSpecularGlossiness") == 0) + { + out_material->has_pbr_specular_glossiness = 1; + i = cgltf_parse_json_pbr_specular_glossiness(options, tokens, i + 1, json_chunk, &out_material->pbr_specular_glossiness); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_unlit") == 0) + { + out_material->unlit = 1; + i = cgltf_skip_json(tokens, i+1); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_clearcoat") == 0) + { + out_material->has_clearcoat = 1; + i = cgltf_parse_json_clearcoat(options, tokens, i + 1, json_chunk, &out_material->clearcoat); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_ior") == 0) + { + out_material->has_ior = 1; + i = cgltf_parse_json_ior(tokens, i + 1, json_chunk, &out_material->ior); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_specular") == 0) + { + out_material->has_specular = 1; + i = cgltf_parse_json_specular(options, tokens, i + 1, json_chunk, &out_material->specular); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_transmission") == 0) + { + out_material->has_transmission = 1; + i = cgltf_parse_json_transmission(options, tokens, i + 1, json_chunk, &out_material->transmission); + } + else + { + i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, &(out_material->extensions[out_material->extensions_count++])); + } + + if (i < 0) + { + return i; + } + } + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_accessors(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) +{ + i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_accessor), (void**)&out_data->accessors, &out_data->accessors_count); + if (i < 0) + { + return i; + } + + for (cgltf_size j = 0; j < out_data->accessors_count; ++j) + { + i = cgltf_parse_json_accessor(options, tokens, i, json_chunk, &out_data->accessors[j]); + if (i < 0) + { + return i; + } + } + return i; +} + +static int cgltf_parse_json_materials(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) +{ + i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_material), (void**)&out_data->materials, &out_data->materials_count); + if (i < 0) + { + return i; + } + + for (cgltf_size j = 0; j < out_data->materials_count; ++j) + { + i = cgltf_parse_json_material(options, tokens, i, json_chunk, &out_data->materials[j]); + if (i < 0) + { + return i; + } + } + return i; +} + +static int cgltf_parse_json_images(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) +{ + i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_image), (void**)&out_data->images, &out_data->images_count); + if (i < 0) + { + return i; + } + + for (cgltf_size j = 0; j < out_data->images_count; ++j) + { + i = cgltf_parse_json_image(options, tokens, i, json_chunk, &out_data->images[j]); + if (i < 0) + { + return i; + } + } + return i; +} + +static int cgltf_parse_json_textures(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) +{ + i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_texture), (void**)&out_data->textures, &out_data->textures_count); + if (i < 0) + { + return i; + } + + for (cgltf_size j = 0; j < out_data->textures_count; ++j) + { + i = cgltf_parse_json_texture(options, tokens, i, json_chunk, &out_data->textures[j]); + if (i < 0) + { + return i; + } + } + return i; +} + +static int cgltf_parse_json_samplers(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) +{ + i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_sampler), (void**)&out_data->samplers, &out_data->samplers_count); + if (i < 0) + { + return i; + } + + for (cgltf_size j = 0; j < out_data->samplers_count; ++j) + { + i = cgltf_parse_json_sampler(options, tokens, i, json_chunk, &out_data->samplers[j]); + if (i < 0) + { + return i; + } + } + return i; +} + +static int cgltf_parse_json_buffer_view(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_buffer_view* out_buffer_view) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "buffer") == 0) + { + ++i; + out_buffer_view->buffer = CGLTF_PTRINDEX(cgltf_buffer, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteOffset") == 0) + { + ++i; + out_buffer_view->offset = + cgltf_json_to_int(tokens+i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteLength") == 0) + { + ++i; + out_buffer_view->size = + cgltf_json_to_int(tokens+i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteStride") == 0) + { + ++i; + out_buffer_view->stride = + cgltf_json_to_int(tokens+i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "target") == 0) + { + ++i; + int type = cgltf_json_to_int(tokens+i, json_chunk); + switch (type) + { + case 34962: + type = cgltf_buffer_view_type_vertices; + break; + case 34963: + type = cgltf_buffer_view_type_indices; + break; + default: + type = cgltf_buffer_view_type_invalid; + break; + } + out_buffer_view->type = (cgltf_buffer_view_type)type; + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_buffer_view->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_buffer_view->extensions_count, &out_buffer_view->extensions); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_buffer_views(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) +{ + i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_buffer_view), (void**)&out_data->buffer_views, &out_data->buffer_views_count); + if (i < 0) + { + return i; + } + + for (cgltf_size j = 0; j < out_data->buffer_views_count; ++j) + { + i = cgltf_parse_json_buffer_view(options, tokens, i, json_chunk, &out_data->buffer_views[j]); + if (i < 0) + { + return i; + } + } + return i; +} + +static int cgltf_parse_json_buffer(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_buffer* out_buffer) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "byteLength") == 0) + { + ++i; + out_buffer->size = + cgltf_json_to_int(tokens+i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "uri") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_buffer->uri); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_buffer->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_buffer->extensions_count, &out_buffer->extensions); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_buffers(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) +{ + i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_buffer), (void**)&out_data->buffers, &out_data->buffers_count); + if (i < 0) + { + return i; + } + + for (cgltf_size j = 0; j < out_data->buffers_count; ++j) + { + i = cgltf_parse_json_buffer(options, tokens, i, json_chunk, &out_data->buffers[j]); + if (i < 0) + { + return i; + } + } + return i; +} + +static int cgltf_parse_json_skin(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_skin* out_skin) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_skin->name); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "joints") == 0) + { + i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_node*), (void**)&out_skin->joints, &out_skin->joints_count); + if (i < 0) + { + return i; + } + + for (cgltf_size k = 0; k < out_skin->joints_count; ++k) + { + out_skin->joints[k] = CGLTF_PTRINDEX(cgltf_node, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "skeleton") == 0) + { + ++i; + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE); + out_skin->skeleton = CGLTF_PTRINDEX(cgltf_node, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "inverseBindMatrices") == 0) + { + ++i; + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE); + out_skin->inverse_bind_matrices = CGLTF_PTRINDEX(cgltf_accessor, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_skin->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_skin->extensions_count, &out_skin->extensions); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_skins(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) +{ + i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_skin), (void**)&out_data->skins, &out_data->skins_count); + if (i < 0) + { + return i; + } + + for (cgltf_size j = 0; j < out_data->skins_count; ++j) + { + i = cgltf_parse_json_skin(options, tokens, i, json_chunk, &out_data->skins[j]); + if (i < 0) + { + return i; + } + } + return i; +} + +static int cgltf_parse_json_camera(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_camera* out_camera) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_camera->name); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "type") == 0) + { + ++i; + if (cgltf_json_strcmp(tokens + i, json_chunk, "perspective") == 0) + { + out_camera->type = cgltf_camera_type_perspective; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "orthographic") == 0) + { + out_camera->type = cgltf_camera_type_orthographic; + } + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "perspective") == 0) + { + ++i; + + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int data_size = tokens[i].size; + ++i; + + out_camera->type = cgltf_camera_type_perspective; + + for (int k = 0; k < data_size; ++k) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "aspectRatio") == 0) + { + ++i; + out_camera->data.perspective.aspect_ratio = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "yfov") == 0) + { + ++i; + out_camera->data.perspective.yfov = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "zfar") == 0) + { + ++i; + out_camera->data.perspective.zfar = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "znear") == 0) + { + ++i; + out_camera->data.perspective.znear = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_camera->data.perspective.extras); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "orthographic") == 0) + { + ++i; + + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int data_size = tokens[i].size; + ++i; + + out_camera->type = cgltf_camera_type_orthographic; + + for (int k = 0; k < data_size; ++k) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "xmag") == 0) + { + ++i; + out_camera->data.orthographic.xmag = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "ymag") == 0) + { + ++i; + out_camera->data.orthographic.ymag = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "zfar") == 0) + { + ++i; + out_camera->data.orthographic.zfar = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "znear") == 0) + { + ++i; + out_camera->data.orthographic.znear = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_camera->data.orthographic.extras); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_camera->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_camera->extensions_count, &out_camera->extensions); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_cameras(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) +{ + i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_camera), (void**)&out_data->cameras, &out_data->cameras_count); + if (i < 0) + { + return i; + } + + for (cgltf_size j = 0; j < out_data->cameras_count; ++j) + { + i = cgltf_parse_json_camera(options, tokens, i, json_chunk, &out_data->cameras[j]); + if (i < 0) + { + return i; + } + } + return i; +} + +static int cgltf_parse_json_light(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_light* out_light) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_light->name); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "color") == 0) + { + i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_light->color, 3); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "intensity") == 0) + { + ++i; + out_light->intensity = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "type") == 0) + { + ++i; + if (cgltf_json_strcmp(tokens + i, json_chunk, "directional") == 0) + { + out_light->type = cgltf_light_type_directional; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "point") == 0) + { + out_light->type = cgltf_light_type_point; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "spot") == 0) + { + out_light->type = cgltf_light_type_spot; + } + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "range") == 0) + { + ++i; + out_light->range = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "spot") == 0) + { + ++i; + + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int data_size = tokens[i].size; + ++i; + + for (int k = 0; k < data_size; ++k) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "innerConeAngle") == 0) + { + ++i; + out_light->spot_inner_cone_angle = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "outerConeAngle") == 0) + { + ++i; + out_light->spot_outer_cone_angle = cgltf_json_to_float(tokens + i, json_chunk); + ++i; + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_lights(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) +{ + i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_light), (void**)&out_data->lights, &out_data->lights_count); + if (i < 0) + { + return i; + } + + for (cgltf_size j = 0; j < out_data->lights_count; ++j) + { + i = cgltf_parse_json_light(options, tokens, i, json_chunk, &out_data->lights[j]); + if (i < 0) + { + return i; + } + } + return i; +} + +static int cgltf_parse_json_node(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_node* out_node) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + out_node->rotation[3] = 1.0f; + out_node->scale[0] = 1.0f; + out_node->scale[1] = 1.0f; + out_node->scale[2] = 1.0f; + out_node->matrix[0] = 1.0f; + out_node->matrix[5] = 1.0f; + out_node->matrix[10] = 1.0f; + out_node->matrix[15] = 1.0f; + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_node->name); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "children") == 0) + { + i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_node*), (void**)&out_node->children, &out_node->children_count); + if (i < 0) + { + return i; + } + + for (cgltf_size k = 0; k < out_node->children_count; ++k) + { + out_node->children[k] = CGLTF_PTRINDEX(cgltf_node, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "mesh") == 0) + { + ++i; + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE); + out_node->mesh = CGLTF_PTRINDEX(cgltf_mesh, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "skin") == 0) + { + ++i; + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE); + out_node->skin = CGLTF_PTRINDEX(cgltf_skin, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "camera") == 0) + { + ++i; + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE); + out_node->camera = CGLTF_PTRINDEX(cgltf_camera, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "translation") == 0) + { + out_node->has_translation = 1; + i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_node->translation, 3); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "rotation") == 0) + { + out_node->has_rotation = 1; + i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_node->rotation, 4); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "scale") == 0) + { + out_node->has_scale = 1; + i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_node->scale, 3); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "matrix") == 0) + { + out_node->has_matrix = 1; + i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_node->matrix, 16); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "weights") == 0) + { + i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_float), (void**)&out_node->weights, &out_node->weights_count); + if (i < 0) + { + return i; + } + + i = cgltf_parse_json_float_array(tokens, i - 1, json_chunk, out_node->weights, (int)out_node->weights_count); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_node->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + ++i; + + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + if(out_node->extensions) + { + return CGLTF_ERROR_JSON; + } + + int extensions_size = tokens[i].size; + out_node->extensions_count= 0; + out_node->extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size); + + if (!out_node->extensions) + { + return CGLTF_ERROR_NOMEM; + } + + ++i; + + for (int k = 0; k < extensions_size; ++k) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_lights_punctual") == 0) + { + ++i; + + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int data_size = tokens[i].size; + ++i; + + for (int m = 0; m < data_size; ++m) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "light") == 0) + { + ++i; + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE); + out_node->light = CGLTF_PTRINDEX(cgltf_light, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else + { + i = cgltf_skip_json(tokens, i + 1); + } + + if (i < 0) + { + return i; + } + } + } + else + { + i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, &(out_node->extensions[out_node->extensions_count++])); + } + + if (i < 0) + { + return i; + } + } + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_nodes(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) +{ + i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_node), (void**)&out_data->nodes, &out_data->nodes_count); + if (i < 0) + { + return i; + } + + for (cgltf_size j = 0; j < out_data->nodes_count; ++j) + { + i = cgltf_parse_json_node(options, tokens, i, json_chunk, &out_data->nodes[j]); + if (i < 0) + { + return i; + } + } + return i; +} + +static int cgltf_parse_json_scene(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_scene* out_scene) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_scene->name); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "nodes") == 0) + { + i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_node*), (void**)&out_scene->nodes, &out_scene->nodes_count); + if (i < 0) + { + return i; + } + + for (cgltf_size k = 0; k < out_scene->nodes_count; ++k) + { + out_scene->nodes[k] = CGLTF_PTRINDEX(cgltf_node, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_scene->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_scene->extensions_count, &out_scene->extensions); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_scenes(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) +{ + i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_scene), (void**)&out_data->scenes, &out_data->scenes_count); + if (i < 0) + { + return i; + } + + for (cgltf_size j = 0; j < out_data->scenes_count; ++j) + { + i = cgltf_parse_json_scene(options, tokens, i, json_chunk, &out_data->scenes[j]); + if (i < 0) + { + return i; + } + } + return i; +} + +static int cgltf_parse_json_animation_sampler(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_animation_sampler* out_sampler) +{ + (void)options; + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "input") == 0) + { + ++i; + out_sampler->input = CGLTF_PTRINDEX(cgltf_accessor, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "output") == 0) + { + ++i; + out_sampler->output = CGLTF_PTRINDEX(cgltf_accessor, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "interpolation") == 0) + { + ++i; + if (cgltf_json_strcmp(tokens + i, json_chunk, "LINEAR") == 0) + { + out_sampler->interpolation = cgltf_interpolation_type_linear; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "STEP") == 0) + { + out_sampler->interpolation = cgltf_interpolation_type_step; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "CUBICSPLINE") == 0) + { + out_sampler->interpolation = cgltf_interpolation_type_cubic_spline; + } + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_sampler->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_sampler->extensions_count, &out_sampler->extensions); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_animation_channel(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_animation_channel* out_channel) +{ + (void)options; + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "sampler") == 0) + { + ++i; + out_channel->sampler = CGLTF_PTRINDEX(cgltf_animation_sampler, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "target") == 0) + { + ++i; + + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int target_size = tokens[i].size; + ++i; + + for (int k = 0; k < target_size; ++k) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "node") == 0) + { + ++i; + out_channel->target_node = CGLTF_PTRINDEX(cgltf_node, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "path") == 0) + { + ++i; + if (cgltf_json_strcmp(tokens+i, json_chunk, "translation") == 0) + { + out_channel->target_path = cgltf_animation_path_type_translation; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "rotation") == 0) + { + out_channel->target_path = cgltf_animation_path_type_rotation; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "scale") == 0) + { + out_channel->target_path = cgltf_animation_path_type_scale; + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "weights") == 0) + { + out_channel->target_path = cgltf_animation_path_type_weights; + } + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_channel->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_channel->extensions_count, &out_channel->extensions); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_animation(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_animation* out_animation) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_animation->name); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "samplers") == 0) + { + i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_animation_sampler), (void**)&out_animation->samplers, &out_animation->samplers_count); + if (i < 0) + { + return i; + } + + for (cgltf_size k = 0; k < out_animation->samplers_count; ++k) + { + i = cgltf_parse_json_animation_sampler(options, tokens, i, json_chunk, &out_animation->samplers[k]); + if (i < 0) + { + return i; + } + } + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "channels") == 0) + { + i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_animation_channel), (void**)&out_animation->channels, &out_animation->channels_count); + if (i < 0) + { + return i; + } + + for (cgltf_size k = 0; k < out_animation->channels_count; ++k) + { + i = cgltf_parse_json_animation_channel(options, tokens, i, json_chunk, &out_animation->channels[k]); + if (i < 0) + { + return i; + } + } + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_animation->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_animation->extensions_count, &out_animation->extensions); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +static int cgltf_parse_json_animations(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) +{ + i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_animation), (void**)&out_data->animations, &out_data->animations_count); + if (i < 0) + { + return i; + } + + for (cgltf_size j = 0; j < out_data->animations_count; ++j) + { + i = cgltf_parse_json_animation(options, tokens, i, json_chunk, &out_data->animations[j]); + if (i < 0) + { + return i; + } + } + return i; +} + +static int cgltf_parse_json_asset(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_asset* out_asset) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "copyright") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_asset->copyright); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "generator") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_asset->generator); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "version") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_asset->version); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "minVersion") == 0) + { + i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_asset->min_version); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_asset->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_asset->extensions_count, &out_asset->extensions); + } + else + { + i = cgltf_skip_json(tokens, i+1); + } + + if (i < 0) + { + return i; + } + } + + if (out_asset->version && CGLTF_ATOF(out_asset->version) < 2) + { + return CGLTF_ERROR_LEGACY; + } + + return i; +} + +cgltf_size cgltf_num_components(cgltf_type type) { + switch (type) + { + case cgltf_type_vec2: + return 2; + case cgltf_type_vec3: + return 3; + case cgltf_type_vec4: + return 4; + case cgltf_type_mat2: + return 4; + case cgltf_type_mat3: + return 9; + case cgltf_type_mat4: + return 16; + case cgltf_type_invalid: + case cgltf_type_scalar: + default: + return 1; + } +} + +static cgltf_size cgltf_component_size(cgltf_component_type component_type) { + switch (component_type) + { + case cgltf_component_type_r_8: + case cgltf_component_type_r_8u: + return 1; + case cgltf_component_type_r_16: + case cgltf_component_type_r_16u: + return 2; + case cgltf_component_type_r_32u: + case cgltf_component_type_r_32f: + return 4; + case cgltf_component_type_invalid: + default: + return 0; + } +} + +static cgltf_size cgltf_calc_size(cgltf_type type, cgltf_component_type component_type) +{ + cgltf_size component_size = cgltf_component_size(component_type); + if (type == cgltf_type_mat2 && component_size == 1) + { + return 8 * component_size; + } + else if (type == cgltf_type_mat3 && (component_size == 1 || component_size == 2)) + { + return 12 * component_size; + } + return component_size * cgltf_num_components(type); +} + +static int cgltf_fixup_pointers(cgltf_data* out_data); + +static int cgltf_parse_json_root(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) +{ + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int size = tokens[i].size; + ++i; + + for (int j = 0; j < size; ++j) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "asset") == 0) + { + i = cgltf_parse_json_asset(options, tokens, i + 1, json_chunk, &out_data->asset); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "meshes") == 0) + { + i = cgltf_parse_json_meshes(options, tokens, i + 1, json_chunk, out_data); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "accessors") == 0) + { + i = cgltf_parse_json_accessors(options, tokens, i + 1, json_chunk, out_data); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "bufferViews") == 0) + { + i = cgltf_parse_json_buffer_views(options, tokens, i + 1, json_chunk, out_data); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "buffers") == 0) + { + i = cgltf_parse_json_buffers(options, tokens, i + 1, json_chunk, out_data); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "materials") == 0) + { + i = cgltf_parse_json_materials(options, tokens, i + 1, json_chunk, out_data); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "images") == 0) + { + i = cgltf_parse_json_images(options, tokens, i + 1, json_chunk, out_data); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "textures") == 0) + { + i = cgltf_parse_json_textures(options, tokens, i + 1, json_chunk, out_data); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "samplers") == 0) + { + i = cgltf_parse_json_samplers(options, tokens, i + 1, json_chunk, out_data); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "skins") == 0) + { + i = cgltf_parse_json_skins(options, tokens, i + 1, json_chunk, out_data); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "cameras") == 0) + { + i = cgltf_parse_json_cameras(options, tokens, i + 1, json_chunk, out_data); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "nodes") == 0) + { + i = cgltf_parse_json_nodes(options, tokens, i + 1, json_chunk, out_data); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "scenes") == 0) + { + i = cgltf_parse_json_scenes(options, tokens, i + 1, json_chunk, out_data); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "scene") == 0) + { + ++i; + out_data->scene = CGLTF_PTRINDEX(cgltf_scene, cgltf_json_to_int(tokens + i, json_chunk)); + ++i; + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "animations") == 0) + { + i = cgltf_parse_json_animations(options, tokens, i + 1, json_chunk, out_data); + } + else if (cgltf_json_strcmp(tokens+i, json_chunk, "extras") == 0) + { + i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_data->extras); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) + { + ++i; + + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + if(out_data->data_extensions) + { + return CGLTF_ERROR_JSON; + } + + int extensions_size = tokens[i].size; + out_data->data_extensions_count = 0; + out_data->data_extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size); + + if (!out_data->data_extensions) + { + return CGLTF_ERROR_NOMEM; + } + + ++i; + + for (int k = 0; k < extensions_size; ++k) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_lights_punctual") == 0) + { + ++i; + + CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); + + int data_size = tokens[i].size; + ++i; + + for (int m = 0; m < data_size; ++m) + { + CGLTF_CHECK_KEY(tokens[i]); + + if (cgltf_json_strcmp(tokens + i, json_chunk, "lights") == 0) + { + i = cgltf_parse_json_lights(options, tokens, i + 1, json_chunk, out_data); + } + else + { + i = cgltf_skip_json(tokens, i + 1); + } + + if (i < 0) + { + return i; + } + } + } + else + { + i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, &(out_data->data_extensions[out_data->data_extensions_count++])); + } + + if (i < 0) + { + return i; + } + } + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensionsUsed") == 0) + { + i = cgltf_parse_json_string_array(options, tokens, i + 1, json_chunk, &out_data->extensions_used, &out_data->extensions_used_count); + } + else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensionsRequired") == 0) + { + i = cgltf_parse_json_string_array(options, tokens, i + 1, json_chunk, &out_data->extensions_required, &out_data->extensions_required_count); + } + else + { + i = cgltf_skip_json(tokens, i + 1); + } + + if (i < 0) + { + return i; + } + } + + return i; +} + +cgltf_result cgltf_parse_json(cgltf_options* options, const uint8_t* json_chunk, cgltf_size size, cgltf_data** out_data) +{ + jsmn_parser parser = { 0, 0, 0 }; + + if (options->json_token_count == 0) + { + int token_count = jsmn_parse(&parser, (const char*)json_chunk, size, NULL, 0); + + if (token_count <= 0) + { + return cgltf_result_invalid_json; + } + + options->json_token_count = token_count; + } + + jsmntok_t* tokens = (jsmntok_t*)options->memory.alloc(options->memory.user_data, sizeof(jsmntok_t) * (options->json_token_count + 1)); + + if (!tokens) + { + return cgltf_result_out_of_memory; + } + + jsmn_init(&parser); + + int token_count = jsmn_parse(&parser, (const char*)json_chunk, size, tokens, options->json_token_count); + + if (token_count <= 0) + { + options->memory.free(options->memory.user_data, tokens); + return cgltf_result_invalid_json; + } + + // this makes sure that we always have an UNDEFINED token at the end of the stream + // for invalid JSON inputs this makes sure we don't perform out of bound reads of token data + tokens[token_count].type = JSMN_UNDEFINED; + + cgltf_data* data = (cgltf_data*)options->memory.alloc(options->memory.user_data, sizeof(cgltf_data)); + + if (!data) + { + options->memory.free(options->memory.user_data, tokens); + return cgltf_result_out_of_memory; + } + + memset(data, 0, sizeof(cgltf_data)); + data->memory = options->memory; + data->file = options->file; + + int i = cgltf_parse_json_root(options, tokens, 0, json_chunk, data); + + options->memory.free(options->memory.user_data, tokens); + + if (i < 0) + { + cgltf_free(data); + + switch (i) + { + case CGLTF_ERROR_NOMEM: return cgltf_result_out_of_memory; + case CGLTF_ERROR_LEGACY: return cgltf_result_legacy_gltf; + default: return cgltf_result_invalid_gltf; + } + } + + if (cgltf_fixup_pointers(data) < 0) + { + cgltf_free(data); + return cgltf_result_invalid_gltf; + } + + data->json = (const char*)json_chunk; + data->json_size = size; + + *out_data = data; + + return cgltf_result_success; +} + +static int cgltf_fixup_pointers(cgltf_data* data) +{ + for (cgltf_size i = 0; i < data->meshes_count; ++i) + { + for (cgltf_size j = 0; j < data->meshes[i].primitives_count; ++j) + { + CGLTF_PTRFIXUP(data->meshes[i].primitives[j].indices, data->accessors, data->accessors_count); + CGLTF_PTRFIXUP(data->meshes[i].primitives[j].material, data->materials, data->materials_count); + + for (cgltf_size k = 0; k < data->meshes[i].primitives[j].attributes_count; ++k) + { + CGLTF_PTRFIXUP_REQ(data->meshes[i].primitives[j].attributes[k].data, data->accessors, data->accessors_count); + } + + for (cgltf_size k = 0; k < data->meshes[i].primitives[j].targets_count; ++k) + { + for (cgltf_size m = 0; m < data->meshes[i].primitives[j].targets[k].attributes_count; ++m) + { + CGLTF_PTRFIXUP_REQ(data->meshes[i].primitives[j].targets[k].attributes[m].data, data->accessors, data->accessors_count); + } + } + + if (data->meshes[i].primitives[j].has_draco_mesh_compression) + { + CGLTF_PTRFIXUP_REQ(data->meshes[i].primitives[j].draco_mesh_compression.buffer_view, data->buffer_views, data->buffer_views_count); + for (cgltf_size m = 0; m < data->meshes[i].primitives[j].draco_mesh_compression.attributes_count; ++m) + { + CGLTF_PTRFIXUP_REQ(data->meshes[i].primitives[j].draco_mesh_compression.attributes[m].data, data->accessors, data->accessors_count); + } + } + } + } + + for (cgltf_size i = 0; i < data->accessors_count; ++i) + { + CGLTF_PTRFIXUP(data->accessors[i].buffer_view, data->buffer_views, data->buffer_views_count); + + if (data->accessors[i].is_sparse) + { + CGLTF_PTRFIXUP_REQ(data->accessors[i].sparse.indices_buffer_view, data->buffer_views, data->buffer_views_count); + CGLTF_PTRFIXUP_REQ(data->accessors[i].sparse.values_buffer_view, data->buffer_views, data->buffer_views_count); + } + + if (data->accessors[i].buffer_view) + { + data->accessors[i].stride = data->accessors[i].buffer_view->stride; + } + + if (data->accessors[i].stride == 0) + { + data->accessors[i].stride = cgltf_calc_size(data->accessors[i].type, data->accessors[i].component_type); + } + } + + for (cgltf_size i = 0; i < data->textures_count; ++i) + { + CGLTF_PTRFIXUP(data->textures[i].image, data->images, data->images_count); + CGLTF_PTRFIXUP(data->textures[i].sampler, data->samplers, data->samplers_count); + } + + for (cgltf_size i = 0; i < data->images_count; ++i) + { + CGLTF_PTRFIXUP(data->images[i].buffer_view, data->buffer_views, data->buffer_views_count); + } + + for (cgltf_size i = 0; i < data->materials_count; ++i) + { + CGLTF_PTRFIXUP(data->materials[i].normal_texture.texture, data->textures, data->textures_count); + CGLTF_PTRFIXUP(data->materials[i].emissive_texture.texture, data->textures, data->textures_count); + CGLTF_PTRFIXUP(data->materials[i].occlusion_texture.texture, data->textures, data->textures_count); + + CGLTF_PTRFIXUP(data->materials[i].pbr_metallic_roughness.base_color_texture.texture, data->textures, data->textures_count); + CGLTF_PTRFIXUP(data->materials[i].pbr_metallic_roughness.metallic_roughness_texture.texture, data->textures, data->textures_count); + + CGLTF_PTRFIXUP(data->materials[i].pbr_specular_glossiness.diffuse_texture.texture, data->textures, data->textures_count); + CGLTF_PTRFIXUP(data->materials[i].pbr_specular_glossiness.specular_glossiness_texture.texture, data->textures, data->textures_count); + + CGLTF_PTRFIXUP(data->materials[i].clearcoat.clearcoat_texture.texture, data->textures, data->textures_count); + CGLTF_PTRFIXUP(data->materials[i].clearcoat.clearcoat_roughness_texture.texture, data->textures, data->textures_count); + CGLTF_PTRFIXUP(data->materials[i].clearcoat.clearcoat_normal_texture.texture, data->textures, data->textures_count); + + CGLTF_PTRFIXUP(data->materials[i].specular.specular_texture.texture, data->textures, data->textures_count); + + CGLTF_PTRFIXUP(data->materials[i].transmission.transmission_texture.texture, data->textures, data->textures_count); + } + + for (cgltf_size i = 0; i < data->buffer_views_count; ++i) + { + CGLTF_PTRFIXUP_REQ(data->buffer_views[i].buffer, data->buffers, data->buffers_count); + } + + for (cgltf_size i = 0; i < data->skins_count; ++i) + { + for (cgltf_size j = 0; j < data->skins[i].joints_count; ++j) + { + CGLTF_PTRFIXUP_REQ(data->skins[i].joints[j], data->nodes, data->nodes_count); + } + + CGLTF_PTRFIXUP(data->skins[i].skeleton, data->nodes, data->nodes_count); + CGLTF_PTRFIXUP(data->skins[i].inverse_bind_matrices, data->accessors, data->accessors_count); + } + + for (cgltf_size i = 0; i < data->nodes_count; ++i) + { + for (cgltf_size j = 0; j < data->nodes[i].children_count; ++j) + { + CGLTF_PTRFIXUP_REQ(data->nodes[i].children[j], data->nodes, data->nodes_count); + + if (data->nodes[i].children[j]->parent) + { + return CGLTF_ERROR_JSON; + } + + data->nodes[i].children[j]->parent = &data->nodes[i]; + } + + CGLTF_PTRFIXUP(data->nodes[i].mesh, data->meshes, data->meshes_count); + CGLTF_PTRFIXUP(data->nodes[i].skin, data->skins, data->skins_count); + CGLTF_PTRFIXUP(data->nodes[i].camera, data->cameras, data->cameras_count); + CGLTF_PTRFIXUP(data->nodes[i].light, data->lights, data->lights_count); + } + + for (cgltf_size i = 0; i < data->scenes_count; ++i) + { + for (cgltf_size j = 0; j < data->scenes[i].nodes_count; ++j) + { + CGLTF_PTRFIXUP_REQ(data->scenes[i].nodes[j], data->nodes, data->nodes_count); + + if (data->scenes[i].nodes[j]->parent) + { + return CGLTF_ERROR_JSON; + } + } + } + + CGLTF_PTRFIXUP(data->scene, data->scenes, data->scenes_count); + + for (cgltf_size i = 0; i < data->animations_count; ++i) + { + for (cgltf_size j = 0; j < data->animations[i].samplers_count; ++j) + { + CGLTF_PTRFIXUP_REQ(data->animations[i].samplers[j].input, data->accessors, data->accessors_count); + CGLTF_PTRFIXUP_REQ(data->animations[i].samplers[j].output, data->accessors, data->accessors_count); + } + + for (cgltf_size j = 0; j < data->animations[i].channels_count; ++j) + { + CGLTF_PTRFIXUP_REQ(data->animations[i].channels[j].sampler, data->animations[i].samplers, data->animations[i].samplers_count); + CGLTF_PTRFIXUP(data->animations[i].channels[j].target_node, data->nodes, data->nodes_count); + } + } + + return 0; +} + +/* + * -- jsmn.c start -- + * Source: https://github.com/zserge/jsmn + * License: MIT + * + * Copyright (c) 2010 Serge A. Zaitsev + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +/** + * Allocates a fresh unused token from the token pull. + */ +static jsmntok_t *jsmn_alloc_token(jsmn_parser *parser, + jsmntok_t *tokens, size_t num_tokens) { + jsmntok_t *tok; + if (parser->toknext >= num_tokens) { + return NULL; + } + tok = &tokens[parser->toknext++]; + tok->start = tok->end = -1; + tok->size = 0; +#ifdef JSMN_PARENT_LINKS + tok->parent = -1; +#endif + return tok; +} + +/** + * Fills token type and boundaries. + */ +static void jsmn_fill_token(jsmntok_t *token, jsmntype_t type, + int start, int end) { + token->type = type; + token->start = start; + token->end = end; + token->size = 0; +} + +/** + * Fills next available token with JSON primitive. + */ +static int jsmn_parse_primitive(jsmn_parser *parser, const char *js, + size_t len, jsmntok_t *tokens, size_t num_tokens) { + jsmntok_t *token; + int start; + + start = parser->pos; + + for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { + switch (js[parser->pos]) { +#ifndef JSMN_STRICT + /* In strict mode primitive must be followed by "," or "}" or "]" */ + case ':': +#endif + case '\t' : case '\r' : case '\n' : case ' ' : + case ',' : case ']' : case '}' : + goto found; + } + if (js[parser->pos] < 32 || js[parser->pos] >= 127) { + parser->pos = start; + return JSMN_ERROR_INVAL; + } + } +#ifdef JSMN_STRICT + /* In strict mode primitive must be followed by a comma/object/array */ + parser->pos = start; + return JSMN_ERROR_PART; +#endif + +found: + if (tokens == NULL) { + parser->pos--; + return 0; + } + token = jsmn_alloc_token(parser, tokens, num_tokens); + if (token == NULL) { + parser->pos = start; + return JSMN_ERROR_NOMEM; + } + jsmn_fill_token(token, JSMN_PRIMITIVE, start, parser->pos); +#ifdef JSMN_PARENT_LINKS + token->parent = parser->toksuper; +#endif + parser->pos--; + return 0; +} + +/** + * Fills next token with JSON string. + */ +static int jsmn_parse_string(jsmn_parser *parser, const char *js, + size_t len, jsmntok_t *tokens, size_t num_tokens) { + jsmntok_t *token; + + int start = parser->pos; + + parser->pos++; + + /* Skip starting quote */ + for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { + char c = js[parser->pos]; + + /* Quote: end of string */ + if (c == '\"') { + if (tokens == NULL) { + return 0; + } + token = jsmn_alloc_token(parser, tokens, num_tokens); + if (token == NULL) { + parser->pos = start; + return JSMN_ERROR_NOMEM; + } + jsmn_fill_token(token, JSMN_STRING, start+1, parser->pos); +#ifdef JSMN_PARENT_LINKS + token->parent = parser->toksuper; +#endif + return 0; + } + + /* Backslash: Quoted symbol expected */ + if (c == '\\' && parser->pos + 1 < len) { + int i; + parser->pos++; + switch (js[parser->pos]) { + /* Allowed escaped symbols */ + case '\"': case '/' : case '\\' : case 'b' : + case 'f' : case 'r' : case 'n' : case 't' : + break; + /* Allows escaped symbol \uXXXX */ + case 'u': + parser->pos++; + for(i = 0; i < 4 && parser->pos < len && js[parser->pos] != '\0'; i++) { + /* If it isn't a hex character we have an error */ + if(!((js[parser->pos] >= 48 && js[parser->pos] <= 57) || /* 0-9 */ + (js[parser->pos] >= 65 && js[parser->pos] <= 70) || /* A-F */ + (js[parser->pos] >= 97 && js[parser->pos] <= 102))) { /* a-f */ + parser->pos = start; + return JSMN_ERROR_INVAL; + } + parser->pos++; + } + parser->pos--; + break; + /* Unexpected symbol */ + default: + parser->pos = start; + return JSMN_ERROR_INVAL; + } + } + } + parser->pos = start; + return JSMN_ERROR_PART; +} + +/** + * Parse JSON string and fill tokens. + */ +static int jsmn_parse(jsmn_parser *parser, const char *js, size_t len, + jsmntok_t *tokens, size_t num_tokens) { + int r; + int i; + jsmntok_t *token; + int count = parser->toknext; + + for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { + char c; + jsmntype_t type; + + c = js[parser->pos]; + switch (c) { + case '{': case '[': + count++; + if (tokens == NULL) { + break; + } + token = jsmn_alloc_token(parser, tokens, num_tokens); + if (token == NULL) + return JSMN_ERROR_NOMEM; + if (parser->toksuper != -1) { + tokens[parser->toksuper].size++; +#ifdef JSMN_PARENT_LINKS + token->parent = parser->toksuper; +#endif + } + token->type = (c == '{' ? JSMN_OBJECT : JSMN_ARRAY); + token->start = parser->pos; + parser->toksuper = parser->toknext - 1; + break; + case '}': case ']': + if (tokens == NULL) + break; + type = (c == '}' ? JSMN_OBJECT : JSMN_ARRAY); +#ifdef JSMN_PARENT_LINKS + if (parser->toknext < 1) { + return JSMN_ERROR_INVAL; + } + token = &tokens[parser->toknext - 1]; + for (;;) { + if (token->start != -1 && token->end == -1) { + if (token->type != type) { + return JSMN_ERROR_INVAL; + } + token->end = parser->pos + 1; + parser->toksuper = token->parent; + break; + } + if (token->parent == -1) { + if(token->type != type || parser->toksuper == -1) { + return JSMN_ERROR_INVAL; + } + break; + } + token = &tokens[token->parent]; + } +#else + for (i = parser->toknext - 1; i >= 0; i--) { + token = &tokens[i]; + if (token->start != -1 && token->end == -1) { + if (token->type != type) { + return JSMN_ERROR_INVAL; + } + parser->toksuper = -1; + token->end = parser->pos + 1; + break; + } + } + /* Error if unmatched closing bracket */ + if (i == -1) return JSMN_ERROR_INVAL; + for (; i >= 0; i--) { + token = &tokens[i]; + if (token->start != -1 && token->end == -1) { + parser->toksuper = i; + break; + } + } +#endif + break; + case '\"': + r = jsmn_parse_string(parser, js, len, tokens, num_tokens); + if (r < 0) return r; + count++; + if (parser->toksuper != -1 && tokens != NULL) + tokens[parser->toksuper].size++; + break; + case '\t' : case '\r' : case '\n' : case ' ': + break; + case ':': + parser->toksuper = parser->toknext - 1; + break; + case ',': + if (tokens != NULL && parser->toksuper != -1 && + tokens[parser->toksuper].type != JSMN_ARRAY && + tokens[parser->toksuper].type != JSMN_OBJECT) { +#ifdef JSMN_PARENT_LINKS + parser->toksuper = tokens[parser->toksuper].parent; +#else + for (i = parser->toknext - 1; i >= 0; i--) { + if (tokens[i].type == JSMN_ARRAY || tokens[i].type == JSMN_OBJECT) { + if (tokens[i].start != -1 && tokens[i].end == -1) { + parser->toksuper = i; + break; + } + } + } +#endif + } + break; +#ifdef JSMN_STRICT + /* In strict mode primitives are: numbers and booleans */ + case '-': case '0': case '1' : case '2': case '3' : case '4': + case '5': case '6': case '7' : case '8': case '9': + case 't': case 'f': case 'n' : + /* And they must not be keys of the object */ + if (tokens != NULL && parser->toksuper != -1) { + jsmntok_t *t = &tokens[parser->toksuper]; + if (t->type == JSMN_OBJECT || + (t->type == JSMN_STRING && t->size != 0)) { + return JSMN_ERROR_INVAL; + } + } +#else + /* In non-strict mode every unquoted value is a primitive */ + default: +#endif + r = jsmn_parse_primitive(parser, js, len, tokens, num_tokens); + if (r < 0) return r; + count++; + if (parser->toksuper != -1 && tokens != NULL) + tokens[parser->toksuper].size++; + break; + +#ifdef JSMN_STRICT + /* Unexpected char in strict mode */ + default: + return JSMN_ERROR_INVAL; +#endif + } + } + + if (tokens != NULL) { + for (i = parser->toknext - 1; i >= 0; i--) { + /* Unmatched opened object or array */ + if (tokens[i].start != -1 && tokens[i].end == -1) { + return JSMN_ERROR_PART; + } + } + } + + return count; +} + +/** + * Creates a new parser based over a given buffer with an array of tokens + * available. + */ +static void jsmn_init(jsmn_parser *parser) { + parser->pos = 0; + parser->toknext = 0; + parser->toksuper = -1; +} +/* + * -- jsmn.c end -- + */ + +#endif /* #ifdef CGLTF_IMPLEMENTATION */ + +/* cgltf is distributed under MIT license: + * + * Copyright (c) 2018 Johannes Kuhlmann + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ diff --git a/contrib/cgltf/cgltf_write.h b/contrib/cgltf/cgltf_write.h new file mode 100644 index 0000000..2096a5b --- /dev/null +++ b/contrib/cgltf/cgltf_write.h @@ -0,0 +1,1173 @@ +/** + * cgltf_write - a single-file glTF 2.0 writer written in C99. + * + * Version: 1.7 + * + * Website: https://github.com/jkuhlmann/cgltf + * + * Distributed under the MIT License, see notice at the end of this file. + * + * Building: + * Include this file where you need the struct and function + * declarations. Have exactly one source file where you define + * `CGLTF_WRITE_IMPLEMENTATION` before including this file to get the + * function definitions. + * + * Reference: + * `cgltf_result cgltf_write_file(const cgltf_options* options, const char* + * path, const cgltf_data* data)` writes JSON to the given file path. Buffer + * files and external images are not written out. `data` is not deallocated. + * + * `cgltf_size cgltf_write(const cgltf_options* options, char* buffer, + * cgltf_size size, const cgltf_data* data)` writes JSON into the given memory + * buffer. Returns the number of bytes written to `buffer`, including a null + * terminator. If buffer is null, returns the number of bytes that would have + * been written. `data` is not deallocated. + * + * To write custom JSON into the `extras` field, aggregate all the custom JSON + * into a single buffer, then set `file_data` to this buffer. By supplying + * start_offset and end_offset values for various objects, you can select a + * range of characters within the aggregated buffer. + */ +#ifndef CGLTF_WRITE_H_INCLUDED__ +#define CGLTF_WRITE_H_INCLUDED__ + +#include "cgltf.h" + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +cgltf_result cgltf_write_file(const cgltf_options* options, const char* path, const cgltf_data* data); +cgltf_size cgltf_write(const cgltf_options* options, char* buffer, cgltf_size size, const cgltf_data* data); + +#ifdef __cplusplus +} +#endif + +#endif /* #ifndef CGLTF_WRITE_H_INCLUDED__ */ + +/* + * + * Stop now, if you are only interested in the API. + * Below, you find the implementation. + * + */ + +#if defined(__INTELLISENSE__) || defined(__JETBRAINS_IDE__) +/* This makes MSVC/CLion intellisense work. */ +#define CGLTF_IMPLEMENTATION +#endif + +#ifdef CGLTF_WRITE_IMPLEMENTATION + +#include +#include +#include +#include + +#define CGLTF_EXTENSION_FLAG_TEXTURE_TRANSFORM (1 << 0) +#define CGLTF_EXTENSION_FLAG_MATERIALS_UNLIT (1 << 1) +#define CGLTF_EXTENSION_FLAG_SPECULAR_GLOSSINESS (1 << 2) +#define CGLTF_EXTENSION_FLAG_LIGHTS_PUNCTUAL (1 << 3) +#define CGLTF_EXTENSION_FLAG_DRACO_MESH_COMPRESSION (1 << 4) +#define CGLTF_EXTENSION_FLAG_MATERIALS_CLEARCOAT (1 << 5) +#define CGLTF_EXTENSION_FLAG_MATERIALS_IOR (1 << 6) +#define CGLTF_EXTENSION_FLAG_MATERIALS_SPECULAR (1 << 7) +#define CGLTF_EXTENSION_FLAG_MATERIALS_TRANSMISSION (1 << 8) + +typedef struct { + char* buffer; + cgltf_size buffer_size; + cgltf_size remaining; + char* cursor; + cgltf_size tmp; + cgltf_size chars_written; + const cgltf_data* data; + int depth; + const char* indent; + int needs_comma; + uint32_t extension_flags; + uint32_t required_extension_flags; +} cgltf_write_context; + +#define CGLTF_MIN(a, b) (a < b ? a : b) + +#define CGLTF_SPRINTF(...) { \ + context->tmp = snprintf ( context->cursor, context->remaining, __VA_ARGS__ ); \ + context->chars_written += context->tmp; \ + if (context->cursor) { \ + context->cursor += context->tmp; \ + context->remaining -= context->tmp; \ + } } + +#define CGLTF_SNPRINTF(length, ...) { \ + context->tmp = snprintf ( context->cursor, CGLTF_MIN(length + 1, context->remaining), __VA_ARGS__ ); \ + context->chars_written += length; \ + if (context->cursor) { \ + context->cursor += length; \ + context->remaining -= length; \ + } } + +#define CGLTF_WRITE_IDXPROP(label, val, start) if (val) { \ + cgltf_write_indent(context); \ + CGLTF_SPRINTF("\"%s\": %d", label, (int) (val - start)); \ + context->needs_comma = 1; } + +#define CGLTF_WRITE_IDXARRPROP(label, dim, vals, start) if (vals) { \ + cgltf_write_indent(context); \ + CGLTF_SPRINTF("\"%s\": [", label); \ + for (int i = 0; i < (int)(dim); ++i) { \ + int idx = (int) (vals[i] - start); \ + if (i != 0) CGLTF_SPRINTF(","); \ + CGLTF_SPRINTF(" %d", idx); \ + } \ + CGLTF_SPRINTF(" ]"); \ + context->needs_comma = 1; } + +#define CGLTF_WRITE_TEXTURE_INFO(label, info) if (info.texture) { \ + cgltf_write_line(context, "\"" label "\": {"); \ + CGLTF_WRITE_IDXPROP("index", info.texture, context->data->textures); \ + cgltf_write_intprop(context, "texCoord", info.texcoord, 0); \ + cgltf_write_floatprop(context, "scale", info.scale, 1.0f); \ + if (info.has_transform) { \ + context->extension_flags |= CGLTF_EXTENSION_FLAG_TEXTURE_TRANSFORM; \ + cgltf_write_texture_transform(context, &info.transform); \ + } \ + cgltf_write_extras(context, &info.extras); \ + cgltf_write_line(context, "}"); } + +static void cgltf_write_indent(cgltf_write_context* context) +{ + if (context->needs_comma) + { + CGLTF_SPRINTF(",\n"); + context->needs_comma = 0; + } + else + { + CGLTF_SPRINTF("\n"); + } + for (int i = 0; i < context->depth; ++i) + { + CGLTF_SPRINTF("%s", context->indent); + } +} + +static void cgltf_write_line(cgltf_write_context* context, const char* line) +{ + if (line[0] == ']' || line[0] == '}') + { + --context->depth; + context->needs_comma = 0; + } + cgltf_write_indent(context); + CGLTF_SPRINTF("%s", line); + cgltf_size last = (cgltf_size)(strlen(line) - 1); + if (line[0] == ']' || line[0] == '}') + { + context->needs_comma = 1; + } + if (line[last] == '[' || line[last] == '{') + { + ++context->depth; + context->needs_comma = 0; + } +} + +static void cgltf_write_strprop(cgltf_write_context* context, const char* label, const char* val) +{ + if (val) + { + cgltf_write_indent(context); + CGLTF_SPRINTF("\"%s\": \"%s\"", label, val); + context->needs_comma = 1; + } +} + +static void cgltf_write_extras(cgltf_write_context* context, const cgltf_extras* extras) +{ + cgltf_size length = extras->end_offset - extras->start_offset; + if (length > 0 && context->data->file_data) + { + char* json_string = ((char*) context->data->file_data) + extras->start_offset; + cgltf_write_indent(context); + CGLTF_SPRINTF("%s", "\"extras\": "); + CGLTF_SNPRINTF(length, "%s", json_string); + context->needs_comma = 1; + } +} + +static void cgltf_write_stritem(cgltf_write_context* context, const char* item) +{ + cgltf_write_indent(context); + CGLTF_SPRINTF("\"%s\"", item); + context->needs_comma = 1; +} + +static void cgltf_write_intprop(cgltf_write_context* context, const char* label, int val, int def) +{ + if (val != def) + { + cgltf_write_indent(context); + CGLTF_SPRINTF("\"%s\": %d", label, val); + context->needs_comma = 1; + } +} + +static void cgltf_write_floatprop(cgltf_write_context* context, const char* label, float val, float def) +{ + if (val != def) + { + cgltf_write_indent(context); + CGLTF_SPRINTF("\"%s\": ", label); + CGLTF_SPRINTF("%g", val); + context->needs_comma = 1; + + if (context->cursor) + { + char *decimal_comma = strchr(context->cursor - context->tmp, ','); + if (decimal_comma) + { + *decimal_comma = '.'; + } + } + } +} + +static void cgltf_write_boolprop_optional(cgltf_write_context* context, const char* label, bool val, bool def) +{ + if (val != def) + { + cgltf_write_indent(context); + CGLTF_SPRINTF("\"%s\": %s", label, val ? "true" : "false"); + context->needs_comma = 1; + } +} + +static void cgltf_write_floatarrayprop(cgltf_write_context* context, const char* label, const cgltf_float* vals, cgltf_size dim) +{ + cgltf_write_indent(context); + CGLTF_SPRINTF("\"%s\": [", label); + for (cgltf_size i = 0; i < dim; ++i) + { + if (i != 0) + { + CGLTF_SPRINTF(", %g", vals[i]); + } + else + { + CGLTF_SPRINTF("%g", vals[i]); + } + } + CGLTF_SPRINTF("]"); + context->needs_comma = 1; +} + +static bool cgltf_check_floatarray(const float* vals, int dim, float val) { + while (dim--) + { + if (vals[dim] != val) + { + return true; + } + } + return false; +} + +static int cgltf_int_from_component_type(cgltf_component_type ctype) +{ + switch (ctype) + { + case cgltf_component_type_r_8: return 5120; + case cgltf_component_type_r_8u: return 5121; + case cgltf_component_type_r_16: return 5122; + case cgltf_component_type_r_16u: return 5123; + case cgltf_component_type_r_32u: return 5125; + case cgltf_component_type_r_32f: return 5126; + default: return 0; + } +} + +static const char* cgltf_str_from_alpha_mode(cgltf_alpha_mode alpha_mode) +{ + switch (alpha_mode) + { + case cgltf_alpha_mode_mask: return "MASK"; + case cgltf_alpha_mode_blend: return "BLEND"; + default: return NULL; + } +} + +static const char* cgltf_str_from_type(cgltf_type type) +{ + switch (type) + { + case cgltf_type_scalar: return "SCALAR"; + case cgltf_type_vec2: return "VEC2"; + case cgltf_type_vec3: return "VEC3"; + case cgltf_type_vec4: return "VEC4"; + case cgltf_type_mat2: return "MAT2"; + case cgltf_type_mat3: return "MAT3"; + case cgltf_type_mat4: return "MAT4"; + default: return NULL; + } +} + +static cgltf_size cgltf_dim_from_type(cgltf_type type) +{ + switch (type) + { + case cgltf_type_scalar: return 1; + case cgltf_type_vec2: return 2; + case cgltf_type_vec3: return 3; + case cgltf_type_vec4: return 4; + case cgltf_type_mat2: return 4; + case cgltf_type_mat3: return 9; + case cgltf_type_mat4: return 16; + default: return 0; + } +} + +static const char* cgltf_str_from_camera_type(cgltf_camera_type camera_type) +{ + switch (camera_type) + { + case cgltf_camera_type_perspective: return "perspective"; + case cgltf_camera_type_orthographic: return "orthographic"; + default: return NULL; + } +} + +static const char* cgltf_str_from_light_type(cgltf_light_type light_type) +{ + switch (light_type) + { + case cgltf_light_type_directional: return "directional"; + case cgltf_light_type_point: return "point"; + case cgltf_light_type_spot: return "spot"; + default: return NULL; + } +} + +static void cgltf_write_texture_transform(cgltf_write_context* context, const cgltf_texture_transform* transform) +{ + cgltf_write_line(context, "\"extensions\": {"); + cgltf_write_line(context, "\"KHR_texture_transform\": {"); + if (cgltf_check_floatarray(transform->offset, 2, 0.0f)) + { + cgltf_write_floatarrayprop(context, "offset", transform->offset, 2); + } + cgltf_write_floatprop(context, "rotation", transform->rotation, 0.0f); + if (cgltf_check_floatarray(transform->scale, 2, 1.0f)) + { + cgltf_write_floatarrayprop(context, "scale", transform->scale, 2); + } + cgltf_write_intprop(context, "texCoord", transform->texcoord, 0); + cgltf_write_line(context, "}"); + cgltf_write_line(context, "}"); +} + +static void cgltf_write_asset(cgltf_write_context* context, const cgltf_asset* asset) +{ + cgltf_write_line(context, "\"asset\": {"); + cgltf_write_strprop(context, "copyright", asset->copyright); + cgltf_write_strprop(context, "generator", asset->generator); + cgltf_write_strprop(context, "version", asset->version); + cgltf_write_strprop(context, "min_version", asset->min_version); + cgltf_write_extras(context, &asset->extras); + cgltf_write_line(context, "}"); +} + +static void cgltf_write_primitive(cgltf_write_context* context, const cgltf_primitive* prim) +{ + cgltf_write_intprop(context, "mode", (int) prim->type, 4); + CGLTF_WRITE_IDXPROP("indices", prim->indices, context->data->accessors); + CGLTF_WRITE_IDXPROP("material", prim->material, context->data->materials); + cgltf_write_line(context, "\"attributes\": {"); + for (cgltf_size i = 0; i < prim->attributes_count; ++i) + { + const cgltf_attribute* attr = prim->attributes + i; + CGLTF_WRITE_IDXPROP(attr->name, attr->data, context->data->accessors); + } + cgltf_write_line(context, "}"); + + if (prim->targets_count) + { + cgltf_write_line(context, "\"targets\": ["); + for (cgltf_size i = 0; i < prim->targets_count; ++i) + { + cgltf_write_line(context, "{"); + for (cgltf_size j = 0; j < prim->targets[i].attributes_count; ++j) + { + const cgltf_attribute* attr = prim->targets[i].attributes + j; + CGLTF_WRITE_IDXPROP(attr->name, attr->data, context->data->accessors); + } + cgltf_write_line(context, "}"); + } + cgltf_write_line(context, "]"); + } + cgltf_write_extras(context, &prim->extras); + + cgltf_bool has_extensions = prim->has_draco_mesh_compression; + if (has_extensions) { + cgltf_write_line(context, "\"extensions\": {"); + + if (prim->has_draco_mesh_compression) { + context->extension_flags |= CGLTF_EXTENSION_FLAG_DRACO_MESH_COMPRESSION; + if (prim->attributes_count == 0 || prim->indices == 0) { + context->required_extension_flags |= CGLTF_EXTENSION_FLAG_DRACO_MESH_COMPRESSION; + } + + cgltf_write_line(context, "\"KHR_draco_mesh_compression\": {"); + CGLTF_WRITE_IDXPROP("bufferView", prim->draco_mesh_compression.buffer_view, context->data->buffer_views); + cgltf_write_line(context, "\"attributes\": {"); + for (cgltf_size i = 0; i < prim->draco_mesh_compression.attributes_count; ++i) + { + const cgltf_attribute* attr = prim->draco_mesh_compression.attributes + i; + CGLTF_WRITE_IDXPROP(attr->name, attr->data, context->data->accessors); + } + cgltf_write_line(context, "}"); + cgltf_write_line(context, "}"); + } + + cgltf_write_line(context, "}"); + } +} + +static void cgltf_write_mesh(cgltf_write_context* context, const cgltf_mesh* mesh) +{ + cgltf_write_line(context, "{"); + cgltf_write_strprop(context, "name", mesh->name); + + cgltf_write_line(context, "\"primitives\": ["); + for (cgltf_size i = 0; i < mesh->primitives_count; ++i) + { + cgltf_write_line(context, "{"); + cgltf_write_primitive(context, mesh->primitives + i); + cgltf_write_line(context, "}"); + } + cgltf_write_line(context, "]"); + + if (mesh->weights_count > 0) + { + cgltf_write_floatarrayprop(context, "weights", mesh->weights, mesh->weights_count); + } + cgltf_write_extras(context, &mesh->extras); + cgltf_write_line(context, "}"); +} + +static void cgltf_write_buffer_view(cgltf_write_context* context, const cgltf_buffer_view* view) +{ + cgltf_write_line(context, "{"); + CGLTF_WRITE_IDXPROP("buffer", view->buffer, context->data->buffers); + cgltf_write_intprop(context, "byteLength", (int)view->size, -1); + cgltf_write_intprop(context, "byteOffset", (int)view->offset, 0); + cgltf_write_intprop(context, "byteStride", (int)view->stride, 0); + // NOTE: We skip writing "target" because the spec says its usage can be inferred. + cgltf_write_extras(context, &view->extras); + cgltf_write_line(context, "}"); +} + + +static void cgltf_write_buffer(cgltf_write_context* context, const cgltf_buffer* buffer) +{ + cgltf_write_line(context, "{"); + cgltf_write_strprop(context, "uri", buffer->uri); + cgltf_write_intprop(context, "byteLength", (int)buffer->size, -1); + cgltf_write_extras(context, &buffer->extras); + cgltf_write_line(context, "}"); +} + +static void cgltf_write_material(cgltf_write_context* context, const cgltf_material* material) +{ + cgltf_write_line(context, "{"); + cgltf_write_strprop(context, "name", material->name); + cgltf_write_floatprop(context, "alphaCutoff", material->alpha_cutoff, 0.5f); + cgltf_write_boolprop_optional(context, "doubleSided", material->double_sided, false); + // cgltf_write_boolprop_optional(context, "unlit", material->unlit, false); + + if (material->unlit) + { + context->extension_flags |= CGLTF_EXTENSION_FLAG_MATERIALS_UNLIT; + } + + if (material->has_pbr_specular_glossiness) + { + context->extension_flags |= CGLTF_EXTENSION_FLAG_SPECULAR_GLOSSINESS; + } + + if (material->has_clearcoat) + { + context->extension_flags |= CGLTF_EXTENSION_FLAG_MATERIALS_CLEARCOAT; + } + + if (material->has_transmission) + { + context->extension_flags |= CGLTF_EXTENSION_FLAG_MATERIALS_TRANSMISSION; + } + + if (material->has_ior) + { + context->extension_flags |= CGLTF_EXTENSION_FLAG_MATERIALS_IOR; + } + + if (material->has_specular) + { + context->extension_flags |= CGLTF_EXTENSION_FLAG_MATERIALS_SPECULAR; + } + + if (material->has_pbr_metallic_roughness) + { + const cgltf_pbr_metallic_roughness* params = &material->pbr_metallic_roughness; + cgltf_write_line(context, "\"pbrMetallicRoughness\": {"); + CGLTF_WRITE_TEXTURE_INFO("baseColorTexture", params->base_color_texture); + CGLTF_WRITE_TEXTURE_INFO("metallicRoughnessTexture", params->metallic_roughness_texture); + cgltf_write_floatprop(context, "metallicFactor", params->metallic_factor, 1.0f); + cgltf_write_floatprop(context, "roughnessFactor", params->roughness_factor, 1.0f); + if (cgltf_check_floatarray(params->base_color_factor, 4, 1.0f)) + { + cgltf_write_floatarrayprop(context, "baseColorFactor", params->base_color_factor, 4); + } + cgltf_write_extras(context, ¶ms->extras); + cgltf_write_line(context, "}"); + } + + if (material->unlit || material->has_pbr_specular_glossiness || material->has_clearcoat || material->has_ior || material->has_specular || material->has_transmission) + { + cgltf_write_line(context, "\"extensions\": {"); + if (material->has_clearcoat) + { + const cgltf_clearcoat* params = &material->clearcoat; + cgltf_write_line(context, "\"KHR_materials_clearcoat\": {"); + CGLTF_WRITE_TEXTURE_INFO("clearcoatTexture", params->clearcoat_texture); + CGLTF_WRITE_TEXTURE_INFO("clearcoatRoughnessTexture", params->clearcoat_roughness_texture); + CGLTF_WRITE_TEXTURE_INFO("clearcoatNormalTexture", params->clearcoat_normal_texture); + cgltf_write_floatprop(context, "clearcoatFactor", params->clearcoat_factor, 0.0f); + cgltf_write_floatprop(context, "clearcoatRoughnessFactor", params->clearcoat_roughness_factor, 0.0f); + cgltf_write_line(context, "}"); + } + if (material->has_ior) + { + const cgltf_ior* params = &material->ior; + cgltf_write_line(context, "\"KHR_materials_ior\": {"); + cgltf_write_floatprop(context, "ior", params->ior, 1.5f); + cgltf_write_line(context, "}"); + } + if (material->has_specular) + { + const cgltf_specular* params = &material->specular; + cgltf_write_line(context, "\"KHR_materials_specular\": {"); + CGLTF_WRITE_TEXTURE_INFO("specularTexture", params->specular_texture); + cgltf_write_floatprop(context, "specularFactor", params->specular_factor, 1.0f); + if (cgltf_check_floatarray(params->specular_color_factor, 3, 1.0f)) + { + cgltf_write_floatarrayprop(context, "specularColorFactor", params->specular_color_factor, 3); + } + cgltf_write_line(context, "}"); + } + if (material->has_transmission) + { + const cgltf_transmission* params = &material->transmission; + cgltf_write_line(context, "\"KHR_materials_transmission\": {"); + CGLTF_WRITE_TEXTURE_INFO("transmissionTexture", params->transmission_texture); + cgltf_write_floatprop(context, "transmissionFactor", params->transmission_factor, 0.0f); + cgltf_write_line(context, "}"); + } + if (material->has_pbr_specular_glossiness) + { + const cgltf_pbr_specular_glossiness* params = &material->pbr_specular_glossiness; + cgltf_write_line(context, "\"KHR_materials_pbrSpecularGlossiness\": {"); + CGLTF_WRITE_TEXTURE_INFO("diffuseTexture", params->diffuse_texture); + CGLTF_WRITE_TEXTURE_INFO("specularGlossinessTexture", params->specular_glossiness_texture); + if (cgltf_check_floatarray(params->diffuse_factor, 4, 1.0f)) + { + cgltf_write_floatarrayprop(context, "dffuseFactor", params->diffuse_factor, 4); + } + if (cgltf_check_floatarray(params->specular_factor, 3, 1.0f)) + { + cgltf_write_floatarrayprop(context, "specularFactor", params->specular_factor, 3); + } + cgltf_write_floatprop(context, "glossinessFactor", params->glossiness_factor, 1.0f); + cgltf_write_line(context, "}"); + } + if (material->unlit) + { + cgltf_write_line(context, "\"KHR_materials_unlit\": {}"); + } + cgltf_write_line(context, "}"); + } + + CGLTF_WRITE_TEXTURE_INFO("normalTexture", material->normal_texture); + CGLTF_WRITE_TEXTURE_INFO("occlusionTexture", material->occlusion_texture); + CGLTF_WRITE_TEXTURE_INFO("emissiveTexture", material->emissive_texture); + if (cgltf_check_floatarray(material->emissive_factor, 3, 0.0f)) + { + cgltf_write_floatarrayprop(context, "emissiveFactor", material->emissive_factor, 3); + } + cgltf_write_strprop(context, "alphaMode", cgltf_str_from_alpha_mode(material->alpha_mode)); + cgltf_write_extras(context, &material->extras); + cgltf_write_line(context, "}"); +} + +static void cgltf_write_image(cgltf_write_context* context, const cgltf_image* image) +{ + cgltf_write_line(context, "{"); + cgltf_write_strprop(context, "name", image->name); + cgltf_write_strprop(context, "uri", image->uri); + CGLTF_WRITE_IDXPROP("bufferView", image->buffer_view, context->data->buffer_views); + cgltf_write_strprop(context, "mimeType", image->mime_type); + cgltf_write_extras(context, &image->extras); + cgltf_write_line(context, "}"); +} + +static void cgltf_write_texture(cgltf_write_context* context, const cgltf_texture* texture) +{ + cgltf_write_line(context, "{"); + cgltf_write_strprop(context, "name", texture->name); + CGLTF_WRITE_IDXPROP("source", texture->image, context->data->images); + CGLTF_WRITE_IDXPROP("sampler", texture->sampler, context->data->samplers); + cgltf_write_extras(context, &texture->extras); + cgltf_write_line(context, "}"); +} + +static void cgltf_write_skin(cgltf_write_context* context, const cgltf_skin* skin) +{ + cgltf_write_line(context, "{"); + CGLTF_WRITE_IDXPROP("skeleton", skin->skeleton, context->data->nodes); + CGLTF_WRITE_IDXPROP("inverseBindMatrices", skin->inverse_bind_matrices, context->data->accessors); + CGLTF_WRITE_IDXARRPROP("joints", skin->joints_count, skin->joints, context->data->nodes); + cgltf_write_strprop(context, "name", skin->name); + cgltf_write_extras(context, &skin->extras); + cgltf_write_line(context, "}"); +} + +static const char* cgltf_write_str_path_type(cgltf_animation_path_type path_type) +{ + switch (path_type) + { + case cgltf_animation_path_type_translation: + return "translation"; + case cgltf_animation_path_type_rotation: + return "rotation"; + case cgltf_animation_path_type_scale: + return "scale"; + case cgltf_animation_path_type_weights: + return "weights"; + case cgltf_animation_path_type_invalid: + break; + } + return "invalid"; +} + +static const char* cgltf_write_str_interpolation_type(cgltf_interpolation_type interpolation_type) +{ + switch (interpolation_type) + { + case cgltf_interpolation_type_linear: + return "LINEAR"; + case cgltf_interpolation_type_step: + return "STEP"; + case cgltf_interpolation_type_cubic_spline: + return "CUBICSPLINE"; + } + return "invalid"; +} + +static void cgltf_write_path_type(cgltf_write_context* context, const char *label, cgltf_animation_path_type path_type) +{ + cgltf_write_strprop(context, label, cgltf_write_str_path_type(path_type)); +} + +static void cgltf_write_interpolation_type(cgltf_write_context* context, const char *label, cgltf_interpolation_type interpolation_type) +{ + cgltf_write_strprop(context, label, cgltf_write_str_interpolation_type(interpolation_type)); +} + +static void cgltf_write_animation_sampler(cgltf_write_context* context, const cgltf_animation_sampler* animation_sampler) +{ + cgltf_write_line(context, "{"); + cgltf_write_interpolation_type(context, "interpolation", animation_sampler->interpolation); + CGLTF_WRITE_IDXPROP("input", animation_sampler->input, context->data->accessors); + CGLTF_WRITE_IDXPROP("output", animation_sampler->output, context->data->accessors); + cgltf_write_extras(context, &animation_sampler->extras); + cgltf_write_line(context, "}"); +} + +static void cgltf_write_animation_channel(cgltf_write_context* context, const cgltf_animation* animation, const cgltf_animation_channel* animation_channel) +{ + cgltf_write_line(context, "{"); + CGLTF_WRITE_IDXPROP("sampler", animation_channel->sampler, animation->samplers); + cgltf_write_line(context, "\"target\": {"); + CGLTF_WRITE_IDXPROP("node", animation_channel->target_node, context->data->nodes); + cgltf_write_path_type(context, "path", animation_channel->target_path); + cgltf_write_line(context, "}"); + cgltf_write_extras(context, &animation_channel->extras); + cgltf_write_line(context, "}"); +} + +static void cgltf_write_animation(cgltf_write_context* context, const cgltf_animation* animation) +{ + cgltf_write_line(context, "{"); + cgltf_write_strprop(context, "name", animation->name); + + if (animation->samplers_count > 0) + { + cgltf_write_line(context, "\"samplers\": ["); + for (cgltf_size i = 0; i < animation->samplers_count; ++i) + { + cgltf_write_animation_sampler(context, animation->samplers + i); + } + cgltf_write_line(context, "]"); + } + if (animation->channels_count > 0) + { + cgltf_write_line(context, "\"channels\": ["); + for (cgltf_size i = 0; i < animation->channels_count; ++i) + { + cgltf_write_animation_channel(context, animation, animation->channels + i); + } + cgltf_write_line(context, "]"); + } + cgltf_write_extras(context, &animation->extras); + cgltf_write_line(context, "}"); +} + +static void cgltf_write_sampler(cgltf_write_context* context, const cgltf_sampler* sampler) +{ + cgltf_write_line(context, "{"); + cgltf_write_intprop(context, "magFilter", sampler->mag_filter, 0); + cgltf_write_intprop(context, "minFilter", sampler->min_filter, 0); + cgltf_write_intprop(context, "wrapS", sampler->wrap_s, 10497); + cgltf_write_intprop(context, "wrapT", sampler->wrap_t, 10497); + cgltf_write_extras(context, &sampler->extras); + cgltf_write_line(context, "}"); +} + +static void cgltf_write_node(cgltf_write_context* context, const cgltf_node* node) +{ + cgltf_write_line(context, "{"); + CGLTF_WRITE_IDXARRPROP("children", node->children_count, node->children, context->data->nodes); + CGLTF_WRITE_IDXPROP("mesh", node->mesh, context->data->meshes); + cgltf_write_strprop(context, "name", node->name); + if (node->has_matrix) + { + cgltf_write_floatarrayprop(context, "matrix", node->matrix, 16); + } + if (node->has_translation) + { + cgltf_write_floatarrayprop(context, "translation", node->translation, 3); + } + if (node->has_rotation) + { + cgltf_write_floatarrayprop(context, "rotation", node->rotation, 4); + } + if (node->has_scale) + { + cgltf_write_floatarrayprop(context, "scale", node->scale, 3); + } + if (node->skin) + { + CGLTF_WRITE_IDXPROP("skin", node->skin, context->data->skins); + } + + if (node->light) + { + context->extension_flags |= CGLTF_EXTENSION_FLAG_LIGHTS_PUNCTUAL; + cgltf_write_line(context, "\"extensions\": {"); + cgltf_write_line(context, "\"KHR_lights_punctual\": {"); + CGLTF_WRITE_IDXPROP("light", node->light, context->data->lights); + cgltf_write_line(context, "}"); + cgltf_write_line(context, "}"); + } + + if (node->weights_count > 0) + { + cgltf_write_floatarrayprop(context, "weights", node->weights, node->weights_count); + } + + if (node->camera) + { + CGLTF_WRITE_IDXPROP("camera", node->camera, context->data->cameras); + } + + cgltf_write_extras(context, &node->extras); + cgltf_write_line(context, "}"); +} + +static void cgltf_write_scene(cgltf_write_context* context, const cgltf_scene* scene) +{ + cgltf_write_line(context, "{"); + cgltf_write_strprop(context, "name", scene->name); + CGLTF_WRITE_IDXARRPROP("nodes", scene->nodes_count, scene->nodes, context->data->nodes); + cgltf_write_extras(context, &scene->extras); + cgltf_write_line(context, "}"); +} + +static void cgltf_write_accessor(cgltf_write_context* context, const cgltf_accessor* accessor) +{ + cgltf_write_line(context, "{"); + CGLTF_WRITE_IDXPROP("bufferView", accessor->buffer_view, context->data->buffer_views); + cgltf_write_intprop(context, "componentType", cgltf_int_from_component_type(accessor->component_type), 0); + cgltf_write_strprop(context, "type", cgltf_str_from_type(accessor->type)); + cgltf_size dim = cgltf_dim_from_type(accessor->type); + cgltf_write_boolprop_optional(context, "normalized", accessor->normalized, false); + cgltf_write_intprop(context, "byteOffset", (int)accessor->offset, 0); + cgltf_write_intprop(context, "count", (int)accessor->count, -1); + if (accessor->has_min) + { + cgltf_write_floatarrayprop(context, "min", accessor->min, dim); + } + if (accessor->has_max) + { + cgltf_write_floatarrayprop(context, "max", accessor->max, dim); + } + if (accessor->is_sparse) + { + cgltf_write_line(context, "\"sparse\": {"); + cgltf_write_intprop(context, "count", (int)accessor->sparse.count, 0); + cgltf_write_line(context, "\"indices\": {"); + cgltf_write_intprop(context, "byteOffset", (int)accessor->sparse.indices_byte_offset, 0); + CGLTF_WRITE_IDXPROP("bufferView", accessor->sparse.indices_buffer_view, context->data->buffer_views); + cgltf_write_intprop(context, "componentType", cgltf_int_from_component_type(accessor->sparse.indices_component_type), 0); + cgltf_write_extras(context, &accessor->sparse.indices_extras); + cgltf_write_line(context, "}"); + cgltf_write_line(context, "\"values\": {"); + cgltf_write_intprop(context, "byteOffset", (int)accessor->sparse.values_byte_offset, 0); + CGLTF_WRITE_IDXPROP("bufferView", accessor->sparse.values_buffer_view, context->data->buffer_views); + cgltf_write_extras(context, &accessor->sparse.values_extras); + cgltf_write_line(context, "}"); + cgltf_write_extras(context, &accessor->sparse.extras); + cgltf_write_line(context, "}"); + } + cgltf_write_extras(context, &accessor->extras); + cgltf_write_line(context, "}"); +} + +static void cgltf_write_camera(cgltf_write_context* context, const cgltf_camera* camera) +{ + cgltf_write_line(context, "{"); + cgltf_write_strprop(context, "type", cgltf_str_from_camera_type(camera->type)); + if (camera->name) + { + cgltf_write_strprop(context, "name", camera->name); + } + + if (camera->type == cgltf_camera_type_orthographic) + { + cgltf_write_line(context, "\"orthographic\": {"); + cgltf_write_floatprop(context, "xmag", camera->data.orthographic.xmag, -1.0f); + cgltf_write_floatprop(context, "ymag", camera->data.orthographic.ymag, -1.0f); + cgltf_write_floatprop(context, "zfar", camera->data.orthographic.zfar, -1.0f); + cgltf_write_floatprop(context, "znear", camera->data.orthographic.znear, -1.0f); + cgltf_write_extras(context, &camera->data.orthographic.extras); + cgltf_write_line(context, "}"); + } + else if (camera->type == cgltf_camera_type_perspective) + { + cgltf_write_line(context, "\"perspective\": {"); + cgltf_write_floatprop(context, "aspectRatio", camera->data.perspective.aspect_ratio, -1.0f); + cgltf_write_floatprop(context, "yfov", camera->data.perspective.yfov, -1.0f); + cgltf_write_floatprop(context, "zfar", camera->data.perspective.zfar, -1.0f); + cgltf_write_floatprop(context, "znear", camera->data.perspective.znear, -1.0f); + cgltf_write_extras(context, &camera->data.perspective.extras); + cgltf_write_line(context, "}"); + } + cgltf_write_extras(context, &camera->extras); + cgltf_write_line(context, "}"); +} + +static void cgltf_write_light(cgltf_write_context* context, const cgltf_light* light) +{ + cgltf_write_line(context, "{"); + cgltf_write_strprop(context, "type", cgltf_str_from_light_type(light->type)); + if (light->name) + { + cgltf_write_strprop(context, "name", light->name); + } + if (cgltf_check_floatarray(light->color, 3, 1.0f)) + { + cgltf_write_floatarrayprop(context, "color", light->color, 3); + } + cgltf_write_floatprop(context, "intensity", light->intensity, 1.0f); + cgltf_write_floatprop(context, "range", light->range, 0.0f); + + if (light->type == cgltf_light_type_spot) + { + cgltf_write_line(context, "\"spot\": {"); + cgltf_write_floatprop(context, "innerConeAngle", light->spot_inner_cone_angle, 0.0f); + cgltf_write_floatprop(context, "outerConeAngle", light->spot_outer_cone_angle, 3.14159265358979323846f/4.0f); + cgltf_write_line(context, "}"); + } + cgltf_write_line(context, "}"); +} + +cgltf_result cgltf_write_file(const cgltf_options* options, const char* path, const cgltf_data* data) +{ + cgltf_size expected = cgltf_write(options, NULL, 0, data); + char* buffer = (char*) malloc(expected); + cgltf_size actual = cgltf_write(options, buffer, expected, data); + if (expected != actual) { + fprintf(stderr, "Error: expected %zu bytes but wrote %zu bytes.\n", expected, actual); + } + FILE* file = fopen(path, "wt"); + if (!file) + { + return cgltf_result_file_not_found; + } + // Note that cgltf_write() includes a null terminator, which we omit from the file content. + fwrite(buffer, actual - 1, 1, file); + fclose(file); + free(buffer); + return cgltf_result_success; +} + +static void cgltf_write_extensions(cgltf_write_context* context, uint32_t extension_flags) +{ + if (extension_flags & CGLTF_EXTENSION_FLAG_TEXTURE_TRANSFORM) { + cgltf_write_stritem(context, "KHR_texture_transform"); + } + if (extension_flags & CGLTF_EXTENSION_FLAG_MATERIALS_UNLIT) { + cgltf_write_stritem(context, "KHR_materials_unlit"); + } + if (extension_flags & CGLTF_EXTENSION_FLAG_SPECULAR_GLOSSINESS) { + cgltf_write_stritem(context, "KHR_materials_pbrSpecularGlossiness"); + } + if (extension_flags & CGLTF_EXTENSION_FLAG_LIGHTS_PUNCTUAL) { + cgltf_write_stritem(context, "KHR_lights_punctual"); + } + if (extension_flags & CGLTF_EXTENSION_FLAG_DRACO_MESH_COMPRESSION) { + cgltf_write_stritem(context, "KHR_draco_mesh_compression"); + } + if (extension_flags & CGLTF_EXTENSION_FLAG_MATERIALS_CLEARCOAT) { + cgltf_write_stritem(context, "KHR_materials_clearcoat"); + } + if (extension_flags & CGLTF_EXTENSION_FLAG_MATERIALS_IOR) { + cgltf_write_stritem(context, "KHR_materials_ior"); + } + if (extension_flags & CGLTF_EXTENSION_FLAG_MATERIALS_SPECULAR) { + cgltf_write_stritem(context, "KHR_materials_specular"); + } + if (extension_flags & CGLTF_EXTENSION_FLAG_MATERIALS_TRANSMISSION) { + cgltf_write_stritem(context, "KHR_materials_transmission"); + } +} + +cgltf_size cgltf_write(const cgltf_options* options, char* buffer, cgltf_size size, const cgltf_data* data) +{ + (void)options; + cgltf_write_context ctx; + ctx.buffer = buffer; + ctx.buffer_size = size; + ctx.remaining = size; + ctx.cursor = buffer; + ctx.chars_written = 0; + ctx.data = data; + ctx.depth = 1; + ctx.indent = " "; + ctx.needs_comma = 0; + ctx.extension_flags = 0; + ctx.required_extension_flags = 0; + + cgltf_write_context* context = &ctx; + + CGLTF_SPRINTF("{"); + + if (data->accessors_count > 0) + { + cgltf_write_line(context, "\"accessors\": ["); + for (cgltf_size i = 0; i < data->accessors_count; ++i) + { + cgltf_write_accessor(context, data->accessors + i); + } + cgltf_write_line(context, "]"); + } + + cgltf_write_asset(context, &data->asset); + + if (data->buffer_views_count > 0) + { + cgltf_write_line(context, "\"bufferViews\": ["); + for (cgltf_size i = 0; i < data->buffer_views_count; ++i) + { + cgltf_write_buffer_view(context, data->buffer_views + i); + } + cgltf_write_line(context, "]"); + } + + if (data->buffers_count > 0) + { + cgltf_write_line(context, "\"buffers\": ["); + for (cgltf_size i = 0; i < data->buffers_count; ++i) + { + cgltf_write_buffer(context, data->buffers + i); + } + cgltf_write_line(context, "]"); + } + + if (data->images_count > 0) + { + cgltf_write_line(context, "\"images\": ["); + for (cgltf_size i = 0; i < data->images_count; ++i) + { + cgltf_write_image(context, data->images + i); + } + cgltf_write_line(context, "]"); + } + + if (data->meshes_count > 0) + { + cgltf_write_line(context, "\"meshes\": ["); + for (cgltf_size i = 0; i < data->meshes_count; ++i) + { + cgltf_write_mesh(context, data->meshes + i); + } + cgltf_write_line(context, "]"); + } + + if (data->materials_count > 0) + { + cgltf_write_line(context, "\"materials\": ["); + for (cgltf_size i = 0; i < data->materials_count; ++i) + { + cgltf_write_material(context, data->materials + i); + } + cgltf_write_line(context, "]"); + } + + if (data->nodes_count > 0) + { + cgltf_write_line(context, "\"nodes\": ["); + for (cgltf_size i = 0; i < data->nodes_count; ++i) + { + cgltf_write_node(context, data->nodes + i); + } + cgltf_write_line(context, "]"); + } + + if (data->samplers_count > 0) + { + cgltf_write_line(context, "\"samplers\": ["); + for (cgltf_size i = 0; i < data->samplers_count; ++i) + { + cgltf_write_sampler(context, data->samplers + i); + } + cgltf_write_line(context, "]"); + } + + CGLTF_WRITE_IDXPROP("scene", data->scene, data->scenes); + + if (data->scenes_count > 0) + { + cgltf_write_line(context, "\"scenes\": ["); + for (cgltf_size i = 0; i < data->scenes_count; ++i) + { + cgltf_write_scene(context, data->scenes + i); + } + cgltf_write_line(context, "]"); + } + + if (data->textures_count > 0) + { + cgltf_write_line(context, "\"textures\": ["); + for (cgltf_size i = 0; i < data->textures_count; ++i) + { + cgltf_write_texture(context, data->textures + i); + } + cgltf_write_line(context, "]"); + } + + if (data->skins_count > 0) + { + cgltf_write_line(context, "\"skins\": ["); + for (cgltf_size i = 0; i < data->skins_count; ++i) + { + cgltf_write_skin(context, data->skins + i); + } + cgltf_write_line(context, "]"); + } + + if (data->animations_count > 0) + { + cgltf_write_line(context, "\"animations\": ["); + for (cgltf_size i = 0; i < data->animations_count; ++i) + { + cgltf_write_animation(context, data->animations + i); + } + cgltf_write_line(context, "]"); + } + + if (data->cameras_count > 0) + { + cgltf_write_line(context, "\"cameras\": ["); + for (cgltf_size i = 0; i < data->cameras_count; ++i) + { + cgltf_write_camera(context, data->cameras + i); + } + cgltf_write_line(context, "]"); + } + + if (data->lights_count > 0) + { + cgltf_write_line(context, "\"extensions\": {"); + + cgltf_write_line(context, "\"KHR_lights_punctual\": {"); + cgltf_write_line(context, "\"lights\": ["); + for (cgltf_size i = 0; i < data->lights_count; ++i) + { + cgltf_write_light(context, data->lights + i); + } + cgltf_write_line(context, "]"); + cgltf_write_line(context, "}"); + + cgltf_write_line(context, "}"); + } + + if (context->extension_flags != 0) { + cgltf_write_line(context, "\"extensionsUsed\": ["); + cgltf_write_extensions(context, context->extension_flags); + cgltf_write_line(context, "]"); + } + + if (context->required_extension_flags != 0) { + cgltf_write_line(context, "\"extensionsRequired\": ["); + cgltf_write_extensions(context, context->required_extension_flags); + cgltf_write_line(context, "]"); + } + + cgltf_write_extras(context, &data->extras); + + CGLTF_SPRINTF("\n}\n"); + + // snprintf does not include the null terminator in its return value, so be sure to include it + // in the returned byte count. + return 1 + ctx.chars_written; +} + +#endif /* #ifdef CGLTF_WRITE_IMPLEMENTATION */ + +/* cgltf is distributed under MIT license: + * + * Copyright (c) 2019 Philip Rideout + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ diff --git a/contrib/stb/CMakeLists.txt b/contrib/stb/CMakeLists.txt new file mode 100644 index 0000000..8cee003 --- /dev/null +++ b/contrib/stb/CMakeLists.txt @@ -0,0 +1,8 @@ +cmake_minimum_required(VERSION 3.16) + +project(stb) + +add_library(stb INTERFACE) + +target_include_directories(stb INTERFACE + ${CMAKE_CURRENT_SOURCE_DIR}) diff --git a/contrib/stb/stb_image.h b/contrib/stb/stb_image.h new file mode 100644 index 0000000..97038e6 --- /dev/null +++ b/contrib/stb/stb_image.h @@ -0,0 +1,7762 @@ +/* stb_image - v2.26 - public domain image loader - http://nothings.org/stb + no warranty implied; use at your own risk + + Do this: + #define STB_IMAGE_IMPLEMENTATION + before you include this file in *one* C or C++ file to create the implementation. + + // i.e. it should look like this: + #include ... + #include ... + #include ... + #define STB_IMAGE_IMPLEMENTATION + #include "stb_image.h" + + You can #define STBI_ASSERT(x) before the #include to avoid using assert.h. + And #define STBI_MALLOC, STBI_REALLOC, and STBI_FREE to avoid using malloc,realloc,free + + + QUICK NOTES: + Primarily of interest to game developers and other people who can + avoid problematic images and only need the trivial interface + + JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib) + PNG 1/2/4/8/16-bit-per-channel + + TGA (not sure what subset, if a subset) + BMP non-1bpp, non-RLE + PSD (composited view only, no extra channels, 8/16 bit-per-channel) + + GIF (*comp always reports as 4-channel) + HDR (radiance rgbE format) + PIC (Softimage PIC) + PNM (PPM and PGM binary only) + + Animated GIF still needs a proper API, but here's one way to do it: + http://gist.github.com/urraka/685d9a6340b26b830d49 + + - decode from memory or through FILE (define STBI_NO_STDIO to remove code) + - decode from arbitrary I/O callbacks + - SIMD acceleration on x86/x64 (SSE2) and ARM (NEON) + + Full documentation under "DOCUMENTATION" below. + + +LICENSE + + See end of file for license information. + +RECENT REVISION HISTORY: + + 2.26 (2020-07-13) many minor fixes + 2.25 (2020-02-02) fix warnings + 2.24 (2020-02-02) fix warnings; thread-local failure_reason and flip_vertically + 2.23 (2019-08-11) fix clang static analysis warning + 2.22 (2019-03-04) gif fixes, fix warnings + 2.21 (2019-02-25) fix typo in comment + 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs + 2.19 (2018-02-11) fix warning + 2.18 (2018-01-30) fix warnings + 2.17 (2018-01-29) bugfix, 1-bit BMP, 16-bitness query, fix warnings + 2.16 (2017-07-23) all functions have 16-bit variants; optimizations; bugfixes + 2.15 (2017-03-18) fix png-1,2,4; all Imagenet JPGs; no runtime SSE detection on GCC + 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs + 2.13 (2016-12-04) experimental 16-bit API, only for PNG so far; fixes + 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes + 2.11 (2016-04-02) 16-bit PNGS; enable SSE2 in non-gcc x64 + RGB-format JPEG; remove white matting in PSD; + allocate large structures on the stack; + correct channel count for PNG & BMP + 2.10 (2016-01-22) avoid warning introduced in 2.09 + 2.09 (2016-01-16) 16-bit TGA; comments in PNM files; STBI_REALLOC_SIZED + + See end of file for full revision history. + + + ============================ Contributors ========================= + + Image formats Extensions, features + Sean Barrett (jpeg, png, bmp) Jetro Lauha (stbi_info) + Nicolas Schulz (hdr, psd) Martin "SpartanJ" Golini (stbi_info) + Jonathan Dummer (tga) James "moose2000" Brown (iPhone PNG) + Jean-Marc Lienher (gif) Ben "Disch" Wenger (io callbacks) + Tom Seddon (pic) Omar Cornut (1/2/4-bit PNG) + Thatcher Ulrich (psd) Nicolas Guillemot (vertical flip) + Ken Miller (pgm, ppm) Richard Mitton (16-bit PSD) + github:urraka (animated gif) Junggon Kim (PNM comments) + Christopher Forseth (animated gif) Daniel Gibson (16-bit TGA) + socks-the-fox (16-bit PNG) + Jeremy Sawicki (handle all ImageNet JPGs) + Optimizations & bugfixes Mikhail Morozov (1-bit BMP) + Fabian "ryg" Giesen Anael Seghezzi (is-16-bit query) + Arseny Kapoulkine + John-Mark Allen + Carmelo J Fdez-Aguera + + Bug & warning fixes + Marc LeBlanc David Woo Guillaume George Martins Mozeiko + Christpher Lloyd Jerry Jansson Joseph Thomson Blazej Dariusz Roszkowski + Phil Jordan Dave Moore Roy Eltham + Hayaki Saito Nathan Reed Won Chun + Luke Graham Johan Duparc Nick Verigakis the Horde3D community + Thomas Ruf Ronny Chevalier github:rlyeh + Janez Zemva John Bartholomew Michal Cichon github:romigrou + Jonathan Blow Ken Hamada Tero Hanninen github:svdijk + Laurent Gomila Cort Stratton github:snagar + Aruelien Pocheville Sergio Gonzalez Thibault Reuille github:Zelex + Cass Everitt Ryamond Barbiero github:grim210 + Paul Du Bois Engin Manap Aldo Culquicondor github:sammyhw + Philipp Wiesemann Dale Weiler Oriol Ferrer Mesia github:phprus + Josh Tobin Matthew Gregan github:poppolopoppo + Julian Raschke Gregory Mullen Christian Floisand github:darealshinji + Baldur Karlsson Kevin Schmidt JR Smith github:Michaelangel007 + Brad Weinberger Matvey Cherevko [reserved] + Luca Sas Alexander Veselov Zack Middleton [reserved] + Ryan C. Gordon [reserved] [reserved] + DO NOT ADD YOUR NAME HERE + + To add your name to the credits, pick a random blank space in the middle and fill it. + 80% of merge conflicts on stb PRs are due to people adding their name at the end + of the credits. +*/ + +#ifndef STBI_INCLUDE_STB_IMAGE_H +#define STBI_INCLUDE_STB_IMAGE_H + +// DOCUMENTATION +// +// Limitations: +// - no 12-bit-per-channel JPEG +// - no JPEGs with arithmetic coding +// - GIF always returns *comp=4 +// +// Basic usage (see HDR discussion below for HDR usage): +// int x,y,n; +// unsigned char *data = stbi_load(filename, &x, &y, &n, 0); +// // ... process data if not NULL ... +// // ... x = width, y = height, n = # 8-bit components per pixel ... +// // ... replace '0' with '1'..'4' to force that many components per pixel +// // ... but 'n' will always be the number that it would have been if you said 0 +// stbi_image_free(data) +// +// Standard parameters: +// int *x -- outputs image width in pixels +// int *y -- outputs image height in pixels +// int *channels_in_file -- outputs # of image components in image file +// int desired_channels -- if non-zero, # of image components requested in result +// +// The return value from an image loader is an 'unsigned char *' which points +// to the pixel data, or NULL on an allocation failure or if the image is +// corrupt or invalid. The pixel data consists of *y scanlines of *x pixels, +// with each pixel consisting of N interleaved 8-bit components; the first +// pixel pointed to is top-left-most in the image. There is no padding between +// image scanlines or between pixels, regardless of format. The number of +// components N is 'desired_channels' if desired_channels is non-zero, or +// *channels_in_file otherwise. If desired_channels is non-zero, +// *channels_in_file has the number of components that _would_ have been +// output otherwise. E.g. if you set desired_channels to 4, you will always +// get RGBA output, but you can check *channels_in_file to see if it's trivially +// opaque because e.g. there were only 3 channels in the source image. +// +// An output image with N components has the following components interleaved +// in this order in each pixel: +// +// N=#comp components +// 1 grey +// 2 grey, alpha +// 3 red, green, blue +// 4 red, green, blue, alpha +// +// If image loading fails for any reason, the return value will be NULL, +// and *x, *y, *channels_in_file will be unchanged. The function +// stbi_failure_reason() can be queried for an extremely brief, end-user +// unfriendly explanation of why the load failed. Define STBI_NO_FAILURE_STRINGS +// to avoid compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly +// more user-friendly ones. +// +// Paletted PNG, BMP, GIF, and PIC images are automatically depalettized. +// +// =========================================================================== +// +// UNICODE: +// +// If compiling for Windows and you wish to use Unicode filenames, compile +// with +// #define STBI_WINDOWS_UTF8 +// and pass utf8-encoded filenames. Call stbi_convert_wchar_to_utf8 to convert +// Windows wchar_t filenames to utf8. +// +// =========================================================================== +// +// Philosophy +// +// stb libraries are designed with the following priorities: +// +// 1. easy to use +// 2. easy to maintain +// 3. good performance +// +// Sometimes I let "good performance" creep up in priority over "easy to maintain", +// and for best performance I may provide less-easy-to-use APIs that give higher +// performance, in addition to the easy-to-use ones. Nevertheless, it's important +// to keep in mind that from the standpoint of you, a client of this library, +// all you care about is #1 and #3, and stb libraries DO NOT emphasize #3 above all. +// +// Some secondary priorities arise directly from the first two, some of which +// provide more explicit reasons why performance can't be emphasized. +// +// - Portable ("ease of use") +// - Small source code footprint ("easy to maintain") +// - No dependencies ("ease of use") +// +// =========================================================================== +// +// I/O callbacks +// +// I/O callbacks allow you to read from arbitrary sources, like packaged +// files or some other source. Data read from callbacks are processed +// through a small internal buffer (currently 128 bytes) to try to reduce +// overhead. +// +// The three functions you must define are "read" (reads some bytes of data), +// "skip" (skips some bytes of data), "eof" (reports if the stream is at the end). +// +// =========================================================================== +// +// SIMD support +// +// The JPEG decoder will try to automatically use SIMD kernels on x86 when +// supported by the compiler. For ARM Neon support, you must explicitly +// request it. +// +// (The old do-it-yourself SIMD API is no longer supported in the current +// code.) +// +// On x86, SSE2 will automatically be used when available based on a run-time +// test; if not, the generic C versions are used as a fall-back. On ARM targets, +// the typical path is to have separate builds for NEON and non-NEON devices +// (at least this is true for iOS and Android). Therefore, the NEON support is +// toggled by a build flag: define STBI_NEON to get NEON loops. +// +// If for some reason you do not want to use any of SIMD code, or if +// you have issues compiling it, you can disable it entirely by +// defining STBI_NO_SIMD. +// +// =========================================================================== +// +// HDR image support (disable by defining STBI_NO_HDR) +// +// stb_image supports loading HDR images in general, and currently the Radiance +// .HDR file format specifically. You can still load any file through the existing +// interface; if you attempt to load an HDR file, it will be automatically remapped +// to LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1; +// both of these constants can be reconfigured through this interface: +// +// stbi_hdr_to_ldr_gamma(2.2f); +// stbi_hdr_to_ldr_scale(1.0f); +// +// (note, do not use _inverse_ constants; stbi_image will invert them +// appropriately). +// +// Additionally, there is a new, parallel interface for loading files as +// (linear) floats to preserve the full dynamic range: +// +// float *data = stbi_loadf(filename, &x, &y, &n, 0); +// +// If you load LDR images through this interface, those images will +// be promoted to floating point values, run through the inverse of +// constants corresponding to the above: +// +// stbi_ldr_to_hdr_scale(1.0f); +// stbi_ldr_to_hdr_gamma(2.2f); +// +// Finally, given a filename (or an open file or memory block--see header +// file for details) containing image data, you can query for the "most +// appropriate" interface to use (that is, whether the image is HDR or +// not), using: +// +// stbi_is_hdr(char *filename); +// +// =========================================================================== +// +// iPhone PNG support: +// +// By default we convert iphone-formatted PNGs back to RGB, even though +// they are internally encoded differently. You can disable this conversion +// by calling stbi_convert_iphone_png_to_rgb(0), in which case +// you will always just get the native iphone "format" through (which +// is BGR stored in RGB). +// +// Call stbi_set_unpremultiply_on_load(1) as well to force a divide per +// pixel to remove any premultiplied alpha *only* if the image file explicitly +// says there's premultiplied data (currently only happens in iPhone images, +// and only if iPhone convert-to-rgb processing is on). +// +// =========================================================================== +// +// ADDITIONAL CONFIGURATION +// +// - You can suppress implementation of any of the decoders to reduce +// your code footprint by #defining one or more of the following +// symbols before creating the implementation. +// +// STBI_NO_JPEG +// STBI_NO_PNG +// STBI_NO_BMP +// STBI_NO_PSD +// STBI_NO_TGA +// STBI_NO_GIF +// STBI_NO_HDR +// STBI_NO_PIC +// STBI_NO_PNM (.ppm and .pgm) +// +// - You can request *only* certain decoders and suppress all other ones +// (this will be more forward-compatible, as addition of new decoders +// doesn't require you to disable them explicitly): +// +// STBI_ONLY_JPEG +// STBI_ONLY_PNG +// STBI_ONLY_BMP +// STBI_ONLY_PSD +// STBI_ONLY_TGA +// STBI_ONLY_GIF +// STBI_ONLY_HDR +// STBI_ONLY_PIC +// STBI_ONLY_PNM (.ppm and .pgm) +// +// - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still +// want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB +// +// - If you define STBI_MAX_DIMENSIONS, stb_image will reject images greater +// than that size (in either width or height) without further processing. +// This is to let programs in the wild set an upper bound to prevent +// denial-of-service attacks on untrusted data, as one could generate a +// valid image of gigantic dimensions and force stb_image to allocate a +// huge block of memory and spend disproportionate time decoding it. By +// default this is set to (1 << 24), which is 16777216, but that's still +// very big. + +#ifndef STBI_NO_STDIO +#include +#endif // STBI_NO_STDIO + +#define STBI_VERSION 1 + +enum +{ + STBI_default = 0, // only used for desired_channels + + STBI_grey = 1, + STBI_grey_alpha = 2, + STBI_rgb = 3, + STBI_rgb_alpha = 4 +}; + +#include +typedef unsigned char stbi_uc; +typedef unsigned short stbi_us; + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef STBIDEF +#ifdef STB_IMAGE_STATIC +#define STBIDEF static +#else +#define STBIDEF extern +#endif +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// PRIMARY API - works on images of any type +// + +// +// load image by filename, open file, or memory buffer +// + +typedef struct +{ + int (*read) (void *user,char *data,int size); // fill 'data' with 'size' bytes. return number of bytes actually read + void (*skip) (void *user,int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative + int (*eof) (void *user); // returns nonzero if we are at end of file/data +} stbi_io_callbacks; + +//////////////////////////////////// +// +// 8-bits-per-channel interface +// + +STBIDEF stbi_uc *stbi_load_from_memory (stbi_uc const *buffer, int len , int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk , void *user, int *x, int *y, int *channels_in_file, int desired_channels); + +#ifndef STBI_NO_STDIO +STBIDEF stbi_uc *stbi_load (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); +// for stbi_load_from_file, file pointer is left pointing immediately after image +#endif + +#ifndef STBI_NO_GIF +STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp); +#endif + +#ifdef STBI_WINDOWS_UTF8 +STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input); +#endif + +//////////////////////////////////// +// +// 16-bits-per-channel interface +// + +STBIDEF stbi_us *stbi_load_16_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); + +#ifndef STBI_NO_STDIO +STBIDEF stbi_us *stbi_load_16 (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_us *stbi_load_from_file_16(FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); +#endif + +//////////////////////////////////// +// +// float-per-channel interface +// +#ifndef STBI_NO_LINEAR + STBIDEF float *stbi_loadf_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); + STBIDEF float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); + + #ifndef STBI_NO_STDIO + STBIDEF float *stbi_loadf (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); + STBIDEF float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); + #endif +#endif + +#ifndef STBI_NO_HDR + STBIDEF void stbi_hdr_to_ldr_gamma(float gamma); + STBIDEF void stbi_hdr_to_ldr_scale(float scale); +#endif // STBI_NO_HDR + +#ifndef STBI_NO_LINEAR + STBIDEF void stbi_ldr_to_hdr_gamma(float gamma); + STBIDEF void stbi_ldr_to_hdr_scale(float scale); +#endif // STBI_NO_LINEAR + +// stbi_is_hdr is always defined, but always returns false if STBI_NO_HDR +STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user); +STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len); +#ifndef STBI_NO_STDIO +STBIDEF int stbi_is_hdr (char const *filename); +STBIDEF int stbi_is_hdr_from_file(FILE *f); +#endif // STBI_NO_STDIO + + +// get a VERY brief reason for failure +// on most compilers (and ALL modern mainstream compilers) this is threadsafe +STBIDEF const char *stbi_failure_reason (void); + +// free the loaded image -- this is just free() +STBIDEF void stbi_image_free (void *retval_from_stbi_load); + +// get image dimensions & components without fully decoding +STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp); +STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp); +STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len); +STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *clbk, void *user); + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_info (char const *filename, int *x, int *y, int *comp); +STBIDEF int stbi_info_from_file (FILE *f, int *x, int *y, int *comp); +STBIDEF int stbi_is_16_bit (char const *filename); +STBIDEF int stbi_is_16_bit_from_file(FILE *f); +#endif + + + +// for image formats that explicitly notate that they have premultiplied alpha, +// we just return the colors as stored in the file. set this flag to force +// unpremultiplication. results are undefined if the unpremultiply overflow. +STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply); + +// indicate whether we should process iphone images back to canonical format, +// or just pass them through "as-is" +STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert); + +// flip the image vertically, so the first pixel in the output array is the bottom left +STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip); + +// as above, but only applies to images loaded on the thread that calls the function +// this function is only available if your compiler supports thread-local variables; +// calling it will fail to link if your compiler doesn't +STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip); + +// ZLIB client - used by PNG, available for other purposes + +STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen); +STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header); +STBIDEF char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen); +STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); + +STBIDEF char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen); +STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); + + +#ifdef __cplusplus +} +#endif + +// +// +//// end header file ///////////////////////////////////////////////////// +#endif // STBI_INCLUDE_STB_IMAGE_H + +#ifdef STB_IMAGE_IMPLEMENTATION + +#if defined(STBI_ONLY_JPEG) || defined(STBI_ONLY_PNG) || defined(STBI_ONLY_BMP) \ + || defined(STBI_ONLY_TGA) || defined(STBI_ONLY_GIF) || defined(STBI_ONLY_PSD) \ + || defined(STBI_ONLY_HDR) || defined(STBI_ONLY_PIC) || defined(STBI_ONLY_PNM) \ + || defined(STBI_ONLY_ZLIB) + #ifndef STBI_ONLY_JPEG + #define STBI_NO_JPEG + #endif + #ifndef STBI_ONLY_PNG + #define STBI_NO_PNG + #endif + #ifndef STBI_ONLY_BMP + #define STBI_NO_BMP + #endif + #ifndef STBI_ONLY_PSD + #define STBI_NO_PSD + #endif + #ifndef STBI_ONLY_TGA + #define STBI_NO_TGA + #endif + #ifndef STBI_ONLY_GIF + #define STBI_NO_GIF + #endif + #ifndef STBI_ONLY_HDR + #define STBI_NO_HDR + #endif + #ifndef STBI_ONLY_PIC + #define STBI_NO_PIC + #endif + #ifndef STBI_ONLY_PNM + #define STBI_NO_PNM + #endif +#endif + +#if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) && !defined(STBI_NO_ZLIB) +#define STBI_NO_ZLIB +#endif + + +#include +#include // ptrdiff_t on osx +#include +#include +#include + +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) +#include // ldexp, pow +#endif + +#ifndef STBI_NO_STDIO +#include +#endif + +#ifndef STBI_ASSERT +#include +#define STBI_ASSERT(x) assert(x) +#endif + +#ifdef __cplusplus +#define STBI_EXTERN extern "C" +#else +#define STBI_EXTERN extern +#endif + + +#ifndef _MSC_VER + #ifdef __cplusplus + #define stbi_inline inline + #else + #define stbi_inline + #endif +#else + #define stbi_inline __forceinline +#endif + +#ifndef STBI_NO_THREAD_LOCALS + #if defined(__cplusplus) && __cplusplus >= 201103L + #define STBI_THREAD_LOCAL thread_local + #elif defined(__GNUC__) && __GNUC__ < 5 + #define STBI_THREAD_LOCAL __thread + #elif defined(_MSC_VER) + #define STBI_THREAD_LOCAL __declspec(thread) + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__) + #define STBI_THREAD_LOCAL _Thread_local + #endif + + #ifndef STBI_THREAD_LOCAL + #if defined(__GNUC__) + #define STBI_THREAD_LOCAL __thread + #endif + #endif +#endif + +#ifdef _MSC_VER +typedef unsigned short stbi__uint16; +typedef signed short stbi__int16; +typedef unsigned int stbi__uint32; +typedef signed int stbi__int32; +#else +#include +typedef uint16_t stbi__uint16; +typedef int16_t stbi__int16; +typedef uint32_t stbi__uint32; +typedef int32_t stbi__int32; +#endif + +// should produce compiler error if size is wrong +typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1]; + +#ifdef _MSC_VER +#define STBI_NOTUSED(v) (void)(v) +#else +#define STBI_NOTUSED(v) (void)sizeof(v) +#endif + +#ifdef _MSC_VER +#define STBI_HAS_LROTL +#endif + +#ifdef STBI_HAS_LROTL + #define stbi_lrot(x,y) _lrotl(x,y) +#else + #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (32 - (y)))) +#endif + +#if defined(STBI_MALLOC) && defined(STBI_FREE) && (defined(STBI_REALLOC) || defined(STBI_REALLOC_SIZED)) +// ok +#elif !defined(STBI_MALLOC) && !defined(STBI_FREE) && !defined(STBI_REALLOC) && !defined(STBI_REALLOC_SIZED) +// ok +#else +#error "Must define all or none of STBI_MALLOC, STBI_FREE, and STBI_REALLOC (or STBI_REALLOC_SIZED)." +#endif + +#ifndef STBI_MALLOC +#define STBI_MALLOC(sz) malloc(sz) +#define STBI_REALLOC(p,newsz) realloc(p,newsz) +#define STBI_FREE(p) free(p) +#endif + +#ifndef STBI_REALLOC_SIZED +#define STBI_REALLOC_SIZED(p,oldsz,newsz) ((void)oldsz, STBI_REALLOC(p,newsz)) +#endif + +// x86/x64 detection +#if defined(__x86_64__) || defined(_M_X64) +#define STBI__X64_TARGET +#elif defined(__i386) || defined(_M_IX86) +#define STBI__X86_TARGET +#endif + +#if defined(__GNUC__) && defined(STBI__X86_TARGET) && !defined(__SSE2__) && !defined(STBI_NO_SIMD) +// gcc doesn't support sse2 intrinsics unless you compile with -msse2, +// which in turn means it gets to use SSE2 everywhere. This is unfortunate, +// but previous attempts to provide the SSE2 functions with runtime +// detection caused numerous issues. The way architecture extensions are +// exposed in GCC/Clang is, sadly, not really suited for one-file libs. +// New behavior: if compiled with -msse2, we use SSE2 without any +// detection; if not, we don't use it at all. +#define STBI_NO_SIMD +#endif + +#if defined(__MINGW32__) && defined(STBI__X86_TARGET) && !defined(STBI_MINGW_ENABLE_SSE2) && !defined(STBI_NO_SIMD) +// Note that __MINGW32__ doesn't actually mean 32-bit, so we have to avoid STBI__X64_TARGET +// +// 32-bit MinGW wants ESP to be 16-byte aligned, but this is not in the +// Windows ABI and VC++ as well as Windows DLLs don't maintain that invariant. +// As a result, enabling SSE2 on 32-bit MinGW is dangerous when not +// simultaneously enabling "-mstackrealign". +// +// See https://github.com/nothings/stb/issues/81 for more information. +// +// So default to no SSE2 on 32-bit MinGW. If you've read this far and added +// -mstackrealign to your build settings, feel free to #define STBI_MINGW_ENABLE_SSE2. +#define STBI_NO_SIMD +#endif + +#if !defined(STBI_NO_SIMD) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET)) +#define STBI_SSE2 +#include + +#ifdef _MSC_VER + +#if _MSC_VER >= 1400 // not VC6 +#include // __cpuid +static int stbi__cpuid3(void) +{ + int info[4]; + __cpuid(info,1); + return info[3]; +} +#else +static int stbi__cpuid3(void) +{ + int res; + __asm { + mov eax,1 + cpuid + mov res,edx + } + return res; +} +#endif + +#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name + +#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) +static int stbi__sse2_available(void) +{ + int info3 = stbi__cpuid3(); + return ((info3 >> 26) & 1) != 0; +} +#endif + +#else // assume GCC-style if not VC++ +#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) + +#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) +static int stbi__sse2_available(void) +{ + // If we're even attempting to compile this on GCC/Clang, that means + // -msse2 is on, which means the compiler is allowed to use SSE2 + // instructions at will, and so are we. + return 1; +} +#endif + +#endif +#endif + +// ARM NEON +#if defined(STBI_NO_SIMD) && defined(STBI_NEON) +#undef STBI_NEON +#endif + +#ifdef STBI_NEON +#include +// assume GCC or Clang on ARM targets +#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) +#endif + +#ifndef STBI_SIMD_ALIGN +#define STBI_SIMD_ALIGN(type, name) type name +#endif + +#ifndef STBI_MAX_DIMENSIONS +#define STBI_MAX_DIMENSIONS (1 << 24) +#endif + +/////////////////////////////////////////////// +// +// stbi__context struct and start_xxx functions + +// stbi__context structure is our basic context used by all images, so it +// contains all the IO context, plus some basic image information +typedef struct +{ + stbi__uint32 img_x, img_y; + int img_n, img_out_n; + + stbi_io_callbacks io; + void *io_user_data; + + int read_from_callbacks; + int buflen; + stbi_uc buffer_start[128]; + int callback_already_read; + + stbi_uc *img_buffer, *img_buffer_end; + stbi_uc *img_buffer_original, *img_buffer_original_end; +} stbi__context; + + +static void stbi__refill_buffer(stbi__context *s); + +// initialize a memory-decode context +static void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int len) +{ + s->io.read = NULL; + s->read_from_callbacks = 0; + s->callback_already_read = 0; + s->img_buffer = s->img_buffer_original = (stbi_uc *) buffer; + s->img_buffer_end = s->img_buffer_original_end = (stbi_uc *) buffer+len; +} + +// initialize a callback-based context +static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c, void *user) +{ + s->io = *c; + s->io_user_data = user; + s->buflen = sizeof(s->buffer_start); + s->read_from_callbacks = 1; + s->callback_already_read = 0; + s->img_buffer = s->img_buffer_original = s->buffer_start; + stbi__refill_buffer(s); + s->img_buffer_original_end = s->img_buffer_end; +} + +#ifndef STBI_NO_STDIO + +static int stbi__stdio_read(void *user, char *data, int size) +{ + return (int) fread(data,1,size,(FILE*) user); +} + +static void stbi__stdio_skip(void *user, int n) +{ + int ch; + fseek((FILE*) user, n, SEEK_CUR); + ch = fgetc((FILE*) user); /* have to read a byte to reset feof()'s flag */ + if (ch != EOF) { + ungetc(ch, (FILE *) user); /* push byte back onto stream if valid. */ + } +} + +static int stbi__stdio_eof(void *user) +{ + return feof((FILE*) user) || ferror((FILE *) user); +} + +static stbi_io_callbacks stbi__stdio_callbacks = +{ + stbi__stdio_read, + stbi__stdio_skip, + stbi__stdio_eof, +}; + +static void stbi__start_file(stbi__context *s, FILE *f) +{ + stbi__start_callbacks(s, &stbi__stdio_callbacks, (void *) f); +} + +//static void stop_file(stbi__context *s) { } + +#endif // !STBI_NO_STDIO + +static void stbi__rewind(stbi__context *s) +{ + // conceptually rewind SHOULD rewind to the beginning of the stream, + // but we just rewind to the beginning of the initial buffer, because + // we only use it after doing 'test', which only ever looks at at most 92 bytes + s->img_buffer = s->img_buffer_original; + s->img_buffer_end = s->img_buffer_original_end; +} + +enum +{ + STBI_ORDER_RGB, + STBI_ORDER_BGR +}; + +typedef struct +{ + int bits_per_channel; + int num_channels; + int channel_order; +} stbi__result_info; + +#ifndef STBI_NO_JPEG +static int stbi__jpeg_test(stbi__context *s); +static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PNG +static int stbi__png_test(stbi__context *s); +static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__png_is16(stbi__context *s); +#endif + +#ifndef STBI_NO_BMP +static int stbi__bmp_test(stbi__context *s); +static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_TGA +static int stbi__tga_test(stbi__context *s); +static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PSD +static int stbi__psd_test(stbi__context *s); +static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc); +static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__psd_is16(stbi__context *s); +#endif + +#ifndef STBI_NO_HDR +static int stbi__hdr_test(stbi__context *s); +static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PIC +static int stbi__pic_test(stbi__context *s); +static void *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_GIF +static int stbi__gif_test(stbi__context *s); +static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp); +static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PNM +static int stbi__pnm_test(stbi__context *s); +static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +static +#ifdef STBI_THREAD_LOCAL +STBI_THREAD_LOCAL +#endif +const char *stbi__g_failure_reason; + +STBIDEF const char *stbi_failure_reason(void) +{ + return stbi__g_failure_reason; +} + +#ifndef STBI_NO_FAILURE_STRINGS +static int stbi__err(const char *str) +{ + stbi__g_failure_reason = str; + return 0; +} +#endif + +static void *stbi__malloc(size_t size) +{ + return STBI_MALLOC(size); +} + +// stb_image uses ints pervasively, including for offset calculations. +// therefore the largest decoded image size we can support with the +// current code, even on 64-bit targets, is INT_MAX. this is not a +// significant limitation for the intended use case. +// +// we do, however, need to make sure our size calculations don't +// overflow. hence a few helper functions for size calculations that +// multiply integers together, making sure that they're non-negative +// and no overflow occurs. + +// return 1 if the sum is valid, 0 on overflow. +// negative terms are considered invalid. +static int stbi__addsizes_valid(int a, int b) +{ + if (b < 0) return 0; + // now 0 <= b <= INT_MAX, hence also + // 0 <= INT_MAX - b <= INTMAX. + // And "a + b <= INT_MAX" (which might overflow) is the + // same as a <= INT_MAX - b (no overflow) + return a <= INT_MAX - b; +} + +// returns 1 if the product is valid, 0 on overflow. +// negative factors are considered invalid. +static int stbi__mul2sizes_valid(int a, int b) +{ + if (a < 0 || b < 0) return 0; + if (b == 0) return 1; // mul-by-0 is always safe + // portable way to check for no overflows in a*b + return a <= INT_MAX/b; +} + +#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) +// returns 1 if "a*b + add" has no negative terms/factors and doesn't overflow +static int stbi__mad2sizes_valid(int a, int b, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__addsizes_valid(a*b, add); +} +#endif + +// returns 1 if "a*b*c + add" has no negative terms/factors and doesn't overflow +static int stbi__mad3sizes_valid(int a, int b, int c, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && + stbi__addsizes_valid(a*b*c, add); +} + +// returns 1 if "a*b*c*d + add" has no negative terms/factors and doesn't overflow +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) +static int stbi__mad4sizes_valid(int a, int b, int c, int d, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && + stbi__mul2sizes_valid(a*b*c, d) && stbi__addsizes_valid(a*b*c*d, add); +} +#endif + +#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) +// mallocs with size overflow checking +static void *stbi__malloc_mad2(int a, int b, int add) +{ + if (!stbi__mad2sizes_valid(a, b, add)) return NULL; + return stbi__malloc(a*b + add); +} +#endif + +static void *stbi__malloc_mad3(int a, int b, int c, int add) +{ + if (!stbi__mad3sizes_valid(a, b, c, add)) return NULL; + return stbi__malloc(a*b*c + add); +} + +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) +static void *stbi__malloc_mad4(int a, int b, int c, int d, int add) +{ + if (!stbi__mad4sizes_valid(a, b, c, d, add)) return NULL; + return stbi__malloc(a*b*c*d + add); +} +#endif + +// stbi__err - error +// stbi__errpf - error returning pointer to float +// stbi__errpuc - error returning pointer to unsigned char + +#ifdef STBI_NO_FAILURE_STRINGS + #define stbi__err(x,y) 0 +#elif defined(STBI_FAILURE_USERMSG) + #define stbi__err(x,y) stbi__err(y) +#else + #define stbi__err(x,y) stbi__err(x) +#endif + +#define stbi__errpf(x,y) ((float *)(size_t) (stbi__err(x,y)?NULL:NULL)) +#define stbi__errpuc(x,y) ((unsigned char *)(size_t) (stbi__err(x,y)?NULL:NULL)) + +STBIDEF void stbi_image_free(void *retval_from_stbi_load) +{ + STBI_FREE(retval_from_stbi_load); +} + +#ifndef STBI_NO_LINEAR +static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp); +#endif + +#ifndef STBI_NO_HDR +static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp); +#endif + +static int stbi__vertically_flip_on_load_global = 0; + +STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip) +{ + stbi__vertically_flip_on_load_global = flag_true_if_should_flip; +} + +#ifndef STBI_THREAD_LOCAL +#define stbi__vertically_flip_on_load stbi__vertically_flip_on_load_global +#else +static STBI_THREAD_LOCAL int stbi__vertically_flip_on_load_local, stbi__vertically_flip_on_load_set; + +STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip) +{ + stbi__vertically_flip_on_load_local = flag_true_if_should_flip; + stbi__vertically_flip_on_load_set = 1; +} + +#define stbi__vertically_flip_on_load (stbi__vertically_flip_on_load_set \ + ? stbi__vertically_flip_on_load_local \ + : stbi__vertically_flip_on_load_global) +#endif // STBI_THREAD_LOCAL + +static void *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) +{ + memset(ri, 0, sizeof(*ri)); // make sure it's initialized if we add new fields + ri->bits_per_channel = 8; // default is 8 so most paths don't have to be changed + ri->channel_order = STBI_ORDER_RGB; // all current input & output are this, but this is here so we can add BGR order + ri->num_channels = 0; + + #ifndef STBI_NO_JPEG + if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_PNG + if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_BMP + if (stbi__bmp_test(s)) return stbi__bmp_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_GIF + if (stbi__gif_test(s)) return stbi__gif_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_PSD + if (stbi__psd_test(s)) return stbi__psd_load(s,x,y,comp,req_comp, ri, bpc); + #else + STBI_NOTUSED(bpc); + #endif + #ifndef STBI_NO_PIC + if (stbi__pic_test(s)) return stbi__pic_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_PNM + if (stbi__pnm_test(s)) return stbi__pnm_load(s,x,y,comp,req_comp, ri); + #endif + + #ifndef STBI_NO_HDR + if (stbi__hdr_test(s)) { + float *hdr = stbi__hdr_load(s, x,y,comp,req_comp, ri); + return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp); + } + #endif + + #ifndef STBI_NO_TGA + // test tga last because it's a crappy test! + if (stbi__tga_test(s)) + return stbi__tga_load(s,x,y,comp,req_comp, ri); + #endif + + return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt"); +} + +static stbi_uc *stbi__convert_16_to_8(stbi__uint16 *orig, int w, int h, int channels) +{ + int i; + int img_len = w * h * channels; + stbi_uc *reduced; + + reduced = (stbi_uc *) stbi__malloc(img_len); + if (reduced == NULL) return stbi__errpuc("outofmem", "Out of memory"); + + for (i = 0; i < img_len; ++i) + reduced[i] = (stbi_uc)((orig[i] >> 8) & 0xFF); // top half of each byte is sufficient approx of 16->8 bit scaling + + STBI_FREE(orig); + return reduced; +} + +static stbi__uint16 *stbi__convert_8_to_16(stbi_uc *orig, int w, int h, int channels) +{ + int i; + int img_len = w * h * channels; + stbi__uint16 *enlarged; + + enlarged = (stbi__uint16 *) stbi__malloc(img_len*2); + if (enlarged == NULL) return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); + + for (i = 0; i < img_len; ++i) + enlarged[i] = (stbi__uint16)((orig[i] << 8) + orig[i]); // replicate to high and low byte, maps 0->0, 255->0xffff + + STBI_FREE(orig); + return enlarged; +} + +static void stbi__vertical_flip(void *image, int w, int h, int bytes_per_pixel) +{ + int row; + size_t bytes_per_row = (size_t)w * bytes_per_pixel; + stbi_uc temp[2048]; + stbi_uc *bytes = (stbi_uc *)image; + + for (row = 0; row < (h>>1); row++) { + stbi_uc *row0 = bytes + row*bytes_per_row; + stbi_uc *row1 = bytes + (h - row - 1)*bytes_per_row; + // swap row0 with row1 + size_t bytes_left = bytes_per_row; + while (bytes_left) { + size_t bytes_copy = (bytes_left < sizeof(temp)) ? bytes_left : sizeof(temp); + memcpy(temp, row0, bytes_copy); + memcpy(row0, row1, bytes_copy); + memcpy(row1, temp, bytes_copy); + row0 += bytes_copy; + row1 += bytes_copy; + bytes_left -= bytes_copy; + } + } +} + +#ifndef STBI_NO_GIF +static void stbi__vertical_flip_slices(void *image, int w, int h, int z, int bytes_per_pixel) +{ + int slice; + int slice_size = w * h * bytes_per_pixel; + + stbi_uc *bytes = (stbi_uc *)image; + for (slice = 0; slice < z; ++slice) { + stbi__vertical_flip(bytes, w, h, bytes_per_pixel); + bytes += slice_size; + } +} +#endif + +static unsigned char *stbi__load_and_postprocess_8bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + stbi__result_info ri; + void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 8); + + if (result == NULL) + return NULL; + + // it is the responsibility of the loaders to make sure we get either 8 or 16 bit. + STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); + + if (ri.bits_per_channel != 8) { + result = stbi__convert_16_to_8((stbi__uint16 *) result, *x, *y, req_comp == 0 ? *comp : req_comp); + ri.bits_per_channel = 8; + } + + // @TODO: move stbi__convert_format to here + + if (stbi__vertically_flip_on_load) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi_uc)); + } + + return (unsigned char *) result; +} + +static stbi__uint16 *stbi__load_and_postprocess_16bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + stbi__result_info ri; + void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 16); + + if (result == NULL) + return NULL; + + // it is the responsibility of the loaders to make sure we get either 8 or 16 bit. + STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); + + if (ri.bits_per_channel != 16) { + result = stbi__convert_8_to_16((stbi_uc *) result, *x, *y, req_comp == 0 ? *comp : req_comp); + ri.bits_per_channel = 16; + } + + // @TODO: move stbi__convert_format16 to here + // @TODO: special case RGB-to-Y (and RGBA-to-YA) for 8-bit-to-16-bit case to keep more precision + + if (stbi__vertically_flip_on_load) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi__uint16)); + } + + return (stbi__uint16 *) result; +} + +#if !defined(STBI_NO_HDR) && !defined(STBI_NO_LINEAR) +static void stbi__float_postprocess(float *result, int *x, int *y, int *comp, int req_comp) +{ + if (stbi__vertically_flip_on_load && result != NULL) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(float)); + } +} +#endif + +#ifndef STBI_NO_STDIO + +#if defined(_MSC_VER) && defined(STBI_WINDOWS_UTF8) +STBI_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide); +STBI_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t *widestr, int cchwide, char *str, int cbmb, const char *defchar, int *used_default); +#endif + +#if defined(_MSC_VER) && defined(STBI_WINDOWS_UTF8) +STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input) +{ + return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, NULL); +} +#endif + +static FILE *stbi__fopen(char const *filename, char const *mode) +{ + FILE *f; +#if defined(_MSC_VER) && defined(STBI_WINDOWS_UTF8) + wchar_t wMode[64]; + wchar_t wFilename[1024]; + if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename))) + return 0; + + if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode))) + return 0; + +#if _MSC_VER >= 1400 + if (0 != _wfopen_s(&f, wFilename, wMode)) + f = 0; +#else + f = _wfopen(wFilename, wMode); +#endif + +#elif defined(_MSC_VER) && _MSC_VER >= 1400 + if (0 != fopen_s(&f, filename, mode)) + f=0; +#else + f = fopen(filename, mode); +#endif + return f; +} + + +STBIDEF stbi_uc *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + unsigned char *result; + if (!f) return stbi__errpuc("can't fopen", "Unable to open file"); + result = stbi_load_from_file(f,x,y,comp,req_comp); + fclose(f); + return result; +} + +STBIDEF stbi_uc *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + unsigned char *result; + stbi__context s; + stbi__start_file(&s,f); + result = stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); + if (result) { + // need to 'unget' all the characters in the IO buffer + fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); + } + return result; +} + +STBIDEF stbi__uint16 *stbi_load_from_file_16(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + stbi__uint16 *result; + stbi__context s; + stbi__start_file(&s,f); + result = stbi__load_and_postprocess_16bit(&s,x,y,comp,req_comp); + if (result) { + // need to 'unget' all the characters in the IO buffer + fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); + } + return result; +} + +STBIDEF stbi_us *stbi_load_16(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + stbi__uint16 *result; + if (!f) return (stbi_us *) stbi__errpuc("can't fopen", "Unable to open file"); + result = stbi_load_from_file_16(f,x,y,comp,req_comp); + fclose(f); + return result; +} + + +#endif //!STBI_NO_STDIO + +STBIDEF stbi_us *stbi_load_16_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels); +} + +STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *)clbk, user); + return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels); +} + +STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); +} + +STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); + return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); +} + +#ifndef STBI_NO_GIF +STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp) +{ + unsigned char *result; + stbi__context s; + stbi__start_mem(&s,buffer,len); + + result = (unsigned char*) stbi__load_gif_main(&s, delays, x, y, z, comp, req_comp); + if (stbi__vertically_flip_on_load) { + stbi__vertical_flip_slices( result, *x, *y, *z, *comp ); + } + + return result; +} +#endif + +#ifndef STBI_NO_LINEAR +static float *stbi__loadf_main(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + unsigned char *data; + #ifndef STBI_NO_HDR + if (stbi__hdr_test(s)) { + stbi__result_info ri; + float *hdr_data = stbi__hdr_load(s,x,y,comp,req_comp, &ri); + if (hdr_data) + stbi__float_postprocess(hdr_data,x,y,comp,req_comp); + return hdr_data; + } + #endif + data = stbi__load_and_postprocess_8bit(s, x, y, comp, req_comp); + if (data) + return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp); + return stbi__errpf("unknown image type", "Image not of any known type, or corrupt"); +} + +STBIDEF float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__loadf_main(&s,x,y,comp,req_comp); +} + +STBIDEF float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); + return stbi__loadf_main(&s,x,y,comp,req_comp); +} + +#ifndef STBI_NO_STDIO +STBIDEF float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + float *result; + FILE *f = stbi__fopen(filename, "rb"); + if (!f) return stbi__errpf("can't fopen", "Unable to open file"); + result = stbi_loadf_from_file(f,x,y,comp,req_comp); + fclose(f); + return result; +} + +STBIDEF float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_file(&s,f); + return stbi__loadf_main(&s,x,y,comp,req_comp); +} +#endif // !STBI_NO_STDIO + +#endif // !STBI_NO_LINEAR + +// these is-hdr-or-not is defined independent of whether STBI_NO_LINEAR is +// defined, for API simplicity; if STBI_NO_LINEAR is defined, it always +// reports false! + +STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len) +{ + #ifndef STBI_NO_HDR + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__hdr_test(&s); + #else + STBI_NOTUSED(buffer); + STBI_NOTUSED(len); + return 0; + #endif +} + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_is_hdr (char const *filename) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result=0; + if (f) { + result = stbi_is_hdr_from_file(f); + fclose(f); + } + return result; +} + +STBIDEF int stbi_is_hdr_from_file(FILE *f) +{ + #ifndef STBI_NO_HDR + long pos = ftell(f); + int res; + stbi__context s; + stbi__start_file(&s,f); + res = stbi__hdr_test(&s); + fseek(f, pos, SEEK_SET); + return res; + #else + STBI_NOTUSED(f); + return 0; + #endif +} +#endif // !STBI_NO_STDIO + +STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user) +{ + #ifndef STBI_NO_HDR + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); + return stbi__hdr_test(&s); + #else + STBI_NOTUSED(clbk); + STBI_NOTUSED(user); + return 0; + #endif +} + +#ifndef STBI_NO_LINEAR +static float stbi__l2h_gamma=2.2f, stbi__l2h_scale=1.0f; + +STBIDEF void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; } +STBIDEF void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; } +#endif + +static float stbi__h2l_gamma_i=1.0f/2.2f, stbi__h2l_scale_i=1.0f; + +STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1/gamma; } +STBIDEF void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1/scale; } + + +////////////////////////////////////////////////////////////////////////////// +// +// Common code used by all image loaders +// + +enum +{ + STBI__SCAN_load=0, + STBI__SCAN_type, + STBI__SCAN_header +}; + +static void stbi__refill_buffer(stbi__context *s) +{ + int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen); + s->callback_already_read += (int) (s->img_buffer - s->img_buffer_original); + if (n == 0) { + // at end of file, treat same as if from memory, but need to handle case + // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file + s->read_from_callbacks = 0; + s->img_buffer = s->buffer_start; + s->img_buffer_end = s->buffer_start+1; + *s->img_buffer = 0; + } else { + s->img_buffer = s->buffer_start; + s->img_buffer_end = s->buffer_start + n; + } +} + +stbi_inline static stbi_uc stbi__get8(stbi__context *s) +{ + if (s->img_buffer < s->img_buffer_end) + return *s->img_buffer++; + if (s->read_from_callbacks) { + stbi__refill_buffer(s); + return *s->img_buffer++; + } + return 0; +} + +#if defined(STBI_NO_JPEG) && defined(STBI_NO_HDR) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +// nothing +#else +stbi_inline static int stbi__at_eof(stbi__context *s) +{ + if (s->io.read) { + if (!(s->io.eof)(s->io_user_data)) return 0; + // if feof() is true, check if buffer = end + // special case: we've only got the special 0 character at the end + if (s->read_from_callbacks == 0) return 1; + } + + return s->img_buffer >= s->img_buffer_end; +} +#endif + +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) +// nothing +#else +static void stbi__skip(stbi__context *s, int n) +{ + if (n == 0) return; // already there! + if (n < 0) { + s->img_buffer = s->img_buffer_end; + return; + } + if (s->io.read) { + int blen = (int) (s->img_buffer_end - s->img_buffer); + if (blen < n) { + s->img_buffer = s->img_buffer_end; + (s->io.skip)(s->io_user_data, n - blen); + return; + } + } + s->img_buffer += n; +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_TGA) && defined(STBI_NO_HDR) && defined(STBI_NO_PNM) +// nothing +#else +static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n) +{ + if (s->io.read) { + int blen = (int) (s->img_buffer_end - s->img_buffer); + if (blen < n) { + int res, count; + + memcpy(buffer, s->img_buffer, blen); + + count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen); + res = (count == (n-blen)); + s->img_buffer = s->img_buffer_end; + return res; + } + } + + if (s->img_buffer+n <= s->img_buffer_end) { + memcpy(buffer, s->img_buffer, n); + s->img_buffer += n; + return 1; + } else + return 0; +} +#endif + +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC) +// nothing +#else +static int stbi__get16be(stbi__context *s) +{ + int z = stbi__get8(s); + return (z << 8) + stbi__get8(s); +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC) +// nothing +#else +static stbi__uint32 stbi__get32be(stbi__context *s) +{ + stbi__uint32 z = stbi__get16be(s); + return (z << 16) + stbi__get16be(s); +} +#endif + +#if defined(STBI_NO_BMP) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) +// nothing +#else +static int stbi__get16le(stbi__context *s) +{ + int z = stbi__get8(s); + return z + (stbi__get8(s) << 8); +} +#endif + +#ifndef STBI_NO_BMP +static stbi__uint32 stbi__get32le(stbi__context *s) +{ + stbi__uint32 z = stbi__get16le(s); + return z + (stbi__get16le(s) << 16); +} +#endif + +#define STBI__BYTECAST(x) ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings + +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +// nothing +#else +////////////////////////////////////////////////////////////////////////////// +// +// generic converter from built-in img_n to req_comp +// individual types do this automatically as much as possible (e.g. jpeg +// does all cases internally since it needs to colorspace convert anyway, +// and it never has alpha, so very few cases ). png can automatically +// interleave an alpha=255 channel, but falls back to this for other cases +// +// assume data buffer is malloced, so malloc a new one and free that one +// only failure mode is malloc failing + +static stbi_uc stbi__compute_y(int r, int g, int b) +{ + return (stbi_uc) (((r*77) + (g*150) + (29*b)) >> 8); +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +// nothing +#else +static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y) +{ + int i,j; + unsigned char *good; + + if (req_comp == img_n) return data; + STBI_ASSERT(req_comp >= 1 && req_comp <= 4); + + good = (unsigned char *) stbi__malloc_mad3(req_comp, x, y, 0); + if (good == NULL) { + STBI_FREE(data); + return stbi__errpuc("outofmem", "Out of memory"); + } + + for (j=0; j < (int) y; ++j) { + unsigned char *src = data + j * x * img_n ; + unsigned char *dest = good + j * x * req_comp; + + #define STBI__COMBO(a,b) ((a)*8+(b)) + #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) + // convert source image with img_n components to one with req_comp components; + // avoid switch per pixel, so use switch per scanline and massive macros + switch (STBI__COMBO(img_n, req_comp)) { + STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=255; } break; + STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=255; } break; + STBI__CASE(2,1) { dest[0]=src[0]; } break; + STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break; + STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=255; } break; + STBI__CASE(3,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break; + STBI__CASE(3,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = 255; } break; + STBI__CASE(4,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break; + STBI__CASE(4,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = src[3]; } break; + STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break; + default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return stbi__errpuc("unsupported", "Unsupported format conversion"); + } + #undef STBI__CASE + } + + STBI_FREE(data); + return good; +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) +// nothing +#else +static stbi__uint16 stbi__compute_y_16(int r, int g, int b) +{ + return (stbi__uint16) (((r*77) + (g*150) + (29*b)) >> 8); +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) +// nothing +#else +static stbi__uint16 *stbi__convert_format16(stbi__uint16 *data, int img_n, int req_comp, unsigned int x, unsigned int y) +{ + int i,j; + stbi__uint16 *good; + + if (req_comp == img_n) return data; + STBI_ASSERT(req_comp >= 1 && req_comp <= 4); + + good = (stbi__uint16 *) stbi__malloc(req_comp * x * y * 2); + if (good == NULL) { + STBI_FREE(data); + return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); + } + + for (j=0; j < (int) y; ++j) { + stbi__uint16 *src = data + j * x * img_n ; + stbi__uint16 *dest = good + j * x * req_comp; + + #define STBI__COMBO(a,b) ((a)*8+(b)) + #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) + // convert source image with img_n components to one with req_comp components; + // avoid switch per pixel, so use switch per scanline and massive macros + switch (STBI__COMBO(img_n, req_comp)) { + STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=0xffff; } break; + STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=0xffff; } break; + STBI__CASE(2,1) { dest[0]=src[0]; } break; + STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break; + STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=0xffff; } break; + STBI__CASE(3,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break; + STBI__CASE(3,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = 0xffff; } break; + STBI__CASE(4,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break; + STBI__CASE(4,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = src[3]; } break; + STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break; + default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return (stbi__uint16*) stbi__errpuc("unsupported", "Unsupported format conversion"); + } + #undef STBI__CASE + } + + STBI_FREE(data); + return good; +} +#endif + +#ifndef STBI_NO_LINEAR +static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp) +{ + int i,k,n; + float *output; + if (!data) return NULL; + output = (float *) stbi__malloc_mad4(x, y, comp, sizeof(float), 0); + if (output == NULL) { STBI_FREE(data); return stbi__errpf("outofmem", "Out of memory"); } + // compute number of non-alpha components + if (comp & 1) n = comp; else n = comp-1; + for (i=0; i < x*y; ++i) { + for (k=0; k < n; ++k) { + output[i*comp + k] = (float) (pow(data[i*comp+k]/255.0f, stbi__l2h_gamma) * stbi__l2h_scale); + } + } + if (n < comp) { + for (i=0; i < x*y; ++i) { + output[i*comp + n] = data[i*comp + n]/255.0f; + } + } + STBI_FREE(data); + return output; +} +#endif + +#ifndef STBI_NO_HDR +#define stbi__float2int(x) ((int) (x)) +static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp) +{ + int i,k,n; + stbi_uc *output; + if (!data) return NULL; + output = (stbi_uc *) stbi__malloc_mad3(x, y, comp, 0); + if (output == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); } + // compute number of non-alpha components + if (comp & 1) n = comp; else n = comp-1; + for (i=0; i < x*y; ++i) { + for (k=0; k < n; ++k) { + float z = (float) pow(data[i*comp+k]*stbi__h2l_scale_i, stbi__h2l_gamma_i) * 255 + 0.5f; + if (z < 0) z = 0; + if (z > 255) z = 255; + output[i*comp + k] = (stbi_uc) stbi__float2int(z); + } + if (k < comp) { + float z = data[i*comp+k] * 255 + 0.5f; + if (z < 0) z = 0; + if (z > 255) z = 255; + output[i*comp + k] = (stbi_uc) stbi__float2int(z); + } + } + STBI_FREE(data); + return output; +} +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// "baseline" JPEG/JFIF decoder +// +// simple implementation +// - doesn't support delayed output of y-dimension +// - simple interface (only one output format: 8-bit interleaved RGB) +// - doesn't try to recover corrupt jpegs +// - doesn't allow partial loading, loading multiple at once +// - still fast on x86 (copying globals into locals doesn't help x86) +// - allocates lots of intermediate memory (full size of all components) +// - non-interleaved case requires this anyway +// - allows good upsampling (see next) +// high-quality +// - upsampled channels are bilinearly interpolated, even across blocks +// - quality integer IDCT derived from IJG's 'slow' +// performance +// - fast huffman; reasonable integer IDCT +// - some SIMD kernels for common paths on targets with SSE2/NEON +// - uses a lot of intermediate memory, could cache poorly + +#ifndef STBI_NO_JPEG + +// huffman decoding acceleration +#define FAST_BITS 9 // larger handles more cases; smaller stomps less cache + +typedef struct +{ + stbi_uc fast[1 << FAST_BITS]; + // weirdly, repacking this into AoS is a 10% speed loss, instead of a win + stbi__uint16 code[256]; + stbi_uc values[256]; + stbi_uc size[257]; + unsigned int maxcode[18]; + int delta[17]; // old 'firstsymbol' - old 'firstcode' +} stbi__huffman; + +typedef struct +{ + stbi__context *s; + stbi__huffman huff_dc[4]; + stbi__huffman huff_ac[4]; + stbi__uint16 dequant[4][64]; + stbi__int16 fast_ac[4][1 << FAST_BITS]; + +// sizes for components, interleaved MCUs + int img_h_max, img_v_max; + int img_mcu_x, img_mcu_y; + int img_mcu_w, img_mcu_h; + +// definition of jpeg image component + struct + { + int id; + int h,v; + int tq; + int hd,ha; + int dc_pred; + + int x,y,w2,h2; + stbi_uc *data; + void *raw_data, *raw_coeff; + stbi_uc *linebuf; + short *coeff; // progressive only + int coeff_w, coeff_h; // number of 8x8 coefficient blocks + } img_comp[4]; + + stbi__uint32 code_buffer; // jpeg entropy-coded buffer + int code_bits; // number of valid bits + unsigned char marker; // marker seen while filling entropy buffer + int nomore; // flag if we saw a marker so must stop + + int progressive; + int spec_start; + int spec_end; + int succ_high; + int succ_low; + int eob_run; + int jfif; + int app14_color_transform; // Adobe APP14 tag + int rgb; + + int scan_n, order[4]; + int restart_interval, todo; + +// kernels + void (*idct_block_kernel)(stbi_uc *out, int out_stride, short data[64]); + void (*YCbCr_to_RGB_kernel)(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step); + stbi_uc *(*resample_row_hv_2_kernel)(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs); +} stbi__jpeg; + +static int stbi__build_huffman(stbi__huffman *h, int *count) +{ + int i,j,k=0; + unsigned int code; + // build size list for each symbol (from JPEG spec) + for (i=0; i < 16; ++i) + for (j=0; j < count[i]; ++j) + h->size[k++] = (stbi_uc) (i+1); + h->size[k] = 0; + + // compute actual symbols (from jpeg spec) + code = 0; + k = 0; + for(j=1; j <= 16; ++j) { + // compute delta to add to code to compute symbol id + h->delta[j] = k - code; + if (h->size[k] == j) { + while (h->size[k] == j) + h->code[k++] = (stbi__uint16) (code++); + if (code-1 >= (1u << j)) return stbi__err("bad code lengths","Corrupt JPEG"); + } + // compute largest code + 1 for this size, preshifted as needed later + h->maxcode[j] = code << (16-j); + code <<= 1; + } + h->maxcode[j] = 0xffffffff; + + // build non-spec acceleration table; 255 is flag for not-accelerated + memset(h->fast, 255, 1 << FAST_BITS); + for (i=0; i < k; ++i) { + int s = h->size[i]; + if (s <= FAST_BITS) { + int c = h->code[i] << (FAST_BITS-s); + int m = 1 << (FAST_BITS-s); + for (j=0; j < m; ++j) { + h->fast[c+j] = (stbi_uc) i; + } + } + } + return 1; +} + +// build a table that decodes both magnitude and value of small ACs in +// one go. +static void stbi__build_fast_ac(stbi__int16 *fast_ac, stbi__huffman *h) +{ + int i; + for (i=0; i < (1 << FAST_BITS); ++i) { + stbi_uc fast = h->fast[i]; + fast_ac[i] = 0; + if (fast < 255) { + int rs = h->values[fast]; + int run = (rs >> 4) & 15; + int magbits = rs & 15; + int len = h->size[fast]; + + if (magbits && len + magbits <= FAST_BITS) { + // magnitude code followed by receive_extend code + int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> (FAST_BITS - magbits); + int m = 1 << (magbits - 1); + if (k < m) k += (~0U << magbits) + 1; + // if the result is small enough, we can fit it in fast_ac table + if (k >= -128 && k <= 127) + fast_ac[i] = (stbi__int16) ((k * 256) + (run * 16) + (len + magbits)); + } + } + } +} + +static void stbi__grow_buffer_unsafe(stbi__jpeg *j) +{ + do { + unsigned int b = j->nomore ? 0 : stbi__get8(j->s); + if (b == 0xff) { + int c = stbi__get8(j->s); + while (c == 0xff) c = stbi__get8(j->s); // consume fill bytes + if (c != 0) { + j->marker = (unsigned char) c; + j->nomore = 1; + return; + } + } + j->code_buffer |= b << (24 - j->code_bits); + j->code_bits += 8; + } while (j->code_bits <= 24); +} + +// (1 << n) - 1 +static const stbi__uint32 stbi__bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535}; + +// decode a jpeg huffman value from the bitstream +stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h) +{ + unsigned int temp; + int c,k; + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + + // look at the top FAST_BITS and determine what symbol ID it is, + // if the code is <= FAST_BITS + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); + k = h->fast[c]; + if (k < 255) { + int s = h->size[k]; + if (s > j->code_bits) + return -1; + j->code_buffer <<= s; + j->code_bits -= s; + return h->values[k]; + } + + // naive test is to shift the code_buffer down so k bits are + // valid, then test against maxcode. To speed this up, we've + // preshifted maxcode left so that it has (16-k) 0s at the + // end; in other words, regardless of the number of bits, it + // wants to be compared against something shifted to have 16; + // that way we don't need to shift inside the loop. + temp = j->code_buffer >> 16; + for (k=FAST_BITS+1 ; ; ++k) + if (temp < h->maxcode[k]) + break; + if (k == 17) { + // error! code not found + j->code_bits -= 16; + return -1; + } + + if (k > j->code_bits) + return -1; + + // convert the huffman code to the symbol id + c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k]; + STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]); + + // convert the id to a symbol + j->code_bits -= k; + j->code_buffer <<= k; + return h->values[c]; +} + +// bias[n] = (-1<code_bits < n) stbi__grow_buffer_unsafe(j); + + sgn = (stbi__int32)j->code_buffer >> 31; // sign bit is always in MSB + k = stbi_lrot(j->code_buffer, n); + if (n < 0 || n >= (int) (sizeof(stbi__bmask)/sizeof(*stbi__bmask))) return 0; + j->code_buffer = k & ~stbi__bmask[n]; + k &= stbi__bmask[n]; + j->code_bits -= n; + return k + (stbi__jbias[n] & ~sgn); +} + +// get some unsigned bits +stbi_inline static int stbi__jpeg_get_bits(stbi__jpeg *j, int n) +{ + unsigned int k; + if (j->code_bits < n) stbi__grow_buffer_unsafe(j); + k = stbi_lrot(j->code_buffer, n); + j->code_buffer = k & ~stbi__bmask[n]; + k &= stbi__bmask[n]; + j->code_bits -= n; + return k; +} + +stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg *j) +{ + unsigned int k; + if (j->code_bits < 1) stbi__grow_buffer_unsafe(j); + k = j->code_buffer; + j->code_buffer <<= 1; + --j->code_bits; + return k & 0x80000000; +} + +// given a value that's at position X in the zigzag stream, +// where does it appear in the 8x8 matrix coded as row-major? +static const stbi_uc stbi__jpeg_dezigzag[64+15] = +{ + 0, 1, 8, 16, 9, 2, 3, 10, + 17, 24, 32, 25, 18, 11, 4, 5, + 12, 19, 26, 33, 40, 48, 41, 34, + 27, 20, 13, 6, 7, 14, 21, 28, + 35, 42, 49, 56, 57, 50, 43, 36, + 29, 22, 15, 23, 30, 37, 44, 51, + 58, 59, 52, 45, 38, 31, 39, 46, + 53, 60, 61, 54, 47, 55, 62, 63, + // let corrupt input sample past end + 63, 63, 63, 63, 63, 63, 63, 63, + 63, 63, 63, 63, 63, 63, 63 +}; + +// decode one 64-entry block-- +static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman *hdc, stbi__huffman *hac, stbi__int16 *fac, int b, stbi__uint16 *dequant) +{ + int diff,dc,k; + int t; + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + t = stbi__jpeg_huff_decode(j, hdc); + if (t < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + + // 0 all the ac values now so we can do it 32-bits at a time + memset(data,0,64*sizeof(data[0])); + + diff = t ? stbi__extend_receive(j, t) : 0; + dc = j->img_comp[b].dc_pred + diff; + j->img_comp[b].dc_pred = dc; + data[0] = (short) (dc * dequant[0]); + + // decode AC components, see JPEG spec + k = 1; + do { + unsigned int zig; + int c,r,s; + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); + r = fac[c]; + if (r) { // fast-AC path + k += (r >> 4) & 15; // run + s = r & 15; // combined length + j->code_buffer <<= s; + j->code_bits -= s; + // decode into unzigzag'd location + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) ((r >> 8) * dequant[zig]); + } else { + int rs = stbi__jpeg_huff_decode(j, hac); + if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (rs != 0xf0) break; // end block + k += 16; + } else { + k += r; + // decode into unzigzag'd location + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) (stbi__extend_receive(j,s) * dequant[zig]); + } + } + } while (k < 64); + return 1; +} + +static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg *j, short data[64], stbi__huffman *hdc, int b) +{ + int diff,dc; + int t; + if (j->spec_end != 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + + if (j->succ_high == 0) { + // first scan for DC coefficient, must be first + memset(data,0,64*sizeof(data[0])); // 0 all the ac values now + t = stbi__jpeg_huff_decode(j, hdc); + if (t == -1) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + diff = t ? stbi__extend_receive(j, t) : 0; + + dc = j->img_comp[b].dc_pred + diff; + j->img_comp[b].dc_pred = dc; + data[0] = (short) (dc << j->succ_low); + } else { + // refinement scan for DC coefficient + if (stbi__jpeg_get_bit(j)) + data[0] += (short) (1 << j->succ_low); + } + return 1; +} + +// @OPTIMIZE: store non-zigzagged during the decode passes, +// and only de-zigzag when dequantizing +static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__huffman *hac, stbi__int16 *fac) +{ + int k; + if (j->spec_start == 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + + if (j->succ_high == 0) { + int shift = j->succ_low; + + if (j->eob_run) { + --j->eob_run; + return 1; + } + + k = j->spec_start; + do { + unsigned int zig; + int c,r,s; + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); + r = fac[c]; + if (r) { // fast-AC path + k += (r >> 4) & 15; // run + s = r & 15; // combined length + j->code_buffer <<= s; + j->code_bits -= s; + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) ((r >> 8) << shift); + } else { + int rs = stbi__jpeg_huff_decode(j, hac); + if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (r < 15) { + j->eob_run = (1 << r); + if (r) + j->eob_run += stbi__jpeg_get_bits(j, r); + --j->eob_run; + break; + } + k += 16; + } else { + k += r; + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) (stbi__extend_receive(j,s) << shift); + } + } + } while (k <= j->spec_end); + } else { + // refinement scan for these AC coefficients + + short bit = (short) (1 << j->succ_low); + + if (j->eob_run) { + --j->eob_run; + for (k = j->spec_start; k <= j->spec_end; ++k) { + short *p = &data[stbi__jpeg_dezigzag[k]]; + if (*p != 0) + if (stbi__jpeg_get_bit(j)) + if ((*p & bit)==0) { + if (*p > 0) + *p += bit; + else + *p -= bit; + } + } + } else { + k = j->spec_start; + do { + int r,s; + int rs = stbi__jpeg_huff_decode(j, hac); // @OPTIMIZE see if we can use the fast path here, advance-by-r is so slow, eh + if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (r < 15) { + j->eob_run = (1 << r) - 1; + if (r) + j->eob_run += stbi__jpeg_get_bits(j, r); + r = 64; // force end of block + } else { + // r=15 s=0 should write 16 0s, so we just do + // a run of 15 0s and then write s (which is 0), + // so we don't have to do anything special here + } + } else { + if (s != 1) return stbi__err("bad huffman code", "Corrupt JPEG"); + // sign bit + if (stbi__jpeg_get_bit(j)) + s = bit; + else + s = -bit; + } + + // advance by r + while (k <= j->spec_end) { + short *p = &data[stbi__jpeg_dezigzag[k++]]; + if (*p != 0) { + if (stbi__jpeg_get_bit(j)) + if ((*p & bit)==0) { + if (*p > 0) + *p += bit; + else + *p -= bit; + } + } else { + if (r == 0) { + *p = (short) s; + break; + } + --r; + } + } + } while (k <= j->spec_end); + } + } + return 1; +} + +// take a -128..127 value and stbi__clamp it and convert to 0..255 +stbi_inline static stbi_uc stbi__clamp(int x) +{ + // trick to use a single test to catch both cases + if ((unsigned int) x > 255) { + if (x < 0) return 0; + if (x > 255) return 255; + } + return (stbi_uc) x; +} + +#define stbi__f2f(x) ((int) (((x) * 4096 + 0.5))) +#define stbi__fsh(x) ((x) * 4096) + +// derived from jidctint -- DCT_ISLOW +#define STBI__IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \ + int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \ + p2 = s2; \ + p3 = s6; \ + p1 = (p2+p3) * stbi__f2f(0.5411961f); \ + t2 = p1 + p3*stbi__f2f(-1.847759065f); \ + t3 = p1 + p2*stbi__f2f( 0.765366865f); \ + p2 = s0; \ + p3 = s4; \ + t0 = stbi__fsh(p2+p3); \ + t1 = stbi__fsh(p2-p3); \ + x0 = t0+t3; \ + x3 = t0-t3; \ + x1 = t1+t2; \ + x2 = t1-t2; \ + t0 = s7; \ + t1 = s5; \ + t2 = s3; \ + t3 = s1; \ + p3 = t0+t2; \ + p4 = t1+t3; \ + p1 = t0+t3; \ + p2 = t1+t2; \ + p5 = (p3+p4)*stbi__f2f( 1.175875602f); \ + t0 = t0*stbi__f2f( 0.298631336f); \ + t1 = t1*stbi__f2f( 2.053119869f); \ + t2 = t2*stbi__f2f( 3.072711026f); \ + t3 = t3*stbi__f2f( 1.501321110f); \ + p1 = p5 + p1*stbi__f2f(-0.899976223f); \ + p2 = p5 + p2*stbi__f2f(-2.562915447f); \ + p3 = p3*stbi__f2f(-1.961570560f); \ + p4 = p4*stbi__f2f(-0.390180644f); \ + t3 += p1+p4; \ + t2 += p2+p3; \ + t1 += p2+p4; \ + t0 += p1+p3; + +static void stbi__idct_block(stbi_uc *out, int out_stride, short data[64]) +{ + int i,val[64],*v=val; + stbi_uc *o; + short *d = data; + + // columns + for (i=0; i < 8; ++i,++d, ++v) { + // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing + if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0 + && d[40]==0 && d[48]==0 && d[56]==0) { + // no shortcut 0 seconds + // (1|2|3|4|5|6|7)==0 0 seconds + // all separate -0.047 seconds + // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds + int dcterm = d[0]*4; + v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm; + } else { + STBI__IDCT_1D(d[ 0],d[ 8],d[16],d[24],d[32],d[40],d[48],d[56]) + // constants scaled things up by 1<<12; let's bring them back + // down, but keep 2 extra bits of precision + x0 += 512; x1 += 512; x2 += 512; x3 += 512; + v[ 0] = (x0+t3) >> 10; + v[56] = (x0-t3) >> 10; + v[ 8] = (x1+t2) >> 10; + v[48] = (x1-t2) >> 10; + v[16] = (x2+t1) >> 10; + v[40] = (x2-t1) >> 10; + v[24] = (x3+t0) >> 10; + v[32] = (x3-t0) >> 10; + } + } + + for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) { + // no fast case since the first 1D IDCT spread components out + STBI__IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7]) + // constants scaled things up by 1<<12, plus we had 1<<2 from first + // loop, plus horizontal and vertical each scale by sqrt(8) so together + // we've got an extra 1<<3, so 1<<17 total we need to remove. + // so we want to round that, which means adding 0.5 * 1<<17, + // aka 65536. Also, we'll end up with -128 to 127 that we want + // to encode as 0..255 by adding 128, so we'll add that before the shift + x0 += 65536 + (128<<17); + x1 += 65536 + (128<<17); + x2 += 65536 + (128<<17); + x3 += 65536 + (128<<17); + // tried computing the shifts into temps, or'ing the temps to see + // if any were out of range, but that was slower + o[0] = stbi__clamp((x0+t3) >> 17); + o[7] = stbi__clamp((x0-t3) >> 17); + o[1] = stbi__clamp((x1+t2) >> 17); + o[6] = stbi__clamp((x1-t2) >> 17); + o[2] = stbi__clamp((x2+t1) >> 17); + o[5] = stbi__clamp((x2-t1) >> 17); + o[3] = stbi__clamp((x3+t0) >> 17); + o[4] = stbi__clamp((x3-t0) >> 17); + } +} + +#ifdef STBI_SSE2 +// sse2 integer IDCT. not the fastest possible implementation but it +// produces bit-identical results to the generic C version so it's +// fully "transparent". +static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) +{ + // This is constructed to match our regular (generic) integer IDCT exactly. + __m128i row0, row1, row2, row3, row4, row5, row6, row7; + __m128i tmp; + + // dot product constant: even elems=x, odd elems=y + #define dct_const(x,y) _mm_setr_epi16((x),(y),(x),(y),(x),(y),(x),(y)) + + // out(0) = c0[even]*x + c0[odd]*y (c0, x, y 16-bit, out 32-bit) + // out(1) = c1[even]*x + c1[odd]*y + #define dct_rot(out0,out1, x,y,c0,c1) \ + __m128i c0##lo = _mm_unpacklo_epi16((x),(y)); \ + __m128i c0##hi = _mm_unpackhi_epi16((x),(y)); \ + __m128i out0##_l = _mm_madd_epi16(c0##lo, c0); \ + __m128i out0##_h = _mm_madd_epi16(c0##hi, c0); \ + __m128i out1##_l = _mm_madd_epi16(c0##lo, c1); \ + __m128i out1##_h = _mm_madd_epi16(c0##hi, c1) + + // out = in << 12 (in 16-bit, out 32-bit) + #define dct_widen(out, in) \ + __m128i out##_l = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), (in)), 4); \ + __m128i out##_h = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), (in)), 4) + + // wide add + #define dct_wadd(out, a, b) \ + __m128i out##_l = _mm_add_epi32(a##_l, b##_l); \ + __m128i out##_h = _mm_add_epi32(a##_h, b##_h) + + // wide sub + #define dct_wsub(out, a, b) \ + __m128i out##_l = _mm_sub_epi32(a##_l, b##_l); \ + __m128i out##_h = _mm_sub_epi32(a##_h, b##_h) + + // butterfly a/b, add bias, then shift by "s" and pack + #define dct_bfly32o(out0, out1, a,b,bias,s) \ + { \ + __m128i abiased_l = _mm_add_epi32(a##_l, bias); \ + __m128i abiased_h = _mm_add_epi32(a##_h, bias); \ + dct_wadd(sum, abiased, b); \ + dct_wsub(dif, abiased, b); \ + out0 = _mm_packs_epi32(_mm_srai_epi32(sum_l, s), _mm_srai_epi32(sum_h, s)); \ + out1 = _mm_packs_epi32(_mm_srai_epi32(dif_l, s), _mm_srai_epi32(dif_h, s)); \ + } + + // 8-bit interleave step (for transposes) + #define dct_interleave8(a, b) \ + tmp = a; \ + a = _mm_unpacklo_epi8(a, b); \ + b = _mm_unpackhi_epi8(tmp, b) + + // 16-bit interleave step (for transposes) + #define dct_interleave16(a, b) \ + tmp = a; \ + a = _mm_unpacklo_epi16(a, b); \ + b = _mm_unpackhi_epi16(tmp, b) + + #define dct_pass(bias,shift) \ + { \ + /* even part */ \ + dct_rot(t2e,t3e, row2,row6, rot0_0,rot0_1); \ + __m128i sum04 = _mm_add_epi16(row0, row4); \ + __m128i dif04 = _mm_sub_epi16(row0, row4); \ + dct_widen(t0e, sum04); \ + dct_widen(t1e, dif04); \ + dct_wadd(x0, t0e, t3e); \ + dct_wsub(x3, t0e, t3e); \ + dct_wadd(x1, t1e, t2e); \ + dct_wsub(x2, t1e, t2e); \ + /* odd part */ \ + dct_rot(y0o,y2o, row7,row3, rot2_0,rot2_1); \ + dct_rot(y1o,y3o, row5,row1, rot3_0,rot3_1); \ + __m128i sum17 = _mm_add_epi16(row1, row7); \ + __m128i sum35 = _mm_add_epi16(row3, row5); \ + dct_rot(y4o,y5o, sum17,sum35, rot1_0,rot1_1); \ + dct_wadd(x4, y0o, y4o); \ + dct_wadd(x5, y1o, y5o); \ + dct_wadd(x6, y2o, y5o); \ + dct_wadd(x7, y3o, y4o); \ + dct_bfly32o(row0,row7, x0,x7,bias,shift); \ + dct_bfly32o(row1,row6, x1,x6,bias,shift); \ + dct_bfly32o(row2,row5, x2,x5,bias,shift); \ + dct_bfly32o(row3,row4, x3,x4,bias,shift); \ + } + + __m128i rot0_0 = dct_const(stbi__f2f(0.5411961f), stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f)); + __m128i rot0_1 = dct_const(stbi__f2f(0.5411961f) + stbi__f2f( 0.765366865f), stbi__f2f(0.5411961f)); + __m128i rot1_0 = dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f), stbi__f2f(1.175875602f)); + __m128i rot1_1 = dct_const(stbi__f2f(1.175875602f), stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f)); + __m128i rot2_0 = dct_const(stbi__f2f(-1.961570560f) + stbi__f2f( 0.298631336f), stbi__f2f(-1.961570560f)); + __m128i rot2_1 = dct_const(stbi__f2f(-1.961570560f), stbi__f2f(-1.961570560f) + stbi__f2f( 3.072711026f)); + __m128i rot3_0 = dct_const(stbi__f2f(-0.390180644f) + stbi__f2f( 2.053119869f), stbi__f2f(-0.390180644f)); + __m128i rot3_1 = dct_const(stbi__f2f(-0.390180644f), stbi__f2f(-0.390180644f) + stbi__f2f( 1.501321110f)); + + // rounding biases in column/row passes, see stbi__idct_block for explanation. + __m128i bias_0 = _mm_set1_epi32(512); + __m128i bias_1 = _mm_set1_epi32(65536 + (128<<17)); + + // load + row0 = _mm_load_si128((const __m128i *) (data + 0*8)); + row1 = _mm_load_si128((const __m128i *) (data + 1*8)); + row2 = _mm_load_si128((const __m128i *) (data + 2*8)); + row3 = _mm_load_si128((const __m128i *) (data + 3*8)); + row4 = _mm_load_si128((const __m128i *) (data + 4*8)); + row5 = _mm_load_si128((const __m128i *) (data + 5*8)); + row6 = _mm_load_si128((const __m128i *) (data + 6*8)); + row7 = _mm_load_si128((const __m128i *) (data + 7*8)); + + // column pass + dct_pass(bias_0, 10); + + { + // 16bit 8x8 transpose pass 1 + dct_interleave16(row0, row4); + dct_interleave16(row1, row5); + dct_interleave16(row2, row6); + dct_interleave16(row3, row7); + + // transpose pass 2 + dct_interleave16(row0, row2); + dct_interleave16(row1, row3); + dct_interleave16(row4, row6); + dct_interleave16(row5, row7); + + // transpose pass 3 + dct_interleave16(row0, row1); + dct_interleave16(row2, row3); + dct_interleave16(row4, row5); + dct_interleave16(row6, row7); + } + + // row pass + dct_pass(bias_1, 17); + + { + // pack + __m128i p0 = _mm_packus_epi16(row0, row1); // a0a1a2a3...a7b0b1b2b3...b7 + __m128i p1 = _mm_packus_epi16(row2, row3); + __m128i p2 = _mm_packus_epi16(row4, row5); + __m128i p3 = _mm_packus_epi16(row6, row7); + + // 8bit 8x8 transpose pass 1 + dct_interleave8(p0, p2); // a0e0a1e1... + dct_interleave8(p1, p3); // c0g0c1g1... + + // transpose pass 2 + dct_interleave8(p0, p1); // a0c0e0g0... + dct_interleave8(p2, p3); // b0d0f0h0... + + // transpose pass 3 + dct_interleave8(p0, p2); // a0b0c0d0... + dct_interleave8(p1, p3); // a4b4c4d4... + + // store + _mm_storel_epi64((__m128i *) out, p0); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p0, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i *) out, p2); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p2, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i *) out, p1); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p1, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i *) out, p3); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p3, 0x4e)); + } + +#undef dct_const +#undef dct_rot +#undef dct_widen +#undef dct_wadd +#undef dct_wsub +#undef dct_bfly32o +#undef dct_interleave8 +#undef dct_interleave16 +#undef dct_pass +} + +#endif // STBI_SSE2 + +#ifdef STBI_NEON + +// NEON integer IDCT. should produce bit-identical +// results to the generic C version. +static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) +{ + int16x8_t row0, row1, row2, row3, row4, row5, row6, row7; + + int16x4_t rot0_0 = vdup_n_s16(stbi__f2f(0.5411961f)); + int16x4_t rot0_1 = vdup_n_s16(stbi__f2f(-1.847759065f)); + int16x4_t rot0_2 = vdup_n_s16(stbi__f2f( 0.765366865f)); + int16x4_t rot1_0 = vdup_n_s16(stbi__f2f( 1.175875602f)); + int16x4_t rot1_1 = vdup_n_s16(stbi__f2f(-0.899976223f)); + int16x4_t rot1_2 = vdup_n_s16(stbi__f2f(-2.562915447f)); + int16x4_t rot2_0 = vdup_n_s16(stbi__f2f(-1.961570560f)); + int16x4_t rot2_1 = vdup_n_s16(stbi__f2f(-0.390180644f)); + int16x4_t rot3_0 = vdup_n_s16(stbi__f2f( 0.298631336f)); + int16x4_t rot3_1 = vdup_n_s16(stbi__f2f( 2.053119869f)); + int16x4_t rot3_2 = vdup_n_s16(stbi__f2f( 3.072711026f)); + int16x4_t rot3_3 = vdup_n_s16(stbi__f2f( 1.501321110f)); + +#define dct_long_mul(out, inq, coeff) \ + int32x4_t out##_l = vmull_s16(vget_low_s16(inq), coeff); \ + int32x4_t out##_h = vmull_s16(vget_high_s16(inq), coeff) + +#define dct_long_mac(out, acc, inq, coeff) \ + int32x4_t out##_l = vmlal_s16(acc##_l, vget_low_s16(inq), coeff); \ + int32x4_t out##_h = vmlal_s16(acc##_h, vget_high_s16(inq), coeff) + +#define dct_widen(out, inq) \ + int32x4_t out##_l = vshll_n_s16(vget_low_s16(inq), 12); \ + int32x4_t out##_h = vshll_n_s16(vget_high_s16(inq), 12) + +// wide add +#define dct_wadd(out, a, b) \ + int32x4_t out##_l = vaddq_s32(a##_l, b##_l); \ + int32x4_t out##_h = vaddq_s32(a##_h, b##_h) + +// wide sub +#define dct_wsub(out, a, b) \ + int32x4_t out##_l = vsubq_s32(a##_l, b##_l); \ + int32x4_t out##_h = vsubq_s32(a##_h, b##_h) + +// butterfly a/b, then shift using "shiftop" by "s" and pack +#define dct_bfly32o(out0,out1, a,b,shiftop,s) \ + { \ + dct_wadd(sum, a, b); \ + dct_wsub(dif, a, b); \ + out0 = vcombine_s16(shiftop(sum_l, s), shiftop(sum_h, s)); \ + out1 = vcombine_s16(shiftop(dif_l, s), shiftop(dif_h, s)); \ + } + +#define dct_pass(shiftop, shift) \ + { \ + /* even part */ \ + int16x8_t sum26 = vaddq_s16(row2, row6); \ + dct_long_mul(p1e, sum26, rot0_0); \ + dct_long_mac(t2e, p1e, row6, rot0_1); \ + dct_long_mac(t3e, p1e, row2, rot0_2); \ + int16x8_t sum04 = vaddq_s16(row0, row4); \ + int16x8_t dif04 = vsubq_s16(row0, row4); \ + dct_widen(t0e, sum04); \ + dct_widen(t1e, dif04); \ + dct_wadd(x0, t0e, t3e); \ + dct_wsub(x3, t0e, t3e); \ + dct_wadd(x1, t1e, t2e); \ + dct_wsub(x2, t1e, t2e); \ + /* odd part */ \ + int16x8_t sum15 = vaddq_s16(row1, row5); \ + int16x8_t sum17 = vaddq_s16(row1, row7); \ + int16x8_t sum35 = vaddq_s16(row3, row5); \ + int16x8_t sum37 = vaddq_s16(row3, row7); \ + int16x8_t sumodd = vaddq_s16(sum17, sum35); \ + dct_long_mul(p5o, sumodd, rot1_0); \ + dct_long_mac(p1o, p5o, sum17, rot1_1); \ + dct_long_mac(p2o, p5o, sum35, rot1_2); \ + dct_long_mul(p3o, sum37, rot2_0); \ + dct_long_mul(p4o, sum15, rot2_1); \ + dct_wadd(sump13o, p1o, p3o); \ + dct_wadd(sump24o, p2o, p4o); \ + dct_wadd(sump23o, p2o, p3o); \ + dct_wadd(sump14o, p1o, p4o); \ + dct_long_mac(x4, sump13o, row7, rot3_0); \ + dct_long_mac(x5, sump24o, row5, rot3_1); \ + dct_long_mac(x6, sump23o, row3, rot3_2); \ + dct_long_mac(x7, sump14o, row1, rot3_3); \ + dct_bfly32o(row0,row7, x0,x7,shiftop,shift); \ + dct_bfly32o(row1,row6, x1,x6,shiftop,shift); \ + dct_bfly32o(row2,row5, x2,x5,shiftop,shift); \ + dct_bfly32o(row3,row4, x3,x4,shiftop,shift); \ + } + + // load + row0 = vld1q_s16(data + 0*8); + row1 = vld1q_s16(data + 1*8); + row2 = vld1q_s16(data + 2*8); + row3 = vld1q_s16(data + 3*8); + row4 = vld1q_s16(data + 4*8); + row5 = vld1q_s16(data + 5*8); + row6 = vld1q_s16(data + 6*8); + row7 = vld1q_s16(data + 7*8); + + // add DC bias + row0 = vaddq_s16(row0, vsetq_lane_s16(1024, vdupq_n_s16(0), 0)); + + // column pass + dct_pass(vrshrn_n_s32, 10); + + // 16bit 8x8 transpose + { +// these three map to a single VTRN.16, VTRN.32, and VSWP, respectively. +// whether compilers actually get this is another story, sadly. +#define dct_trn16(x, y) { int16x8x2_t t = vtrnq_s16(x, y); x = t.val[0]; y = t.val[1]; } +#define dct_trn32(x, y) { int32x4x2_t t = vtrnq_s32(vreinterpretq_s32_s16(x), vreinterpretq_s32_s16(y)); x = vreinterpretq_s16_s32(t.val[0]); y = vreinterpretq_s16_s32(t.val[1]); } +#define dct_trn64(x, y) { int16x8_t x0 = x; int16x8_t y0 = y; x = vcombine_s16(vget_low_s16(x0), vget_low_s16(y0)); y = vcombine_s16(vget_high_s16(x0), vget_high_s16(y0)); } + + // pass 1 + dct_trn16(row0, row1); // a0b0a2b2a4b4a6b6 + dct_trn16(row2, row3); + dct_trn16(row4, row5); + dct_trn16(row6, row7); + + // pass 2 + dct_trn32(row0, row2); // a0b0c0d0a4b4c4d4 + dct_trn32(row1, row3); + dct_trn32(row4, row6); + dct_trn32(row5, row7); + + // pass 3 + dct_trn64(row0, row4); // a0b0c0d0e0f0g0h0 + dct_trn64(row1, row5); + dct_trn64(row2, row6); + dct_trn64(row3, row7); + +#undef dct_trn16 +#undef dct_trn32 +#undef dct_trn64 + } + + // row pass + // vrshrn_n_s32 only supports shifts up to 16, we need + // 17. so do a non-rounding shift of 16 first then follow + // up with a rounding shift by 1. + dct_pass(vshrn_n_s32, 16); + + { + // pack and round + uint8x8_t p0 = vqrshrun_n_s16(row0, 1); + uint8x8_t p1 = vqrshrun_n_s16(row1, 1); + uint8x8_t p2 = vqrshrun_n_s16(row2, 1); + uint8x8_t p3 = vqrshrun_n_s16(row3, 1); + uint8x8_t p4 = vqrshrun_n_s16(row4, 1); + uint8x8_t p5 = vqrshrun_n_s16(row5, 1); + uint8x8_t p6 = vqrshrun_n_s16(row6, 1); + uint8x8_t p7 = vqrshrun_n_s16(row7, 1); + + // again, these can translate into one instruction, but often don't. +#define dct_trn8_8(x, y) { uint8x8x2_t t = vtrn_u8(x, y); x = t.val[0]; y = t.val[1]; } +#define dct_trn8_16(x, y) { uint16x4x2_t t = vtrn_u16(vreinterpret_u16_u8(x), vreinterpret_u16_u8(y)); x = vreinterpret_u8_u16(t.val[0]); y = vreinterpret_u8_u16(t.val[1]); } +#define dct_trn8_32(x, y) { uint32x2x2_t t = vtrn_u32(vreinterpret_u32_u8(x), vreinterpret_u32_u8(y)); x = vreinterpret_u8_u32(t.val[0]); y = vreinterpret_u8_u32(t.val[1]); } + + // sadly can't use interleaved stores here since we only write + // 8 bytes to each scan line! + + // 8x8 8-bit transpose pass 1 + dct_trn8_8(p0, p1); + dct_trn8_8(p2, p3); + dct_trn8_8(p4, p5); + dct_trn8_8(p6, p7); + + // pass 2 + dct_trn8_16(p0, p2); + dct_trn8_16(p1, p3); + dct_trn8_16(p4, p6); + dct_trn8_16(p5, p7); + + // pass 3 + dct_trn8_32(p0, p4); + dct_trn8_32(p1, p5); + dct_trn8_32(p2, p6); + dct_trn8_32(p3, p7); + + // store + vst1_u8(out, p0); out += out_stride; + vst1_u8(out, p1); out += out_stride; + vst1_u8(out, p2); out += out_stride; + vst1_u8(out, p3); out += out_stride; + vst1_u8(out, p4); out += out_stride; + vst1_u8(out, p5); out += out_stride; + vst1_u8(out, p6); out += out_stride; + vst1_u8(out, p7); + +#undef dct_trn8_8 +#undef dct_trn8_16 +#undef dct_trn8_32 + } + +#undef dct_long_mul +#undef dct_long_mac +#undef dct_widen +#undef dct_wadd +#undef dct_wsub +#undef dct_bfly32o +#undef dct_pass +} + +#endif // STBI_NEON + +#define STBI__MARKER_none 0xff +// if there's a pending marker from the entropy stream, return that +// otherwise, fetch from the stream and get a marker. if there's no +// marker, return 0xff, which is never a valid marker value +static stbi_uc stbi__get_marker(stbi__jpeg *j) +{ + stbi_uc x; + if (j->marker != STBI__MARKER_none) { x = j->marker; j->marker = STBI__MARKER_none; return x; } + x = stbi__get8(j->s); + if (x != 0xff) return STBI__MARKER_none; + while (x == 0xff) + x = stbi__get8(j->s); // consume repeated 0xff fill bytes + return x; +} + +// in each scan, we'll have scan_n components, and the order +// of the components is specified by order[] +#define STBI__RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7) + +// after a restart interval, stbi__jpeg_reset the entropy decoder and +// the dc prediction +static void stbi__jpeg_reset(stbi__jpeg *j) +{ + j->code_bits = 0; + j->code_buffer = 0; + j->nomore = 0; + j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = j->img_comp[3].dc_pred = 0; + j->marker = STBI__MARKER_none; + j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff; + j->eob_run = 0; + // no more than 1<<31 MCUs if no restart_interal? that's plenty safe, + // since we don't even allow 1<<30 pixels +} + +static int stbi__parse_entropy_coded_data(stbi__jpeg *z) +{ + stbi__jpeg_reset(z); + if (!z->progressive) { + if (z->scan_n == 1) { + int i,j; + STBI_SIMD_ALIGN(short, data[64]); + int n = z->order[0]; + // non-interleaved data, we just need to process one block at a time, + // in trivial scanline order + // number of blocks to do just depends on how many actual "pixels" this + // component has, independent of interleaved MCU blocking and such + int w = (z->img_comp[n].x+7) >> 3; + int h = (z->img_comp[n].y+7) >> 3; + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) { + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; + z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); + // every data block is an MCU, so countdown the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + // if it's NOT a restart, then just bail, so we get corrupt data + // rather than no data + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } else { // interleaved + int i,j,k,x,y; + STBI_SIMD_ALIGN(short, data[64]); + for (j=0; j < z->img_mcu_y; ++j) { + for (i=0; i < z->img_mcu_x; ++i) { + // scan an interleaved mcu... process scan_n components in order + for (k=0; k < z->scan_n; ++k) { + int n = z->order[k]; + // scan out an mcu's worth of this component; that's just determined + // by the basic H and V specified for the component + for (y=0; y < z->img_comp[n].v; ++y) { + for (x=0; x < z->img_comp[n].h; ++x) { + int x2 = (i*z->img_comp[n].h + x)*8; + int y2 = (j*z->img_comp[n].v + y)*8; + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; + z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data); + } + } + } + // after all interleaved components, that's an interleaved MCU, + // so now count down the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } + } else { + if (z->scan_n == 1) { + int i,j; + int n = z->order[0]; + // non-interleaved data, we just need to process one block at a time, + // in trivial scanline order + // number of blocks to do just depends on how many actual "pixels" this + // component has, independent of interleaved MCU blocking and such + int w = (z->img_comp[n].x+7) >> 3; + int h = (z->img_comp[n].y+7) >> 3; + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) { + short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); + if (z->spec_start == 0) { + if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) + return 0; + } else { + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block_prog_ac(z, data, &z->huff_ac[ha], z->fast_ac[ha])) + return 0; + } + // every data block is an MCU, so countdown the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } else { // interleaved + int i,j,k,x,y; + for (j=0; j < z->img_mcu_y; ++j) { + for (i=0; i < z->img_mcu_x; ++i) { + // scan an interleaved mcu... process scan_n components in order + for (k=0; k < z->scan_n; ++k) { + int n = z->order[k]; + // scan out an mcu's worth of this component; that's just determined + // by the basic H and V specified for the component + for (y=0; y < z->img_comp[n].v; ++y) { + for (x=0; x < z->img_comp[n].h; ++x) { + int x2 = (i*z->img_comp[n].h + x); + int y2 = (j*z->img_comp[n].v + y); + short *data = z->img_comp[n].coeff + 64 * (x2 + y2 * z->img_comp[n].coeff_w); + if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) + return 0; + } + } + } + // after all interleaved components, that's an interleaved MCU, + // so now count down the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } + } +} + +static void stbi__jpeg_dequantize(short *data, stbi__uint16 *dequant) +{ + int i; + for (i=0; i < 64; ++i) + data[i] *= dequant[i]; +} + +static void stbi__jpeg_finish(stbi__jpeg *z) +{ + if (z->progressive) { + // dequantize and idct the data + int i,j,n; + for (n=0; n < z->s->img_n; ++n) { + int w = (z->img_comp[n].x+7) >> 3; + int h = (z->img_comp[n].y+7) >> 3; + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) { + short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); + stbi__jpeg_dequantize(data, z->dequant[z->img_comp[n].tq]); + z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); + } + } + } + } +} + +static int stbi__process_marker(stbi__jpeg *z, int m) +{ + int L; + switch (m) { + case STBI__MARKER_none: // no marker found + return stbi__err("expected marker","Corrupt JPEG"); + + case 0xDD: // DRI - specify restart interval + if (stbi__get16be(z->s) != 4) return stbi__err("bad DRI len","Corrupt JPEG"); + z->restart_interval = stbi__get16be(z->s); + return 1; + + case 0xDB: // DQT - define quantization table + L = stbi__get16be(z->s)-2; + while (L > 0) { + int q = stbi__get8(z->s); + int p = q >> 4, sixteen = (p != 0); + int t = q & 15,i; + if (p != 0 && p != 1) return stbi__err("bad DQT type","Corrupt JPEG"); + if (t > 3) return stbi__err("bad DQT table","Corrupt JPEG"); + + for (i=0; i < 64; ++i) + z->dequant[t][stbi__jpeg_dezigzag[i]] = (stbi__uint16)(sixteen ? stbi__get16be(z->s) : stbi__get8(z->s)); + L -= (sixteen ? 129 : 65); + } + return L==0; + + case 0xC4: // DHT - define huffman table + L = stbi__get16be(z->s)-2; + while (L > 0) { + stbi_uc *v; + int sizes[16],i,n=0; + int q = stbi__get8(z->s); + int tc = q >> 4; + int th = q & 15; + if (tc > 1 || th > 3) return stbi__err("bad DHT header","Corrupt JPEG"); + for (i=0; i < 16; ++i) { + sizes[i] = stbi__get8(z->s); + n += sizes[i]; + } + L -= 17; + if (tc == 0) { + if (!stbi__build_huffman(z->huff_dc+th, sizes)) return 0; + v = z->huff_dc[th].values; + } else { + if (!stbi__build_huffman(z->huff_ac+th, sizes)) return 0; + v = z->huff_ac[th].values; + } + for (i=0; i < n; ++i) + v[i] = stbi__get8(z->s); + if (tc != 0) + stbi__build_fast_ac(z->fast_ac[th], z->huff_ac + th); + L -= n; + } + return L==0; + } + + // check for comment block or APP blocks + if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) { + L = stbi__get16be(z->s); + if (L < 2) { + if (m == 0xFE) + return stbi__err("bad COM len","Corrupt JPEG"); + else + return stbi__err("bad APP len","Corrupt JPEG"); + } + L -= 2; + + if (m == 0xE0 && L >= 5) { // JFIF APP0 segment + static const unsigned char tag[5] = {'J','F','I','F','\0'}; + int ok = 1; + int i; + for (i=0; i < 5; ++i) + if (stbi__get8(z->s) != tag[i]) + ok = 0; + L -= 5; + if (ok) + z->jfif = 1; + } else if (m == 0xEE && L >= 12) { // Adobe APP14 segment + static const unsigned char tag[6] = {'A','d','o','b','e','\0'}; + int ok = 1; + int i; + for (i=0; i < 6; ++i) + if (stbi__get8(z->s) != tag[i]) + ok = 0; + L -= 6; + if (ok) { + stbi__get8(z->s); // version + stbi__get16be(z->s); // flags0 + stbi__get16be(z->s); // flags1 + z->app14_color_transform = stbi__get8(z->s); // color transform + L -= 6; + } + } + + stbi__skip(z->s, L); + return 1; + } + + return stbi__err("unknown marker","Corrupt JPEG"); +} + +// after we see SOS +static int stbi__process_scan_header(stbi__jpeg *z) +{ + int i; + int Ls = stbi__get16be(z->s); + z->scan_n = stbi__get8(z->s); + if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return stbi__err("bad SOS component count","Corrupt JPEG"); + if (Ls != 6+2*z->scan_n) return stbi__err("bad SOS len","Corrupt JPEG"); + for (i=0; i < z->scan_n; ++i) { + int id = stbi__get8(z->s), which; + int q = stbi__get8(z->s); + for (which = 0; which < z->s->img_n; ++which) + if (z->img_comp[which].id == id) + break; + if (which == z->s->img_n) return 0; // no match + z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return stbi__err("bad DC huff","Corrupt JPEG"); + z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return stbi__err("bad AC huff","Corrupt JPEG"); + z->order[i] = which; + } + + { + int aa; + z->spec_start = stbi__get8(z->s); + z->spec_end = stbi__get8(z->s); // should be 63, but might be 0 + aa = stbi__get8(z->s); + z->succ_high = (aa >> 4); + z->succ_low = (aa & 15); + if (z->progressive) { + if (z->spec_start > 63 || z->spec_end > 63 || z->spec_start > z->spec_end || z->succ_high > 13 || z->succ_low > 13) + return stbi__err("bad SOS", "Corrupt JPEG"); + } else { + if (z->spec_start != 0) return stbi__err("bad SOS","Corrupt JPEG"); + if (z->succ_high != 0 || z->succ_low != 0) return stbi__err("bad SOS","Corrupt JPEG"); + z->spec_end = 63; + } + } + + return 1; +} + +static int stbi__free_jpeg_components(stbi__jpeg *z, int ncomp, int why) +{ + int i; + for (i=0; i < ncomp; ++i) { + if (z->img_comp[i].raw_data) { + STBI_FREE(z->img_comp[i].raw_data); + z->img_comp[i].raw_data = NULL; + z->img_comp[i].data = NULL; + } + if (z->img_comp[i].raw_coeff) { + STBI_FREE(z->img_comp[i].raw_coeff); + z->img_comp[i].raw_coeff = 0; + z->img_comp[i].coeff = 0; + } + if (z->img_comp[i].linebuf) { + STBI_FREE(z->img_comp[i].linebuf); + z->img_comp[i].linebuf = NULL; + } + } + return why; +} + +static int stbi__process_frame_header(stbi__jpeg *z, int scan) +{ + stbi__context *s = z->s; + int Lf,p,i,q, h_max=1,v_max=1,c; + Lf = stbi__get16be(s); if (Lf < 11) return stbi__err("bad SOF len","Corrupt JPEG"); // JPEG + p = stbi__get8(s); if (p != 8) return stbi__err("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline + s->img_y = stbi__get16be(s); if (s->img_y == 0) return stbi__err("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG + s->img_x = stbi__get16be(s); if (s->img_x == 0) return stbi__err("0 width","Corrupt JPEG"); // JPEG requires + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + c = stbi__get8(s); + if (c != 3 && c != 1 && c != 4) return stbi__err("bad component count","Corrupt JPEG"); + s->img_n = c; + for (i=0; i < c; ++i) { + z->img_comp[i].data = NULL; + z->img_comp[i].linebuf = NULL; + } + + if (Lf != 8+3*s->img_n) return stbi__err("bad SOF len","Corrupt JPEG"); + + z->rgb = 0; + for (i=0; i < s->img_n; ++i) { + static const unsigned char rgb[3] = { 'R', 'G', 'B' }; + z->img_comp[i].id = stbi__get8(s); + if (s->img_n == 3 && z->img_comp[i].id == rgb[i]) + ++z->rgb; + q = stbi__get8(s); + z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return stbi__err("bad H","Corrupt JPEG"); + z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return stbi__err("bad V","Corrupt JPEG"); + z->img_comp[i].tq = stbi__get8(s); if (z->img_comp[i].tq > 3) return stbi__err("bad TQ","Corrupt JPEG"); + } + + if (scan != STBI__SCAN_load) return 1; + + if (!stbi__mad3sizes_valid(s->img_x, s->img_y, s->img_n, 0)) return stbi__err("too large", "Image too large to decode"); + + for (i=0; i < s->img_n; ++i) { + if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h; + if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v; + } + + // compute interleaved mcu info + z->img_h_max = h_max; + z->img_v_max = v_max; + z->img_mcu_w = h_max * 8; + z->img_mcu_h = v_max * 8; + // these sizes can't be more than 17 bits + z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w; + z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h; + + for (i=0; i < s->img_n; ++i) { + // number of effective pixels (e.g. for non-interleaved MCU) + z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max; + z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max; + // to simplify generation, we'll allocate enough memory to decode + // the bogus oversized data from using interleaved MCUs and their + // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't + // discard the extra data until colorspace conversion + // + // img_mcu_x, img_mcu_y: <=17 bits; comp[i].h and .v are <=4 (checked earlier) + // so these muls can't overflow with 32-bit ints (which we require) + z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8; + z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8; + z->img_comp[i].coeff = 0; + z->img_comp[i].raw_coeff = 0; + z->img_comp[i].linebuf = NULL; + z->img_comp[i].raw_data = stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15); + if (z->img_comp[i].raw_data == NULL) + return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory")); + // align blocks for idct using mmx/sse + z->img_comp[i].data = (stbi_uc*) (((size_t) z->img_comp[i].raw_data + 15) & ~15); + if (z->progressive) { + // w2, h2 are multiples of 8 (see above) + z->img_comp[i].coeff_w = z->img_comp[i].w2 / 8; + z->img_comp[i].coeff_h = z->img_comp[i].h2 / 8; + z->img_comp[i].raw_coeff = stbi__malloc_mad3(z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15); + if (z->img_comp[i].raw_coeff == NULL) + return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory")); + z->img_comp[i].coeff = (short*) (((size_t) z->img_comp[i].raw_coeff + 15) & ~15); + } + } + + return 1; +} + +// use comparisons since in some cases we handle more than one case (e.g. SOF) +#define stbi__DNL(x) ((x) == 0xdc) +#define stbi__SOI(x) ((x) == 0xd8) +#define stbi__EOI(x) ((x) == 0xd9) +#define stbi__SOF(x) ((x) == 0xc0 || (x) == 0xc1 || (x) == 0xc2) +#define stbi__SOS(x) ((x) == 0xda) + +#define stbi__SOF_progressive(x) ((x) == 0xc2) + +static int stbi__decode_jpeg_header(stbi__jpeg *z, int scan) +{ + int m; + z->jfif = 0; + z->app14_color_transform = -1; // valid values are 0,1,2 + z->marker = STBI__MARKER_none; // initialize cached marker to empty + m = stbi__get_marker(z); + if (!stbi__SOI(m)) return stbi__err("no SOI","Corrupt JPEG"); + if (scan == STBI__SCAN_type) return 1; + m = stbi__get_marker(z); + while (!stbi__SOF(m)) { + if (!stbi__process_marker(z,m)) return 0; + m = stbi__get_marker(z); + while (m == STBI__MARKER_none) { + // some files have extra padding after their blocks, so ok, we'll scan + if (stbi__at_eof(z->s)) return stbi__err("no SOF", "Corrupt JPEG"); + m = stbi__get_marker(z); + } + } + z->progressive = stbi__SOF_progressive(m); + if (!stbi__process_frame_header(z, scan)) return 0; + return 1; +} + +// decode image to YCbCr format +static int stbi__decode_jpeg_image(stbi__jpeg *j) +{ + int m; + for (m = 0; m < 4; m++) { + j->img_comp[m].raw_data = NULL; + j->img_comp[m].raw_coeff = NULL; + } + j->restart_interval = 0; + if (!stbi__decode_jpeg_header(j, STBI__SCAN_load)) return 0; + m = stbi__get_marker(j); + while (!stbi__EOI(m)) { + if (stbi__SOS(m)) { + if (!stbi__process_scan_header(j)) return 0; + if (!stbi__parse_entropy_coded_data(j)) return 0; + if (j->marker == STBI__MARKER_none ) { + // handle 0s at the end of image data from IP Kamera 9060 + while (!stbi__at_eof(j->s)) { + int x = stbi__get8(j->s); + if (x == 255) { + j->marker = stbi__get8(j->s); + break; + } + } + // if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 0 + } + } else if (stbi__DNL(m)) { + int Ld = stbi__get16be(j->s); + stbi__uint32 NL = stbi__get16be(j->s); + if (Ld != 4) return stbi__err("bad DNL len", "Corrupt JPEG"); + if (NL != j->s->img_y) return stbi__err("bad DNL height", "Corrupt JPEG"); + } else { + if (!stbi__process_marker(j, m)) return 0; + } + m = stbi__get_marker(j); + } + if (j->progressive) + stbi__jpeg_finish(j); + return 1; +} + +// static jfif-centered resampling (across block boundaries) + +typedef stbi_uc *(*resample_row_func)(stbi_uc *out, stbi_uc *in0, stbi_uc *in1, + int w, int hs); + +#define stbi__div4(x) ((stbi_uc) ((x) >> 2)) + +static stbi_uc *resample_row_1(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + STBI_NOTUSED(out); + STBI_NOTUSED(in_far); + STBI_NOTUSED(w); + STBI_NOTUSED(hs); + return in_near; +} + +static stbi_uc* stbi__resample_row_v_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate two samples vertically for every one in input + int i; + STBI_NOTUSED(hs); + for (i=0; i < w; ++i) + out[i] = stbi__div4(3*in_near[i] + in_far[i] + 2); + return out; +} + +static stbi_uc* stbi__resample_row_h_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate two samples horizontally for every one in input + int i; + stbi_uc *input = in_near; + + if (w == 1) { + // if only one sample, can't do any interpolation + out[0] = out[1] = input[0]; + return out; + } + + out[0] = input[0]; + out[1] = stbi__div4(input[0]*3 + input[1] + 2); + for (i=1; i < w-1; ++i) { + int n = 3*input[i]+2; + out[i*2+0] = stbi__div4(n+input[i-1]); + out[i*2+1] = stbi__div4(n+input[i+1]); + } + out[i*2+0] = stbi__div4(input[w-2]*3 + input[w-1] + 2); + out[i*2+1] = input[w-1]; + + STBI_NOTUSED(in_far); + STBI_NOTUSED(hs); + + return out; +} + +#define stbi__div16(x) ((stbi_uc) ((x) >> 4)) + +static stbi_uc *stbi__resample_row_hv_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate 2x2 samples for every one in input + int i,t0,t1; + if (w == 1) { + out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); + return out; + } + + t1 = 3*in_near[0] + in_far[0]; + out[0] = stbi__div4(t1+2); + for (i=1; i < w; ++i) { + t0 = t1; + t1 = 3*in_near[i]+in_far[i]; + out[i*2-1] = stbi__div16(3*t0 + t1 + 8); + out[i*2 ] = stbi__div16(3*t1 + t0 + 8); + } + out[w*2-1] = stbi__div4(t1+2); + + STBI_NOTUSED(hs); + + return out; +} + +#if defined(STBI_SSE2) || defined(STBI_NEON) +static stbi_uc *stbi__resample_row_hv_2_simd(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate 2x2 samples for every one in input + int i=0,t0,t1; + + if (w == 1) { + out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); + return out; + } + + t1 = 3*in_near[0] + in_far[0]; + // process groups of 8 pixels for as long as we can. + // note we can't handle the last pixel in a row in this loop + // because we need to handle the filter boundary conditions. + for (; i < ((w-1) & ~7); i += 8) { +#if defined(STBI_SSE2) + // load and perform the vertical filtering pass + // this uses 3*x + y = 4*x + (y - x) + __m128i zero = _mm_setzero_si128(); + __m128i farb = _mm_loadl_epi64((__m128i *) (in_far + i)); + __m128i nearb = _mm_loadl_epi64((__m128i *) (in_near + i)); + __m128i farw = _mm_unpacklo_epi8(farb, zero); + __m128i nearw = _mm_unpacklo_epi8(nearb, zero); + __m128i diff = _mm_sub_epi16(farw, nearw); + __m128i nears = _mm_slli_epi16(nearw, 2); + __m128i curr = _mm_add_epi16(nears, diff); // current row + + // horizontal filter works the same based on shifted vers of current + // row. "prev" is current row shifted right by 1 pixel; we need to + // insert the previous pixel value (from t1). + // "next" is current row shifted left by 1 pixel, with first pixel + // of next block of 8 pixels added in. + __m128i prv0 = _mm_slli_si128(curr, 2); + __m128i nxt0 = _mm_srli_si128(curr, 2); + __m128i prev = _mm_insert_epi16(prv0, t1, 0); + __m128i next = _mm_insert_epi16(nxt0, 3*in_near[i+8] + in_far[i+8], 7); + + // horizontal filter, polyphase implementation since it's convenient: + // even pixels = 3*cur + prev = cur*4 + (prev - cur) + // odd pixels = 3*cur + next = cur*4 + (next - cur) + // note the shared term. + __m128i bias = _mm_set1_epi16(8); + __m128i curs = _mm_slli_epi16(curr, 2); + __m128i prvd = _mm_sub_epi16(prev, curr); + __m128i nxtd = _mm_sub_epi16(next, curr); + __m128i curb = _mm_add_epi16(curs, bias); + __m128i even = _mm_add_epi16(prvd, curb); + __m128i odd = _mm_add_epi16(nxtd, curb); + + // interleave even and odd pixels, then undo scaling. + __m128i int0 = _mm_unpacklo_epi16(even, odd); + __m128i int1 = _mm_unpackhi_epi16(even, odd); + __m128i de0 = _mm_srli_epi16(int0, 4); + __m128i de1 = _mm_srli_epi16(int1, 4); + + // pack and write output + __m128i outv = _mm_packus_epi16(de0, de1); + _mm_storeu_si128((__m128i *) (out + i*2), outv); +#elif defined(STBI_NEON) + // load and perform the vertical filtering pass + // this uses 3*x + y = 4*x + (y - x) + uint8x8_t farb = vld1_u8(in_far + i); + uint8x8_t nearb = vld1_u8(in_near + i); + int16x8_t diff = vreinterpretq_s16_u16(vsubl_u8(farb, nearb)); + int16x8_t nears = vreinterpretq_s16_u16(vshll_n_u8(nearb, 2)); + int16x8_t curr = vaddq_s16(nears, diff); // current row + + // horizontal filter works the same based on shifted vers of current + // row. "prev" is current row shifted right by 1 pixel; we need to + // insert the previous pixel value (from t1). + // "next" is current row shifted left by 1 pixel, with first pixel + // of next block of 8 pixels added in. + int16x8_t prv0 = vextq_s16(curr, curr, 7); + int16x8_t nxt0 = vextq_s16(curr, curr, 1); + int16x8_t prev = vsetq_lane_s16(t1, prv0, 0); + int16x8_t next = vsetq_lane_s16(3*in_near[i+8] + in_far[i+8], nxt0, 7); + + // horizontal filter, polyphase implementation since it's convenient: + // even pixels = 3*cur + prev = cur*4 + (prev - cur) + // odd pixels = 3*cur + next = cur*4 + (next - cur) + // note the shared term. + int16x8_t curs = vshlq_n_s16(curr, 2); + int16x8_t prvd = vsubq_s16(prev, curr); + int16x8_t nxtd = vsubq_s16(next, curr); + int16x8_t even = vaddq_s16(curs, prvd); + int16x8_t odd = vaddq_s16(curs, nxtd); + + // undo scaling and round, then store with even/odd phases interleaved + uint8x8x2_t o; + o.val[0] = vqrshrun_n_s16(even, 4); + o.val[1] = vqrshrun_n_s16(odd, 4); + vst2_u8(out + i*2, o); +#endif + + // "previous" value for next iter + t1 = 3*in_near[i+7] + in_far[i+7]; + } + + t0 = t1; + t1 = 3*in_near[i] + in_far[i]; + out[i*2] = stbi__div16(3*t1 + t0 + 8); + + for (++i; i < w; ++i) { + t0 = t1; + t1 = 3*in_near[i]+in_far[i]; + out[i*2-1] = stbi__div16(3*t0 + t1 + 8); + out[i*2 ] = stbi__div16(3*t1 + t0 + 8); + } + out[w*2-1] = stbi__div4(t1+2); + + STBI_NOTUSED(hs); + + return out; +} +#endif + +static stbi_uc *stbi__resample_row_generic(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // resample with nearest-neighbor + int i,j; + STBI_NOTUSED(in_far); + for (i=0; i < w; ++i) + for (j=0; j < hs; ++j) + out[i*hs+j] = in_near[i]; + return out; +} + +// this is a reduced-precision calculation of YCbCr-to-RGB introduced +// to make sure the code produces the same results in both SIMD and scalar +#define stbi__float2fixed(x) (((int) ((x) * 4096.0f + 0.5f)) << 8) +static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step) +{ + int i; + for (i=0; i < count; ++i) { + int y_fixed = (y[i] << 20) + (1<<19); // rounding + int r,g,b; + int cr = pcr[i] - 128; + int cb = pcb[i] - 128; + r = y_fixed + cr* stbi__float2fixed(1.40200f); + g = y_fixed + (cr*-stbi__float2fixed(0.71414f)) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); + b = y_fixed + cb* stbi__float2fixed(1.77200f); + r >>= 20; + g >>= 20; + b >>= 20; + if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } + if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } + if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } + out[0] = (stbi_uc)r; + out[1] = (stbi_uc)g; + out[2] = (stbi_uc)b; + out[3] = 255; + out += step; + } +} + +#if defined(STBI_SSE2) || defined(STBI_NEON) +static void stbi__YCbCr_to_RGB_simd(stbi_uc *out, stbi_uc const *y, stbi_uc const *pcb, stbi_uc const *pcr, int count, int step) +{ + int i = 0; + +#ifdef STBI_SSE2 + // step == 3 is pretty ugly on the final interleave, and i'm not convinced + // it's useful in practice (you wouldn't use it for textures, for example). + // so just accelerate step == 4 case. + if (step == 4) { + // this is a fairly straightforward implementation and not super-optimized. + __m128i signflip = _mm_set1_epi8(-0x80); + __m128i cr_const0 = _mm_set1_epi16( (short) ( 1.40200f*4096.0f+0.5f)); + __m128i cr_const1 = _mm_set1_epi16( - (short) ( 0.71414f*4096.0f+0.5f)); + __m128i cb_const0 = _mm_set1_epi16( - (short) ( 0.34414f*4096.0f+0.5f)); + __m128i cb_const1 = _mm_set1_epi16( (short) ( 1.77200f*4096.0f+0.5f)); + __m128i y_bias = _mm_set1_epi8((char) (unsigned char) 128); + __m128i xw = _mm_set1_epi16(255); // alpha channel + + for (; i+7 < count; i += 8) { + // load + __m128i y_bytes = _mm_loadl_epi64((__m128i *) (y+i)); + __m128i cr_bytes = _mm_loadl_epi64((__m128i *) (pcr+i)); + __m128i cb_bytes = _mm_loadl_epi64((__m128i *) (pcb+i)); + __m128i cr_biased = _mm_xor_si128(cr_bytes, signflip); // -128 + __m128i cb_biased = _mm_xor_si128(cb_bytes, signflip); // -128 + + // unpack to short (and left-shift cr, cb by 8) + __m128i yw = _mm_unpacklo_epi8(y_bias, y_bytes); + __m128i crw = _mm_unpacklo_epi8(_mm_setzero_si128(), cr_biased); + __m128i cbw = _mm_unpacklo_epi8(_mm_setzero_si128(), cb_biased); + + // color transform + __m128i yws = _mm_srli_epi16(yw, 4); + __m128i cr0 = _mm_mulhi_epi16(cr_const0, crw); + __m128i cb0 = _mm_mulhi_epi16(cb_const0, cbw); + __m128i cb1 = _mm_mulhi_epi16(cbw, cb_const1); + __m128i cr1 = _mm_mulhi_epi16(crw, cr_const1); + __m128i rws = _mm_add_epi16(cr0, yws); + __m128i gwt = _mm_add_epi16(cb0, yws); + __m128i bws = _mm_add_epi16(yws, cb1); + __m128i gws = _mm_add_epi16(gwt, cr1); + + // descale + __m128i rw = _mm_srai_epi16(rws, 4); + __m128i bw = _mm_srai_epi16(bws, 4); + __m128i gw = _mm_srai_epi16(gws, 4); + + // back to byte, set up for transpose + __m128i brb = _mm_packus_epi16(rw, bw); + __m128i gxb = _mm_packus_epi16(gw, xw); + + // transpose to interleave channels + __m128i t0 = _mm_unpacklo_epi8(brb, gxb); + __m128i t1 = _mm_unpackhi_epi8(brb, gxb); + __m128i o0 = _mm_unpacklo_epi16(t0, t1); + __m128i o1 = _mm_unpackhi_epi16(t0, t1); + + // store + _mm_storeu_si128((__m128i *) (out + 0), o0); + _mm_storeu_si128((__m128i *) (out + 16), o1); + out += 32; + } + } +#endif + +#ifdef STBI_NEON + // in this version, step=3 support would be easy to add. but is there demand? + if (step == 4) { + // this is a fairly straightforward implementation and not super-optimized. + uint8x8_t signflip = vdup_n_u8(0x80); + int16x8_t cr_const0 = vdupq_n_s16( (short) ( 1.40200f*4096.0f+0.5f)); + int16x8_t cr_const1 = vdupq_n_s16( - (short) ( 0.71414f*4096.0f+0.5f)); + int16x8_t cb_const0 = vdupq_n_s16( - (short) ( 0.34414f*4096.0f+0.5f)); + int16x8_t cb_const1 = vdupq_n_s16( (short) ( 1.77200f*4096.0f+0.5f)); + + for (; i+7 < count; i += 8) { + // load + uint8x8_t y_bytes = vld1_u8(y + i); + uint8x8_t cr_bytes = vld1_u8(pcr + i); + uint8x8_t cb_bytes = vld1_u8(pcb + i); + int8x8_t cr_biased = vreinterpret_s8_u8(vsub_u8(cr_bytes, signflip)); + int8x8_t cb_biased = vreinterpret_s8_u8(vsub_u8(cb_bytes, signflip)); + + // expand to s16 + int16x8_t yws = vreinterpretq_s16_u16(vshll_n_u8(y_bytes, 4)); + int16x8_t crw = vshll_n_s8(cr_biased, 7); + int16x8_t cbw = vshll_n_s8(cb_biased, 7); + + // color transform + int16x8_t cr0 = vqdmulhq_s16(crw, cr_const0); + int16x8_t cb0 = vqdmulhq_s16(cbw, cb_const0); + int16x8_t cr1 = vqdmulhq_s16(crw, cr_const1); + int16x8_t cb1 = vqdmulhq_s16(cbw, cb_const1); + int16x8_t rws = vaddq_s16(yws, cr0); + int16x8_t gws = vaddq_s16(vaddq_s16(yws, cb0), cr1); + int16x8_t bws = vaddq_s16(yws, cb1); + + // undo scaling, round, convert to byte + uint8x8x4_t o; + o.val[0] = vqrshrun_n_s16(rws, 4); + o.val[1] = vqrshrun_n_s16(gws, 4); + o.val[2] = vqrshrun_n_s16(bws, 4); + o.val[3] = vdup_n_u8(255); + + // store, interleaving r/g/b/a + vst4_u8(out, o); + out += 8*4; + } + } +#endif + + for (; i < count; ++i) { + int y_fixed = (y[i] << 20) + (1<<19); // rounding + int r,g,b; + int cr = pcr[i] - 128; + int cb = pcb[i] - 128; + r = y_fixed + cr* stbi__float2fixed(1.40200f); + g = y_fixed + cr*-stbi__float2fixed(0.71414f) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); + b = y_fixed + cb* stbi__float2fixed(1.77200f); + r >>= 20; + g >>= 20; + b >>= 20; + if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } + if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } + if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } + out[0] = (stbi_uc)r; + out[1] = (stbi_uc)g; + out[2] = (stbi_uc)b; + out[3] = 255; + out += step; + } +} +#endif + +// set up the kernels +static void stbi__setup_jpeg(stbi__jpeg *j) +{ + j->idct_block_kernel = stbi__idct_block; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_row; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2; + +#ifdef STBI_SSE2 + if (stbi__sse2_available()) { + j->idct_block_kernel = stbi__idct_simd; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; + } +#endif + +#ifdef STBI_NEON + j->idct_block_kernel = stbi__idct_simd; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; +#endif +} + +// clean up the temporary component buffers +static void stbi__cleanup_jpeg(stbi__jpeg *j) +{ + stbi__free_jpeg_components(j, j->s->img_n, 0); +} + +typedef struct +{ + resample_row_func resample; + stbi_uc *line0,*line1; + int hs,vs; // expansion factor in each axis + int w_lores; // horizontal pixels pre-expansion + int ystep; // how far through vertical expansion we are + int ypos; // which pre-expansion row we're on +} stbi__resample; + +// fast 0..255 * 0..255 => 0..255 rounded multiplication +static stbi_uc stbi__blinn_8x8(stbi_uc x, stbi_uc y) +{ + unsigned int t = x*y + 128; + return (stbi_uc) ((t + (t >>8)) >> 8); +} + +static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp, int req_comp) +{ + int n, decode_n, is_rgb; + z->s->img_n = 0; // make stbi__cleanup_jpeg safe + + // validate req_comp + if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); + + // load a jpeg image from whichever source, but leave in YCbCr format + if (!stbi__decode_jpeg_image(z)) { stbi__cleanup_jpeg(z); return NULL; } + + // determine actual number of components to generate + n = req_comp ? req_comp : z->s->img_n >= 3 ? 3 : 1; + + is_rgb = z->s->img_n == 3 && (z->rgb == 3 || (z->app14_color_transform == 0 && !z->jfif)); + + if (z->s->img_n == 3 && n < 3 && !is_rgb) + decode_n = 1; + else + decode_n = z->s->img_n; + + // resample and color-convert + { + int k; + unsigned int i,j; + stbi_uc *output; + stbi_uc *coutput[4] = { NULL, NULL, NULL, NULL }; + + stbi__resample res_comp[4]; + + for (k=0; k < decode_n; ++k) { + stbi__resample *r = &res_comp[k]; + + // allocate line buffer big enough for upsampling off the edges + // with upsample factor of 4 + z->img_comp[k].linebuf = (stbi_uc *) stbi__malloc(z->s->img_x + 3); + if (!z->img_comp[k].linebuf) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } + + r->hs = z->img_h_max / z->img_comp[k].h; + r->vs = z->img_v_max / z->img_comp[k].v; + r->ystep = r->vs >> 1; + r->w_lores = (z->s->img_x + r->hs-1) / r->hs; + r->ypos = 0; + r->line0 = r->line1 = z->img_comp[k].data; + + if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1; + else if (r->hs == 1 && r->vs == 2) r->resample = stbi__resample_row_v_2; + else if (r->hs == 2 && r->vs == 1) r->resample = stbi__resample_row_h_2; + else if (r->hs == 2 && r->vs == 2) r->resample = z->resample_row_hv_2_kernel; + else r->resample = stbi__resample_row_generic; + } + + // can't error after this so, this is safe + output = (stbi_uc *) stbi__malloc_mad3(n, z->s->img_x, z->s->img_y, 1); + if (!output) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } + + // now go ahead and resample + for (j=0; j < z->s->img_y; ++j) { + stbi_uc *out = output + n * z->s->img_x * j; + for (k=0; k < decode_n; ++k) { + stbi__resample *r = &res_comp[k]; + int y_bot = r->ystep >= (r->vs >> 1); + coutput[k] = r->resample(z->img_comp[k].linebuf, + y_bot ? r->line1 : r->line0, + y_bot ? r->line0 : r->line1, + r->w_lores, r->hs); + if (++r->ystep >= r->vs) { + r->ystep = 0; + r->line0 = r->line1; + if (++r->ypos < z->img_comp[k].y) + r->line1 += z->img_comp[k].w2; + } + } + if (n >= 3) { + stbi_uc *y = coutput[0]; + if (z->s->img_n == 3) { + if (is_rgb) { + for (i=0; i < z->s->img_x; ++i) { + out[0] = y[i]; + out[1] = coutput[1][i]; + out[2] = coutput[2][i]; + out[3] = 255; + out += n; + } + } else { + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + } + } else if (z->s->img_n == 4) { + if (z->app14_color_transform == 0) { // CMYK + for (i=0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + out[0] = stbi__blinn_8x8(coutput[0][i], m); + out[1] = stbi__blinn_8x8(coutput[1][i], m); + out[2] = stbi__blinn_8x8(coutput[2][i], m); + out[3] = 255; + out += n; + } + } else if (z->app14_color_transform == 2) { // YCCK + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + for (i=0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + out[0] = stbi__blinn_8x8(255 - out[0], m); + out[1] = stbi__blinn_8x8(255 - out[1], m); + out[2] = stbi__blinn_8x8(255 - out[2], m); + out += n; + } + } else { // YCbCr + alpha? Ignore the fourth channel for now + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + } + } else + for (i=0; i < z->s->img_x; ++i) { + out[0] = out[1] = out[2] = y[i]; + out[3] = 255; // not used if n==3 + out += n; + } + } else { + if (is_rgb) { + if (n == 1) + for (i=0; i < z->s->img_x; ++i) + *out++ = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); + else { + for (i=0; i < z->s->img_x; ++i, out += 2) { + out[0] = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); + out[1] = 255; + } + } + } else if (z->s->img_n == 4 && z->app14_color_transform == 0) { + for (i=0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + stbi_uc r = stbi__blinn_8x8(coutput[0][i], m); + stbi_uc g = stbi__blinn_8x8(coutput[1][i], m); + stbi_uc b = stbi__blinn_8x8(coutput[2][i], m); + out[0] = stbi__compute_y(r, g, b); + out[1] = 255; + out += n; + } + } else if (z->s->img_n == 4 && z->app14_color_transform == 2) { + for (i=0; i < z->s->img_x; ++i) { + out[0] = stbi__blinn_8x8(255 - coutput[0][i], coutput[3][i]); + out[1] = 255; + out += n; + } + } else { + stbi_uc *y = coutput[0]; + if (n == 1) + for (i=0; i < z->s->img_x; ++i) out[i] = y[i]; + else + for (i=0; i < z->s->img_x; ++i) { *out++ = y[i]; *out++ = 255; } + } + } + } + stbi__cleanup_jpeg(z); + *out_x = z->s->img_x; + *out_y = z->s->img_y; + if (comp) *comp = z->s->img_n >= 3 ? 3 : 1; // report original components, not output + return output; + } +} + +static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + unsigned char* result; + stbi__jpeg* j = (stbi__jpeg*) stbi__malloc(sizeof(stbi__jpeg)); + STBI_NOTUSED(ri); + j->s = s; + stbi__setup_jpeg(j); + result = load_jpeg_image(j, x,y,comp,req_comp); + STBI_FREE(j); + return result; +} + +static int stbi__jpeg_test(stbi__context *s) +{ + int r; + stbi__jpeg* j = (stbi__jpeg*)stbi__malloc(sizeof(stbi__jpeg)); + j->s = s; + stbi__setup_jpeg(j); + r = stbi__decode_jpeg_header(j, STBI__SCAN_type); + stbi__rewind(s); + STBI_FREE(j); + return r; +} + +static int stbi__jpeg_info_raw(stbi__jpeg *j, int *x, int *y, int *comp) +{ + if (!stbi__decode_jpeg_header(j, STBI__SCAN_header)) { + stbi__rewind( j->s ); + return 0; + } + if (x) *x = j->s->img_x; + if (y) *y = j->s->img_y; + if (comp) *comp = j->s->img_n >= 3 ? 3 : 1; + return 1; +} + +static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp) +{ + int result; + stbi__jpeg* j = (stbi__jpeg*) (stbi__malloc(sizeof(stbi__jpeg))); + j->s = s; + result = stbi__jpeg_info_raw(j, x, y, comp); + STBI_FREE(j); + return result; +} +#endif + +// public domain zlib decode v0.2 Sean Barrett 2006-11-18 +// simple implementation +// - all input must be provided in an upfront buffer +// - all output is written to a single output buffer (can malloc/realloc) +// performance +// - fast huffman + +#ifndef STBI_NO_ZLIB + +// fast-way is faster to check than jpeg huffman, but slow way is slower +#define STBI__ZFAST_BITS 9 // accelerate all cases in default tables +#define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1) + +// zlib-style huffman encoding +// (jpegs packs from left, zlib from right, so can't share code) +typedef struct +{ + stbi__uint16 fast[1 << STBI__ZFAST_BITS]; + stbi__uint16 firstcode[16]; + int maxcode[17]; + stbi__uint16 firstsymbol[16]; + stbi_uc size[288]; + stbi__uint16 value[288]; +} stbi__zhuffman; + +stbi_inline static int stbi__bitreverse16(int n) +{ + n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1); + n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2); + n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4); + n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8); + return n; +} + +stbi_inline static int stbi__bit_reverse(int v, int bits) +{ + STBI_ASSERT(bits <= 16); + // to bit reverse n bits, reverse 16 and shift + // e.g. 11 bits, bit reverse and shift away 5 + return stbi__bitreverse16(v) >> (16-bits); +} + +static int stbi__zbuild_huffman(stbi__zhuffman *z, const stbi_uc *sizelist, int num) +{ + int i,k=0; + int code, next_code[16], sizes[17]; + + // DEFLATE spec for generating codes + memset(sizes, 0, sizeof(sizes)); + memset(z->fast, 0, sizeof(z->fast)); + for (i=0; i < num; ++i) + ++sizes[sizelist[i]]; + sizes[0] = 0; + for (i=1; i < 16; ++i) + if (sizes[i] > (1 << i)) + return stbi__err("bad sizes", "Corrupt PNG"); + code = 0; + for (i=1; i < 16; ++i) { + next_code[i] = code; + z->firstcode[i] = (stbi__uint16) code; + z->firstsymbol[i] = (stbi__uint16) k; + code = (code + sizes[i]); + if (sizes[i]) + if (code-1 >= (1 << i)) return stbi__err("bad codelengths","Corrupt PNG"); + z->maxcode[i] = code << (16-i); // preshift for inner loop + code <<= 1; + k += sizes[i]; + } + z->maxcode[16] = 0x10000; // sentinel + for (i=0; i < num; ++i) { + int s = sizelist[i]; + if (s) { + int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s]; + stbi__uint16 fastv = (stbi__uint16) ((s << 9) | i); + z->size [c] = (stbi_uc ) s; + z->value[c] = (stbi__uint16) i; + if (s <= STBI__ZFAST_BITS) { + int j = stbi__bit_reverse(next_code[s],s); + while (j < (1 << STBI__ZFAST_BITS)) { + z->fast[j] = fastv; + j += (1 << s); + } + } + ++next_code[s]; + } + } + return 1; +} + +// zlib-from-memory implementation for PNG reading +// because PNG allows splitting the zlib stream arbitrarily, +// and it's annoying structurally to have PNG call ZLIB call PNG, +// we require PNG read all the IDATs and combine them into a single +// memory buffer + +typedef struct +{ + stbi_uc *zbuffer, *zbuffer_end; + int num_bits; + stbi__uint32 code_buffer; + + char *zout; + char *zout_start; + char *zout_end; + int z_expandable; + + stbi__zhuffman z_length, z_distance; +} stbi__zbuf; + +stbi_inline static int stbi__zeof(stbi__zbuf *z) +{ + return (z->zbuffer >= z->zbuffer_end); +} + +stbi_inline static stbi_uc stbi__zget8(stbi__zbuf *z) +{ + return stbi__zeof(z) ? 0 : *z->zbuffer++; +} + +static void stbi__fill_bits(stbi__zbuf *z) +{ + do { + if (z->code_buffer >= (1U << z->num_bits)) { + z->zbuffer = z->zbuffer_end; /* treat this as EOF so we fail. */ + return; + } + z->code_buffer |= (unsigned int) stbi__zget8(z) << z->num_bits; + z->num_bits += 8; + } while (z->num_bits <= 24); +} + +stbi_inline static unsigned int stbi__zreceive(stbi__zbuf *z, int n) +{ + unsigned int k; + if (z->num_bits < n) stbi__fill_bits(z); + k = z->code_buffer & ((1 << n) - 1); + z->code_buffer >>= n; + z->num_bits -= n; + return k; +} + +static int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z) +{ + int b,s,k; + // not resolved by fast table, so compute it the slow way + // use jpeg approach, which requires MSbits at top + k = stbi__bit_reverse(a->code_buffer, 16); + for (s=STBI__ZFAST_BITS+1; ; ++s) + if (k < z->maxcode[s]) + break; + if (s >= 16) return -1; // invalid code! + // code size is s, so: + b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s]; + if (b >= (int) sizeof (z->size)) return -1; // some data was corrupt somewhere! + if (z->size[b] != s) return -1; // was originally an assert, but report failure instead. + a->code_buffer >>= s; + a->num_bits -= s; + return z->value[b]; +} + +stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z) +{ + int b,s; + if (a->num_bits < 16) { + if (stbi__zeof(a)) { + return -1; /* report error for unexpected end of data. */ + } + stbi__fill_bits(a); + } + b = z->fast[a->code_buffer & STBI__ZFAST_MASK]; + if (b) { + s = b >> 9; + a->code_buffer >>= s; + a->num_bits -= s; + return b & 511; + } + return stbi__zhuffman_decode_slowpath(a, z); +} + +static int stbi__zexpand(stbi__zbuf *z, char *zout, int n) // need to make room for n bytes +{ + char *q; + unsigned int cur, limit, old_limit; + z->zout = zout; + if (!z->z_expandable) return stbi__err("output buffer limit","Corrupt PNG"); + cur = (unsigned int) (z->zout - z->zout_start); + limit = old_limit = (unsigned) (z->zout_end - z->zout_start); + if (UINT_MAX - cur < (unsigned) n) return stbi__err("outofmem", "Out of memory"); + while (cur + n > limit) { + if(limit > UINT_MAX / 2) return stbi__err("outofmem", "Out of memory"); + limit *= 2; + } + q = (char *) STBI_REALLOC_SIZED(z->zout_start, old_limit, limit); + STBI_NOTUSED(old_limit); + if (q == NULL) return stbi__err("outofmem", "Out of memory"); + z->zout_start = q; + z->zout = q + cur; + z->zout_end = q + limit; + return 1; +} + +static const int stbi__zlength_base[31] = { + 3,4,5,6,7,8,9,10,11,13, + 15,17,19,23,27,31,35,43,51,59, + 67,83,99,115,131,163,195,227,258,0,0 }; + +static const int stbi__zlength_extra[31]= +{ 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; + +static const int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, +257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; + +static const int stbi__zdist_extra[32] = +{ 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; + +static int stbi__parse_huffman_block(stbi__zbuf *a) +{ + char *zout = a->zout; + for(;;) { + int z = stbi__zhuffman_decode(a, &a->z_length); + if (z < 256) { + if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); // error in huffman codes + if (zout >= a->zout_end) { + if (!stbi__zexpand(a, zout, 1)) return 0; + zout = a->zout; + } + *zout++ = (char) z; + } else { + stbi_uc *p; + int len,dist; + if (z == 256) { + a->zout = zout; + return 1; + } + z -= 257; + len = stbi__zlength_base[z]; + if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]); + z = stbi__zhuffman_decode(a, &a->z_distance); + if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); + dist = stbi__zdist_base[z]; + if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]); + if (zout - a->zout_start < dist) return stbi__err("bad dist","Corrupt PNG"); + if (zout + len > a->zout_end) { + if (!stbi__zexpand(a, zout, len)) return 0; + zout = a->zout; + } + p = (stbi_uc *) (zout - dist); + if (dist == 1) { // run of one byte; common in images. + stbi_uc v = *p; + if (len) { do *zout++ = v; while (--len); } + } else { + if (len) { do *zout++ = *p++; while (--len); } + } + } + } +} + +static int stbi__compute_huffman_codes(stbi__zbuf *a) +{ + static const stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; + stbi__zhuffman z_codelength; + stbi_uc lencodes[286+32+137];//padding for maximum single op + stbi_uc codelength_sizes[19]; + int i,n; + + int hlit = stbi__zreceive(a,5) + 257; + int hdist = stbi__zreceive(a,5) + 1; + int hclen = stbi__zreceive(a,4) + 4; + int ntot = hlit + hdist; + + memset(codelength_sizes, 0, sizeof(codelength_sizes)); + for (i=0; i < hclen; ++i) { + int s = stbi__zreceive(a,3); + codelength_sizes[length_dezigzag[i]] = (stbi_uc) s; + } + if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0; + + n = 0; + while (n < ntot) { + int c = stbi__zhuffman_decode(a, &z_codelength); + if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG"); + if (c < 16) + lencodes[n++] = (stbi_uc) c; + else { + stbi_uc fill = 0; + if (c == 16) { + c = stbi__zreceive(a,2)+3; + if (n == 0) return stbi__err("bad codelengths", "Corrupt PNG"); + fill = lencodes[n-1]; + } else if (c == 17) { + c = stbi__zreceive(a,3)+3; + } else if (c == 18) { + c = stbi__zreceive(a,7)+11; + } else { + return stbi__err("bad codelengths", "Corrupt PNG"); + } + if (ntot - n < c) return stbi__err("bad codelengths", "Corrupt PNG"); + memset(lencodes+n, fill, c); + n += c; + } + } + if (n != ntot) return stbi__err("bad codelengths","Corrupt PNG"); + if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0; + if (!stbi__zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0; + return 1; +} + +static int stbi__parse_uncompressed_block(stbi__zbuf *a) +{ + stbi_uc header[4]; + int len,nlen,k; + if (a->num_bits & 7) + stbi__zreceive(a, a->num_bits & 7); // discard + // drain the bit-packed data into header + k = 0; + while (a->num_bits > 0) { + header[k++] = (stbi_uc) (a->code_buffer & 255); // suppress MSVC run-time check + a->code_buffer >>= 8; + a->num_bits -= 8; + } + if (a->num_bits < 0) return stbi__err("zlib corrupt","Corrupt PNG"); + // now fill header the normal way + while (k < 4) + header[k++] = stbi__zget8(a); + len = header[1] * 256 + header[0]; + nlen = header[3] * 256 + header[2]; + if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt","Corrupt PNG"); + if (a->zbuffer + len > a->zbuffer_end) return stbi__err("read past buffer","Corrupt PNG"); + if (a->zout + len > a->zout_end) + if (!stbi__zexpand(a, a->zout, len)) return 0; + memcpy(a->zout, a->zbuffer, len); + a->zbuffer += len; + a->zout += len; + return 1; +} + +static int stbi__parse_zlib_header(stbi__zbuf *a) +{ + int cmf = stbi__zget8(a); + int cm = cmf & 15; + /* int cinfo = cmf >> 4; */ + int flg = stbi__zget8(a); + if (stbi__zeof(a)) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec + if ((cmf*256+flg) % 31 != 0) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec + if (flg & 32) return stbi__err("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png + if (cm != 8) return stbi__err("bad compression","Corrupt PNG"); // DEFLATE required for png + // window = 1 << (8 + cinfo)... but who cares, we fully buffer output + return 1; +} + +static const stbi_uc stbi__zdefault_length[288] = +{ + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8 +}; +static const stbi_uc stbi__zdefault_distance[32] = +{ + 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5 +}; +/* +Init algorithm: +{ + int i; // use <= to match clearly with spec + for (i=0; i <= 143; ++i) stbi__zdefault_length[i] = 8; + for ( ; i <= 255; ++i) stbi__zdefault_length[i] = 9; + for ( ; i <= 279; ++i) stbi__zdefault_length[i] = 7; + for ( ; i <= 287; ++i) stbi__zdefault_length[i] = 8; + + for (i=0; i <= 31; ++i) stbi__zdefault_distance[i] = 5; +} +*/ + +static int stbi__parse_zlib(stbi__zbuf *a, int parse_header) +{ + int final, type; + if (parse_header) + if (!stbi__parse_zlib_header(a)) return 0; + a->num_bits = 0; + a->code_buffer = 0; + do { + final = stbi__zreceive(a,1); + type = stbi__zreceive(a,2); + if (type == 0) { + if (!stbi__parse_uncompressed_block(a)) return 0; + } else if (type == 3) { + return 0; + } else { + if (type == 1) { + // use fixed code lengths + if (!stbi__zbuild_huffman(&a->z_length , stbi__zdefault_length , 288)) return 0; + if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0; + } else { + if (!stbi__compute_huffman_codes(a)) return 0; + } + if (!stbi__parse_huffman_block(a)) return 0; + } + } while (!final); + return 1; +} + +static int stbi__do_zlib(stbi__zbuf *a, char *obuf, int olen, int exp, int parse_header) +{ + a->zout_start = obuf; + a->zout = obuf; + a->zout_end = obuf + olen; + a->z_expandable = exp; + + return stbi__parse_zlib(a, parse_header); +} + +STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen) +{ + stbi__zbuf a; + char *p = (char *) stbi__malloc(initial_size); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *) buffer; + a.zbuffer_end = (stbi_uc *) buffer + len; + if (stbi__do_zlib(&a, p, initial_size, 1, 1)) { + if (outlen) *outlen = (int) (a.zout - a.zout_start); + return a.zout_start; + } else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen) +{ + return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen); +} + +STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header) +{ + stbi__zbuf a; + char *p = (char *) stbi__malloc(initial_size); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *) buffer; + a.zbuffer_end = (stbi_uc *) buffer + len; + if (stbi__do_zlib(&a, p, initial_size, 1, parse_header)) { + if (outlen) *outlen = (int) (a.zout - a.zout_start); + return a.zout_start; + } else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen) +{ + stbi__zbuf a; + a.zbuffer = (stbi_uc *) ibuffer; + a.zbuffer_end = (stbi_uc *) ibuffer + ilen; + if (stbi__do_zlib(&a, obuffer, olen, 0, 1)) + return (int) (a.zout - a.zout_start); + else + return -1; +} + +STBIDEF char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen) +{ + stbi__zbuf a; + char *p = (char *) stbi__malloc(16384); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *) buffer; + a.zbuffer_end = (stbi_uc *) buffer+len; + if (stbi__do_zlib(&a, p, 16384, 1, 0)) { + if (outlen) *outlen = (int) (a.zout - a.zout_start); + return a.zout_start; + } else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen) +{ + stbi__zbuf a; + a.zbuffer = (stbi_uc *) ibuffer; + a.zbuffer_end = (stbi_uc *) ibuffer + ilen; + if (stbi__do_zlib(&a, obuffer, olen, 0, 0)) + return (int) (a.zout - a.zout_start); + else + return -1; +} +#endif + +// public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18 +// simple implementation +// - only 8-bit samples +// - no CRC checking +// - allocates lots of intermediate memory +// - avoids problem of streaming data between subsystems +// - avoids explicit window management +// performance +// - uses stb_zlib, a PD zlib implementation with fast huffman decoding + +#ifndef STBI_NO_PNG +typedef struct +{ + stbi__uint32 length; + stbi__uint32 type; +} stbi__pngchunk; + +static stbi__pngchunk stbi__get_chunk_header(stbi__context *s) +{ + stbi__pngchunk c; + c.length = stbi__get32be(s); + c.type = stbi__get32be(s); + return c; +} + +static int stbi__check_png_header(stbi__context *s) +{ + static const stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 }; + int i; + for (i=0; i < 8; ++i) + if (stbi__get8(s) != png_sig[i]) return stbi__err("bad png sig","Not a PNG"); + return 1; +} + +typedef struct +{ + stbi__context *s; + stbi_uc *idata, *expanded, *out; + int depth; +} stbi__png; + + +enum { + STBI__F_none=0, + STBI__F_sub=1, + STBI__F_up=2, + STBI__F_avg=3, + STBI__F_paeth=4, + // synthetic filters used for first scanline to avoid needing a dummy row of 0s + STBI__F_avg_first, + STBI__F_paeth_first +}; + +static stbi_uc first_row_filter[5] = +{ + STBI__F_none, + STBI__F_sub, + STBI__F_none, + STBI__F_avg_first, + STBI__F_paeth_first +}; + +static int stbi__paeth(int a, int b, int c) +{ + int p = a + b - c; + int pa = abs(p-a); + int pb = abs(p-b); + int pc = abs(p-c); + if (pa <= pb && pa <= pc) return a; + if (pb <= pc) return b; + return c; +} + +static const stbi_uc stbi__depth_scale_table[9] = { 0, 0xff, 0x55, 0, 0x11, 0,0,0, 0x01 }; + +// create the png data from post-deflated data +static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color) +{ + int bytes = (depth == 16? 2 : 1); + stbi__context *s = a->s; + stbi__uint32 i,j,stride = x*out_n*bytes; + stbi__uint32 img_len, img_width_bytes; + int k; + int img_n = s->img_n; // copy it into a local for later + + int output_bytes = out_n*bytes; + int filter_bytes = img_n*bytes; + int width = x; + + STBI_ASSERT(out_n == s->img_n || out_n == s->img_n+1); + a->out = (stbi_uc *) stbi__malloc_mad3(x, y, output_bytes, 0); // extra bytes to write off the end into + if (!a->out) return stbi__err("outofmem", "Out of memory"); + + if (!stbi__mad3sizes_valid(img_n, x, depth, 7)) return stbi__err("too large", "Corrupt PNG"); + img_width_bytes = (((img_n * x * depth) + 7) >> 3); + img_len = (img_width_bytes + 1) * y; + + // we used to check for exact match between raw_len and img_len on non-interlaced PNGs, + // but issue #276 reported a PNG in the wild that had extra data at the end (all zeros), + // so just check for raw_len < img_len always. + if (raw_len < img_len) return stbi__err("not enough pixels","Corrupt PNG"); + + for (j=0; j < y; ++j) { + stbi_uc *cur = a->out + stride*j; + stbi_uc *prior; + int filter = *raw++; + + if (filter > 4) + return stbi__err("invalid filter","Corrupt PNG"); + + if (depth < 8) { + if (img_width_bytes > x) return stbi__err("invalid width","Corrupt PNG"); + cur += x*out_n - img_width_bytes; // store output to the rightmost img_len bytes, so we can decode in place + filter_bytes = 1; + width = img_width_bytes; + } + prior = cur - stride; // bugfix: need to compute this after 'cur +=' computation above + + // if first row, use special filter that doesn't sample previous row + if (j == 0) filter = first_row_filter[filter]; + + // handle first byte explicitly + for (k=0; k < filter_bytes; ++k) { + switch (filter) { + case STBI__F_none : cur[k] = raw[k]; break; + case STBI__F_sub : cur[k] = raw[k]; break; + case STBI__F_up : cur[k] = STBI__BYTECAST(raw[k] + prior[k]); break; + case STBI__F_avg : cur[k] = STBI__BYTECAST(raw[k] + (prior[k]>>1)); break; + case STBI__F_paeth : cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(0,prior[k],0)); break; + case STBI__F_avg_first : cur[k] = raw[k]; break; + case STBI__F_paeth_first: cur[k] = raw[k]; break; + } + } + + if (depth == 8) { + if (img_n != out_n) + cur[img_n] = 255; // first pixel + raw += img_n; + cur += out_n; + prior += out_n; + } else if (depth == 16) { + if (img_n != out_n) { + cur[filter_bytes] = 255; // first pixel top byte + cur[filter_bytes+1] = 255; // first pixel bottom byte + } + raw += filter_bytes; + cur += output_bytes; + prior += output_bytes; + } else { + raw += 1; + cur += 1; + prior += 1; + } + + // this is a little gross, so that we don't switch per-pixel or per-component + if (depth < 8 || img_n == out_n) { + int nk = (width - 1)*filter_bytes; + #define STBI__CASE(f) \ + case f: \ + for (k=0; k < nk; ++k) + switch (filter) { + // "none" filter turns into a memcpy here; make that explicit. + case STBI__F_none: memcpy(cur, raw, nk); break; + STBI__CASE(STBI__F_sub) { cur[k] = STBI__BYTECAST(raw[k] + cur[k-filter_bytes]); } break; + STBI__CASE(STBI__F_up) { cur[k] = STBI__BYTECAST(raw[k] + prior[k]); } break; + STBI__CASE(STBI__F_avg) { cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-filter_bytes])>>1)); } break; + STBI__CASE(STBI__F_paeth) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],prior[k],prior[k-filter_bytes])); } break; + STBI__CASE(STBI__F_avg_first) { cur[k] = STBI__BYTECAST(raw[k] + (cur[k-filter_bytes] >> 1)); } break; + STBI__CASE(STBI__F_paeth_first) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],0,0)); } break; + } + #undef STBI__CASE + raw += nk; + } else { + STBI_ASSERT(img_n+1 == out_n); + #define STBI__CASE(f) \ + case f: \ + for (i=x-1; i >= 1; --i, cur[filter_bytes]=255,raw+=filter_bytes,cur+=output_bytes,prior+=output_bytes) \ + for (k=0; k < filter_bytes; ++k) + switch (filter) { + STBI__CASE(STBI__F_none) { cur[k] = raw[k]; } break; + STBI__CASE(STBI__F_sub) { cur[k] = STBI__BYTECAST(raw[k] + cur[k- output_bytes]); } break; + STBI__CASE(STBI__F_up) { cur[k] = STBI__BYTECAST(raw[k] + prior[k]); } break; + STBI__CASE(STBI__F_avg) { cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k- output_bytes])>>1)); } break; + STBI__CASE(STBI__F_paeth) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k- output_bytes],prior[k],prior[k- output_bytes])); } break; + STBI__CASE(STBI__F_avg_first) { cur[k] = STBI__BYTECAST(raw[k] + (cur[k- output_bytes] >> 1)); } break; + STBI__CASE(STBI__F_paeth_first) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k- output_bytes],0,0)); } break; + } + #undef STBI__CASE + + // the loop above sets the high byte of the pixels' alpha, but for + // 16 bit png files we also need the low byte set. we'll do that here. + if (depth == 16) { + cur = a->out + stride*j; // start at the beginning of the row again + for (i=0; i < x; ++i,cur+=output_bytes) { + cur[filter_bytes+1] = 255; + } + } + } + } + + // we make a separate pass to expand bits to pixels; for performance, + // this could run two scanlines behind the above code, so it won't + // intefere with filtering but will still be in the cache. + if (depth < 8) { + for (j=0; j < y; ++j) { + stbi_uc *cur = a->out + stride*j; + stbi_uc *in = a->out + stride*j + x*out_n - img_width_bytes; + // unpack 1/2/4-bit into a 8-bit buffer. allows us to keep the common 8-bit path optimal at minimal cost for 1/2/4-bit + // png guarante byte alignment, if width is not multiple of 8/4/2 we'll decode dummy trailing data that will be skipped in the later loop + stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] : 1; // scale grayscale values to 0..255 range + + // note that the final byte might overshoot and write more data than desired. + // we can allocate enough data that this never writes out of memory, but it + // could also overwrite the next scanline. can it overwrite non-empty data + // on the next scanline? yes, consider 1-pixel-wide scanlines with 1-bit-per-pixel. + // so we need to explicitly clamp the final ones + + if (depth == 4) { + for (k=x*img_n; k >= 2; k-=2, ++in) { + *cur++ = scale * ((*in >> 4) ); + *cur++ = scale * ((*in ) & 0x0f); + } + if (k > 0) *cur++ = scale * ((*in >> 4) ); + } else if (depth == 2) { + for (k=x*img_n; k >= 4; k-=4, ++in) { + *cur++ = scale * ((*in >> 6) ); + *cur++ = scale * ((*in >> 4) & 0x03); + *cur++ = scale * ((*in >> 2) & 0x03); + *cur++ = scale * ((*in ) & 0x03); + } + if (k > 0) *cur++ = scale * ((*in >> 6) ); + if (k > 1) *cur++ = scale * ((*in >> 4) & 0x03); + if (k > 2) *cur++ = scale * ((*in >> 2) & 0x03); + } else if (depth == 1) { + for (k=x*img_n; k >= 8; k-=8, ++in) { + *cur++ = scale * ((*in >> 7) ); + *cur++ = scale * ((*in >> 6) & 0x01); + *cur++ = scale * ((*in >> 5) & 0x01); + *cur++ = scale * ((*in >> 4) & 0x01); + *cur++ = scale * ((*in >> 3) & 0x01); + *cur++ = scale * ((*in >> 2) & 0x01); + *cur++ = scale * ((*in >> 1) & 0x01); + *cur++ = scale * ((*in ) & 0x01); + } + if (k > 0) *cur++ = scale * ((*in >> 7) ); + if (k > 1) *cur++ = scale * ((*in >> 6) & 0x01); + if (k > 2) *cur++ = scale * ((*in >> 5) & 0x01); + if (k > 3) *cur++ = scale * ((*in >> 4) & 0x01); + if (k > 4) *cur++ = scale * ((*in >> 3) & 0x01); + if (k > 5) *cur++ = scale * ((*in >> 2) & 0x01); + if (k > 6) *cur++ = scale * ((*in >> 1) & 0x01); + } + if (img_n != out_n) { + int q; + // insert alpha = 255 + cur = a->out + stride*j; + if (img_n == 1) { + for (q=x-1; q >= 0; --q) { + cur[q*2+1] = 255; + cur[q*2+0] = cur[q]; + } + } else { + STBI_ASSERT(img_n == 3); + for (q=x-1; q >= 0; --q) { + cur[q*4+3] = 255; + cur[q*4+2] = cur[q*3+2]; + cur[q*4+1] = cur[q*3+1]; + cur[q*4+0] = cur[q*3+0]; + } + } + } + } + } else if (depth == 16) { + // force the image data from big-endian to platform-native. + // this is done in a separate pass due to the decoding relying + // on the data being untouched, but could probably be done + // per-line during decode if care is taken. + stbi_uc *cur = a->out; + stbi__uint16 *cur16 = (stbi__uint16*)cur; + + for(i=0; i < x*y*out_n; ++i,cur16++,cur+=2) { + *cur16 = (cur[0] << 8) | cur[1]; + } + } + + return 1; +} + +static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint32 image_data_len, int out_n, int depth, int color, int interlaced) +{ + int bytes = (depth == 16 ? 2 : 1); + int out_bytes = out_n * bytes; + stbi_uc *final; + int p; + if (!interlaced) + return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, a->s->img_y, depth, color); + + // de-interlacing + final = (stbi_uc *) stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0); + for (p=0; p < 7; ++p) { + int xorig[] = { 0,4,0,2,0,1,0 }; + int yorig[] = { 0,0,4,0,2,0,1 }; + int xspc[] = { 8,8,4,4,2,2,1 }; + int yspc[] = { 8,8,8,4,4,2,2 }; + int i,j,x,y; + // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1 + x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p]; + y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p]; + if (x && y) { + stbi__uint32 img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y; + if (!stbi__create_png_image_raw(a, image_data, image_data_len, out_n, x, y, depth, color)) { + STBI_FREE(final); + return 0; + } + for (j=0; j < y; ++j) { + for (i=0; i < x; ++i) { + int out_y = j*yspc[p]+yorig[p]; + int out_x = i*xspc[p]+xorig[p]; + memcpy(final + out_y*a->s->img_x*out_bytes + out_x*out_bytes, + a->out + (j*x+i)*out_bytes, out_bytes); + } + } + STBI_FREE(a->out); + image_data += img_len; + image_data_len -= img_len; + } + } + a->out = final; + + return 1; +} + +static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi_uc *p = z->out; + + // compute color-based transparency, assuming we've + // already got 255 as the alpha value in the output + STBI_ASSERT(out_n == 2 || out_n == 4); + + if (out_n == 2) { + for (i=0; i < pixel_count; ++i) { + p[1] = (p[0] == tc[0] ? 0 : 255); + p += 2; + } + } else { + for (i=0; i < pixel_count; ++i) { + if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) + p[3] = 0; + p += 4; + } + } + return 1; +} + +static int stbi__compute_transparency16(stbi__png *z, stbi__uint16 tc[3], int out_n) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi__uint16 *p = (stbi__uint16*) z->out; + + // compute color-based transparency, assuming we've + // already got 65535 as the alpha value in the output + STBI_ASSERT(out_n == 2 || out_n == 4); + + if (out_n == 2) { + for (i = 0; i < pixel_count; ++i) { + p[1] = (p[0] == tc[0] ? 0 : 65535); + p += 2; + } + } else { + for (i = 0; i < pixel_count; ++i) { + if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) + p[3] = 0; + p += 4; + } + } + return 1; +} + +static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int pal_img_n) +{ + stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y; + stbi_uc *p, *temp_out, *orig = a->out; + + p = (stbi_uc *) stbi__malloc_mad2(pixel_count, pal_img_n, 0); + if (p == NULL) return stbi__err("outofmem", "Out of memory"); + + // between here and free(out) below, exitting would leak + temp_out = p; + + if (pal_img_n == 3) { + for (i=0; i < pixel_count; ++i) { + int n = orig[i]*4; + p[0] = palette[n ]; + p[1] = palette[n+1]; + p[2] = palette[n+2]; + p += 3; + } + } else { + for (i=0; i < pixel_count; ++i) { + int n = orig[i]*4; + p[0] = palette[n ]; + p[1] = palette[n+1]; + p[2] = palette[n+2]; + p[3] = palette[n+3]; + p += 4; + } + } + STBI_FREE(a->out); + a->out = temp_out; + + STBI_NOTUSED(len); + + return 1; +} + +static int stbi__unpremultiply_on_load = 0; +static int stbi__de_iphone_flag = 0; + +STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply) +{ + stbi__unpremultiply_on_load = flag_true_if_should_unpremultiply; +} + +STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert) +{ + stbi__de_iphone_flag = flag_true_if_should_convert; +} + +static void stbi__de_iphone(stbi__png *z) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi_uc *p = z->out; + + if (s->img_out_n == 3) { // convert bgr to rgb + for (i=0; i < pixel_count; ++i) { + stbi_uc t = p[0]; + p[0] = p[2]; + p[2] = t; + p += 3; + } + } else { + STBI_ASSERT(s->img_out_n == 4); + if (stbi__unpremultiply_on_load) { + // convert bgr to rgb and unpremultiply + for (i=0; i < pixel_count; ++i) { + stbi_uc a = p[3]; + stbi_uc t = p[0]; + if (a) { + stbi_uc half = a / 2; + p[0] = (p[2] * 255 + half) / a; + p[1] = (p[1] * 255 + half) / a; + p[2] = ( t * 255 + half) / a; + } else { + p[0] = p[2]; + p[2] = t; + } + p += 4; + } + } else { + // convert bgr to rgb + for (i=0; i < pixel_count; ++i) { + stbi_uc t = p[0]; + p[0] = p[2]; + p[2] = t; + p += 4; + } + } + } +} + +#define STBI__PNG_TYPE(a,b,c,d) (((unsigned) (a) << 24) + ((unsigned) (b) << 16) + ((unsigned) (c) << 8) + (unsigned) (d)) + +static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) +{ + stbi_uc palette[1024], pal_img_n=0; + stbi_uc has_trans=0, tc[3]={0}; + stbi__uint16 tc16[3]; + stbi__uint32 ioff=0, idata_limit=0, i, pal_len=0; + int first=1,k,interlace=0, color=0, is_iphone=0; + stbi__context *s = z->s; + + z->expanded = NULL; + z->idata = NULL; + z->out = NULL; + + if (!stbi__check_png_header(s)) return 0; + + if (scan == STBI__SCAN_type) return 1; + + for (;;) { + stbi__pngchunk c = stbi__get_chunk_header(s); + switch (c.type) { + case STBI__PNG_TYPE('C','g','B','I'): + is_iphone = 1; + stbi__skip(s, c.length); + break; + case STBI__PNG_TYPE('I','H','D','R'): { + int comp,filter; + if (!first) return stbi__err("multiple IHDR","Corrupt PNG"); + first = 0; + if (c.length != 13) return stbi__err("bad IHDR len","Corrupt PNG"); + s->img_x = stbi__get32be(s); + s->img_y = stbi__get32be(s); + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + z->depth = stbi__get8(s); if (z->depth != 1 && z->depth != 2 && z->depth != 4 && z->depth != 8 && z->depth != 16) return stbi__err("1/2/4/8/16-bit only","PNG not supported: 1/2/4/8/16-bit only"); + color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype","Corrupt PNG"); + if (color == 3 && z->depth == 16) return stbi__err("bad ctype","Corrupt PNG"); + if (color == 3) pal_img_n = 3; else if (color & 1) return stbi__err("bad ctype","Corrupt PNG"); + comp = stbi__get8(s); if (comp) return stbi__err("bad comp method","Corrupt PNG"); + filter= stbi__get8(s); if (filter) return stbi__err("bad filter method","Corrupt PNG"); + interlace = stbi__get8(s); if (interlace>1) return stbi__err("bad interlace method","Corrupt PNG"); + if (!s->img_x || !s->img_y) return stbi__err("0-pixel image","Corrupt PNG"); + if (!pal_img_n) { + s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0); + if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode"); + if (scan == STBI__SCAN_header) return 1; + } else { + // if paletted, then pal_n is our final components, and + // img_n is # components to decompress/filter. + s->img_n = 1; + if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err("too large","Corrupt PNG"); + // if SCAN_header, have to scan to see if we have a tRNS + } + break; + } + + case STBI__PNG_TYPE('P','L','T','E'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (c.length > 256*3) return stbi__err("invalid PLTE","Corrupt PNG"); + pal_len = c.length / 3; + if (pal_len * 3 != c.length) return stbi__err("invalid PLTE","Corrupt PNG"); + for (i=0; i < pal_len; ++i) { + palette[i*4+0] = stbi__get8(s); + palette[i*4+1] = stbi__get8(s); + palette[i*4+2] = stbi__get8(s); + palette[i*4+3] = 255; + } + break; + } + + case STBI__PNG_TYPE('t','R','N','S'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (z->idata) return stbi__err("tRNS after IDAT","Corrupt PNG"); + if (pal_img_n) { + if (scan == STBI__SCAN_header) { s->img_n = 4; return 1; } + if (pal_len == 0) return stbi__err("tRNS before PLTE","Corrupt PNG"); + if (c.length > pal_len) return stbi__err("bad tRNS len","Corrupt PNG"); + pal_img_n = 4; + for (i=0; i < c.length; ++i) + palette[i*4+3] = stbi__get8(s); + } else { + if (!(s->img_n & 1)) return stbi__err("tRNS with alpha","Corrupt PNG"); + if (c.length != (stbi__uint32) s->img_n*2) return stbi__err("bad tRNS len","Corrupt PNG"); + has_trans = 1; + if (z->depth == 16) { + for (k = 0; k < s->img_n; ++k) tc16[k] = (stbi__uint16)stbi__get16be(s); // copy the values as-is + } else { + for (k = 0; k < s->img_n; ++k) tc[k] = (stbi_uc)(stbi__get16be(s) & 255) * stbi__depth_scale_table[z->depth]; // non 8-bit images will be larger + } + } + break; + } + + case STBI__PNG_TYPE('I','D','A','T'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (pal_img_n && !pal_len) return stbi__err("no PLTE","Corrupt PNG"); + if (scan == STBI__SCAN_header) { s->img_n = pal_img_n; return 1; } + if ((int)(ioff + c.length) < (int)ioff) return 0; + if (ioff + c.length > idata_limit) { + stbi__uint32 idata_limit_old = idata_limit; + stbi_uc *p; + if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096; + while (ioff + c.length > idata_limit) + idata_limit *= 2; + STBI_NOTUSED(idata_limit_old); + p = (stbi_uc *) STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory"); + z->idata = p; + } + if (!stbi__getn(s, z->idata+ioff,c.length)) return stbi__err("outofdata","Corrupt PNG"); + ioff += c.length; + break; + } + + case STBI__PNG_TYPE('I','E','N','D'): { + stbi__uint32 raw_len, bpl; + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (scan != STBI__SCAN_load) return 1; + if (z->idata == NULL) return stbi__err("no IDAT","Corrupt PNG"); + // initial guess for decoded data size to avoid unnecessary reallocs + bpl = (s->img_x * z->depth + 7) / 8; // bytes per line, per component + raw_len = bpl * s->img_y * s->img_n /* pixels */ + s->img_y /* filter mode per row */; + z->expanded = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, raw_len, (int *) &raw_len, !is_iphone); + if (z->expanded == NULL) return 0; // zlib should set error + STBI_FREE(z->idata); z->idata = NULL; + if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans) + s->img_out_n = s->img_n+1; + else + s->img_out_n = s->img_n; + if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, z->depth, color, interlace)) return 0; + if (has_trans) { + if (z->depth == 16) { + if (!stbi__compute_transparency16(z, tc16, s->img_out_n)) return 0; + } else { + if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0; + } + } + if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2) + stbi__de_iphone(z); + if (pal_img_n) { + // pal_img_n == 3 or 4 + s->img_n = pal_img_n; // record the actual colors we had + s->img_out_n = pal_img_n; + if (req_comp >= 3) s->img_out_n = req_comp; + if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n)) + return 0; + } else if (has_trans) { + // non-paletted image with tRNS -> source image has (constant) alpha + ++s->img_n; + } + STBI_FREE(z->expanded); z->expanded = NULL; + // end of PNG chunk, read and skip CRC + stbi__get32be(s); + return 1; + } + + default: + // if critical, fail + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if ((c.type & (1 << 29)) == 0) { + #ifndef STBI_NO_FAILURE_STRINGS + // not threadsafe + static char invalid_chunk[] = "XXXX PNG chunk not known"; + invalid_chunk[0] = STBI__BYTECAST(c.type >> 24); + invalid_chunk[1] = STBI__BYTECAST(c.type >> 16); + invalid_chunk[2] = STBI__BYTECAST(c.type >> 8); + invalid_chunk[3] = STBI__BYTECAST(c.type >> 0); + #endif + return stbi__err(invalid_chunk, "PNG not supported: unknown PNG chunk type"); + } + stbi__skip(s, c.length); + break; + } + // end of PNG chunk, read and skip CRC + stbi__get32be(s); + } +} + +static void *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp, stbi__result_info *ri) +{ + void *result=NULL; + if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); + if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) { + if (p->depth <= 8) + ri->bits_per_channel = 8; + else if (p->depth == 16) + ri->bits_per_channel = 16; + else + return stbi__errpuc("bad bits_per_channel", "PNG not supported: unsupported color depth"); + result = p->out; + p->out = NULL; + if (req_comp && req_comp != p->s->img_out_n) { + if (ri->bits_per_channel == 8) + result = stbi__convert_format((unsigned char *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); + else + result = stbi__convert_format16((stbi__uint16 *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); + p->s->img_out_n = req_comp; + if (result == NULL) return result; + } + *x = p->s->img_x; + *y = p->s->img_y; + if (n) *n = p->s->img_n; + } + STBI_FREE(p->out); p->out = NULL; + STBI_FREE(p->expanded); p->expanded = NULL; + STBI_FREE(p->idata); p->idata = NULL; + + return result; +} + +static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi__png p; + p.s = s; + return stbi__do_png(&p, x,y,comp,req_comp, ri); +} + +static int stbi__png_test(stbi__context *s) +{ + int r; + r = stbi__check_png_header(s); + stbi__rewind(s); + return r; +} + +static int stbi__png_info_raw(stbi__png *p, int *x, int *y, int *comp) +{ + if (!stbi__parse_png_file(p, STBI__SCAN_header, 0)) { + stbi__rewind( p->s ); + return 0; + } + if (x) *x = p->s->img_x; + if (y) *y = p->s->img_y; + if (comp) *comp = p->s->img_n; + return 1; +} + +static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp) +{ + stbi__png p; + p.s = s; + return stbi__png_info_raw(&p, x, y, comp); +} + +static int stbi__png_is16(stbi__context *s) +{ + stbi__png p; + p.s = s; + if (!stbi__png_info_raw(&p, NULL, NULL, NULL)) + return 0; + if (p.depth != 16) { + stbi__rewind(p.s); + return 0; + } + return 1; +} +#endif + +// Microsoft/Windows BMP image + +#ifndef STBI_NO_BMP +static int stbi__bmp_test_raw(stbi__context *s) +{ + int r; + int sz; + if (stbi__get8(s) != 'B') return 0; + if (stbi__get8(s) != 'M') return 0; + stbi__get32le(s); // discard filesize + stbi__get16le(s); // discard reserved + stbi__get16le(s); // discard reserved + stbi__get32le(s); // discard data offset + sz = stbi__get32le(s); + r = (sz == 12 || sz == 40 || sz == 56 || sz == 108 || sz == 124); + return r; +} + +static int stbi__bmp_test(stbi__context *s) +{ + int r = stbi__bmp_test_raw(s); + stbi__rewind(s); + return r; +} + + +// returns 0..31 for the highest set bit +static int stbi__high_bit(unsigned int z) +{ + int n=0; + if (z == 0) return -1; + if (z >= 0x10000) { n += 16; z >>= 16; } + if (z >= 0x00100) { n += 8; z >>= 8; } + if (z >= 0x00010) { n += 4; z >>= 4; } + if (z >= 0x00004) { n += 2; z >>= 2; } + if (z >= 0x00002) { n += 1;/* >>= 1;*/ } + return n; +} + +static int stbi__bitcount(unsigned int a) +{ + a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2 + a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4 + a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits + a = (a + (a >> 8)); // max 16 per 8 bits + a = (a + (a >> 16)); // max 32 per 8 bits + return a & 0xff; +} + +// extract an arbitrarily-aligned N-bit value (N=bits) +// from v, and then make it 8-bits long and fractionally +// extend it to full full range. +static int stbi__shiftsigned(unsigned int v, int shift, int bits) +{ + static unsigned int mul_table[9] = { + 0, + 0xff/*0b11111111*/, 0x55/*0b01010101*/, 0x49/*0b01001001*/, 0x11/*0b00010001*/, + 0x21/*0b00100001*/, 0x41/*0b01000001*/, 0x81/*0b10000001*/, 0x01/*0b00000001*/, + }; + static unsigned int shift_table[9] = { + 0, 0,0,1,0,2,4,6,0, + }; + if (shift < 0) + v <<= -shift; + else + v >>= shift; + STBI_ASSERT(v < 256); + v >>= (8-bits); + STBI_ASSERT(bits >= 0 && bits <= 8); + return (int) ((unsigned) v * mul_table[bits]) >> shift_table[bits]; +} + +typedef struct +{ + int bpp, offset, hsz; + unsigned int mr,mg,mb,ma, all_a; + int extra_read; +} stbi__bmp_data; + +static void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info) +{ + int hsz; + if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') return stbi__errpuc("not BMP", "Corrupt BMP"); + stbi__get32le(s); // discard filesize + stbi__get16le(s); // discard reserved + stbi__get16le(s); // discard reserved + info->offset = stbi__get32le(s); + info->hsz = hsz = stbi__get32le(s); + info->mr = info->mg = info->mb = info->ma = 0; + info->extra_read = 14; + + if (info->offset < 0) return stbi__errpuc("bad BMP", "bad BMP"); + + if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) return stbi__errpuc("unknown BMP", "BMP type not supported: unknown"); + if (hsz == 12) { + s->img_x = stbi__get16le(s); + s->img_y = stbi__get16le(s); + } else { + s->img_x = stbi__get32le(s); + s->img_y = stbi__get32le(s); + } + if (stbi__get16le(s) != 1) return stbi__errpuc("bad BMP", "bad BMP"); + info->bpp = stbi__get16le(s); + if (hsz != 12) { + int compress = stbi__get32le(s); + if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE"); + stbi__get32le(s); // discard sizeof + stbi__get32le(s); // discard hres + stbi__get32le(s); // discard vres + stbi__get32le(s); // discard colorsused + stbi__get32le(s); // discard max important + if (hsz == 40 || hsz == 56) { + if (hsz == 56) { + stbi__get32le(s); + stbi__get32le(s); + stbi__get32le(s); + stbi__get32le(s); + } + if (info->bpp == 16 || info->bpp == 32) { + if (compress == 0) { + if (info->bpp == 32) { + info->mr = 0xffu << 16; + info->mg = 0xffu << 8; + info->mb = 0xffu << 0; + info->ma = 0xffu << 24; + info->all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 0 + } else { + info->mr = 31u << 10; + info->mg = 31u << 5; + info->mb = 31u << 0; + } + } else if (compress == 3) { + info->mr = stbi__get32le(s); + info->mg = stbi__get32le(s); + info->mb = stbi__get32le(s); + info->extra_read += 12; + // not documented, but generated by photoshop and handled by mspaint + if (info->mr == info->mg && info->mg == info->mb) { + // ?!?!? + return stbi__errpuc("bad BMP", "bad BMP"); + } + } else + return stbi__errpuc("bad BMP", "bad BMP"); + } + } else { + int i; + if (hsz != 108 && hsz != 124) + return stbi__errpuc("bad BMP", "bad BMP"); + info->mr = stbi__get32le(s); + info->mg = stbi__get32le(s); + info->mb = stbi__get32le(s); + info->ma = stbi__get32le(s); + stbi__get32le(s); // discard color space + for (i=0; i < 12; ++i) + stbi__get32le(s); // discard color space parameters + if (hsz == 124) { + stbi__get32le(s); // discard rendering intent + stbi__get32le(s); // discard offset of profile data + stbi__get32le(s); // discard size of profile data + stbi__get32le(s); // discard reserved + } + } + } + return (void *) 1; +} + + +static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi_uc *out; + unsigned int mr=0,mg=0,mb=0,ma=0, all_a; + stbi_uc pal[256][4]; + int psize=0,i,j,width; + int flip_vertically, pad, target; + stbi__bmp_data info; + STBI_NOTUSED(ri); + + info.all_a = 255; + if (stbi__bmp_parse_header(s, &info) == NULL) + return NULL; // error code already set + + flip_vertically = ((int) s->img_y) > 0; + s->img_y = abs((int) s->img_y); + + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + mr = info.mr; + mg = info.mg; + mb = info.mb; + ma = info.ma; + all_a = info.all_a; + + if (info.hsz == 12) { + if (info.bpp < 24) + psize = (info.offset - info.extra_read - 24) / 3; + } else { + if (info.bpp < 16) + psize = (info.offset - info.extra_read - info.hsz) >> 2; + } + if (psize == 0) { + STBI_ASSERT(info.offset == s->callback_already_read + (int) (s->img_buffer - s->img_buffer_original)); + if (info.offset != s->callback_already_read + (s->img_buffer - s->buffer_start)) { + return stbi__errpuc("bad offset", "Corrupt BMP"); + } + } + + if (info.bpp == 24 && ma == 0xff000000) + s->img_n = 3; + else + s->img_n = ma ? 4 : 3; + if (req_comp && req_comp >= 3) // we can directly decode 3 or 4 + target = req_comp; + else + target = s->img_n; // if they want monochrome, we'll post-convert + + // sanity-check size + if (!stbi__mad3sizes_valid(target, s->img_x, s->img_y, 0)) + return stbi__errpuc("too large", "Corrupt BMP"); + + out = (stbi_uc *) stbi__malloc_mad3(target, s->img_x, s->img_y, 0); + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + if (info.bpp < 16) { + int z=0; + if (psize == 0 || psize > 256) { STBI_FREE(out); return stbi__errpuc("invalid", "Corrupt BMP"); } + for (i=0; i < psize; ++i) { + pal[i][2] = stbi__get8(s); + pal[i][1] = stbi__get8(s); + pal[i][0] = stbi__get8(s); + if (info.hsz != 12) stbi__get8(s); + pal[i][3] = 255; + } + stbi__skip(s, info.offset - info.extra_read - info.hsz - psize * (info.hsz == 12 ? 3 : 4)); + if (info.bpp == 1) width = (s->img_x + 7) >> 3; + else if (info.bpp == 4) width = (s->img_x + 1) >> 1; + else if (info.bpp == 8) width = s->img_x; + else { STBI_FREE(out); return stbi__errpuc("bad bpp", "Corrupt BMP"); } + pad = (-width)&3; + if (info.bpp == 1) { + for (j=0; j < (int) s->img_y; ++j) { + int bit_offset = 7, v = stbi__get8(s); + for (i=0; i < (int) s->img_x; ++i) { + int color = (v>>bit_offset)&0x1; + out[z++] = pal[color][0]; + out[z++] = pal[color][1]; + out[z++] = pal[color][2]; + if (target == 4) out[z++] = 255; + if (i+1 == (int) s->img_x) break; + if((--bit_offset) < 0) { + bit_offset = 7; + v = stbi__get8(s); + } + } + stbi__skip(s, pad); + } + } else { + for (j=0; j < (int) s->img_y; ++j) { + for (i=0; i < (int) s->img_x; i += 2) { + int v=stbi__get8(s),v2=0; + if (info.bpp == 4) { + v2 = v & 15; + v >>= 4; + } + out[z++] = pal[v][0]; + out[z++] = pal[v][1]; + out[z++] = pal[v][2]; + if (target == 4) out[z++] = 255; + if (i+1 == (int) s->img_x) break; + v = (info.bpp == 8) ? stbi__get8(s) : v2; + out[z++] = pal[v][0]; + out[z++] = pal[v][1]; + out[z++] = pal[v][2]; + if (target == 4) out[z++] = 255; + } + stbi__skip(s, pad); + } + } + } else { + int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0; + int z = 0; + int easy=0; + stbi__skip(s, info.offset - info.extra_read - info.hsz); + if (info.bpp == 24) width = 3 * s->img_x; + else if (info.bpp == 16) width = 2*s->img_x; + else /* bpp = 32 and pad = 0 */ width=0; + pad = (-width) & 3; + if (info.bpp == 24) { + easy = 1; + } else if (info.bpp == 32) { + if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000) + easy = 2; + } + if (!easy) { + if (!mr || !mg || !mb) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } + // right shift amt to put high bit in position #7 + rshift = stbi__high_bit(mr)-7; rcount = stbi__bitcount(mr); + gshift = stbi__high_bit(mg)-7; gcount = stbi__bitcount(mg); + bshift = stbi__high_bit(mb)-7; bcount = stbi__bitcount(mb); + ashift = stbi__high_bit(ma)-7; acount = stbi__bitcount(ma); + if (rcount > 8 || gcount > 8 || bcount > 8 || acount > 8) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } + } + for (j=0; j < (int) s->img_y; ++j) { + if (easy) { + for (i=0; i < (int) s->img_x; ++i) { + unsigned char a; + out[z+2] = stbi__get8(s); + out[z+1] = stbi__get8(s); + out[z+0] = stbi__get8(s); + z += 3; + a = (easy == 2 ? stbi__get8(s) : 255); + all_a |= a; + if (target == 4) out[z++] = a; + } + } else { + int bpp = info.bpp; + for (i=0; i < (int) s->img_x; ++i) { + stbi__uint32 v = (bpp == 16 ? (stbi__uint32) stbi__get16le(s) : stbi__get32le(s)); + unsigned int a; + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mr, rshift, rcount)); + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mg, gshift, gcount)); + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mb, bshift, bcount)); + a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255); + all_a |= a; + if (target == 4) out[z++] = STBI__BYTECAST(a); + } + } + stbi__skip(s, pad); + } + } + + // if alpha channel is all 0s, replace with all 255s + if (target == 4 && all_a == 0) + for (i=4*s->img_x*s->img_y-1; i >= 0; i -= 4) + out[i] = 255; + + if (flip_vertically) { + stbi_uc t; + for (j=0; j < (int) s->img_y>>1; ++j) { + stbi_uc *p1 = out + j *s->img_x*target; + stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target; + for (i=0; i < (int) s->img_x*target; ++i) { + t = p1[i]; p1[i] = p2[i]; p2[i] = t; + } + } + } + + if (req_comp && req_comp != target) { + out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y); + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + + *x = s->img_x; + *y = s->img_y; + if (comp) *comp = s->img_n; + return out; +} +#endif + +// Targa Truevision - TGA +// by Jonathan Dummer +#ifndef STBI_NO_TGA +// returns STBI_rgb or whatever, 0 on error +static int stbi__tga_get_comp(int bits_per_pixel, int is_grey, int* is_rgb16) +{ + // only RGB or RGBA (incl. 16bit) or grey allowed + if (is_rgb16) *is_rgb16 = 0; + switch(bits_per_pixel) { + case 8: return STBI_grey; + case 16: if(is_grey) return STBI_grey_alpha; + // fallthrough + case 15: if(is_rgb16) *is_rgb16 = 1; + return STBI_rgb; + case 24: // fallthrough + case 32: return bits_per_pixel/8; + default: return 0; + } +} + +static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp) +{ + int tga_w, tga_h, tga_comp, tga_image_type, tga_bits_per_pixel, tga_colormap_bpp; + int sz, tga_colormap_type; + stbi__get8(s); // discard Offset + tga_colormap_type = stbi__get8(s); // colormap type + if( tga_colormap_type > 1 ) { + stbi__rewind(s); + return 0; // only RGB or indexed allowed + } + tga_image_type = stbi__get8(s); // image type + if ( tga_colormap_type == 1 ) { // colormapped (paletted) image + if (tga_image_type != 1 && tga_image_type != 9) { + stbi__rewind(s); + return 0; + } + stbi__skip(s,4); // skip index of first colormap entry and number of entries + sz = stbi__get8(s); // check bits per palette color entry + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) { + stbi__rewind(s); + return 0; + } + stbi__skip(s,4); // skip image x and y origin + tga_colormap_bpp = sz; + } else { // "normal" image w/o colormap - only RGB or grey allowed, +/- RLE + if ( (tga_image_type != 2) && (tga_image_type != 3) && (tga_image_type != 10) && (tga_image_type != 11) ) { + stbi__rewind(s); + return 0; // only RGB or grey allowed, +/- RLE + } + stbi__skip(s,9); // skip colormap specification and image x/y origin + tga_colormap_bpp = 0; + } + tga_w = stbi__get16le(s); + if( tga_w < 1 ) { + stbi__rewind(s); + return 0; // test width + } + tga_h = stbi__get16le(s); + if( tga_h < 1 ) { + stbi__rewind(s); + return 0; // test height + } + tga_bits_per_pixel = stbi__get8(s); // bits per pixel + stbi__get8(s); // ignore alpha bits + if (tga_colormap_bpp != 0) { + if((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16)) { + // when using a colormap, tga_bits_per_pixel is the size of the indexes + // I don't think anything but 8 or 16bit indexes makes sense + stbi__rewind(s); + return 0; + } + tga_comp = stbi__tga_get_comp(tga_colormap_bpp, 0, NULL); + } else { + tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3) || (tga_image_type == 11), NULL); + } + if(!tga_comp) { + stbi__rewind(s); + return 0; + } + if (x) *x = tga_w; + if (y) *y = tga_h; + if (comp) *comp = tga_comp; + return 1; // seems to have passed everything +} + +static int stbi__tga_test(stbi__context *s) +{ + int res = 0; + int sz, tga_color_type; + stbi__get8(s); // discard Offset + tga_color_type = stbi__get8(s); // color type + if ( tga_color_type > 1 ) goto errorEnd; // only RGB or indexed allowed + sz = stbi__get8(s); // image type + if ( tga_color_type == 1 ) { // colormapped (paletted) image + if (sz != 1 && sz != 9) goto errorEnd; // colortype 1 demands image type 1 or 9 + stbi__skip(s,4); // skip index of first colormap entry and number of entries + sz = stbi__get8(s); // check bits per palette color entry + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; + stbi__skip(s,4); // skip image x and y origin + } else { // "normal" image w/o colormap + if ( (sz != 2) && (sz != 3) && (sz != 10) && (sz != 11) ) goto errorEnd; // only RGB or grey allowed, +/- RLE + stbi__skip(s,9); // skip colormap specification and image x/y origin + } + if ( stbi__get16le(s) < 1 ) goto errorEnd; // test width + if ( stbi__get16le(s) < 1 ) goto errorEnd; // test height + sz = stbi__get8(s); // bits per pixel + if ( (tga_color_type == 1) && (sz != 8) && (sz != 16) ) goto errorEnd; // for colormapped images, bpp is size of an index + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; + + res = 1; // if we got this far, everything's good and we can return 1 instead of 0 + +errorEnd: + stbi__rewind(s); + return res; +} + +// read 16bit value and convert to 24bit RGB +static void stbi__tga_read_rgb16(stbi__context *s, stbi_uc* out) +{ + stbi__uint16 px = (stbi__uint16)stbi__get16le(s); + stbi__uint16 fiveBitMask = 31; + // we have 3 channels with 5bits each + int r = (px >> 10) & fiveBitMask; + int g = (px >> 5) & fiveBitMask; + int b = px & fiveBitMask; + // Note that this saves the data in RGB(A) order, so it doesn't need to be swapped later + out[0] = (stbi_uc)((r * 255)/31); + out[1] = (stbi_uc)((g * 255)/31); + out[2] = (stbi_uc)((b * 255)/31); + + // some people claim that the most significant bit might be used for alpha + // (possibly if an alpha-bit is set in the "image descriptor byte") + // but that only made 16bit test images completely translucent.. + // so let's treat all 15 and 16bit TGAs as RGB with no alpha. +} + +static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + // read in the TGA header stuff + int tga_offset = stbi__get8(s); + int tga_indexed = stbi__get8(s); + int tga_image_type = stbi__get8(s); + int tga_is_RLE = 0; + int tga_palette_start = stbi__get16le(s); + int tga_palette_len = stbi__get16le(s); + int tga_palette_bits = stbi__get8(s); + int tga_x_origin = stbi__get16le(s); + int tga_y_origin = stbi__get16le(s); + int tga_width = stbi__get16le(s); + int tga_height = stbi__get16le(s); + int tga_bits_per_pixel = stbi__get8(s); + int tga_comp, tga_rgb16=0; + int tga_inverted = stbi__get8(s); + // int tga_alpha_bits = tga_inverted & 15; // the 4 lowest bits - unused (useless?) + // image data + unsigned char *tga_data; + unsigned char *tga_palette = NULL; + int i, j; + unsigned char raw_data[4] = {0}; + int RLE_count = 0; + int RLE_repeating = 0; + int read_next_pixel = 1; + STBI_NOTUSED(ri); + STBI_NOTUSED(tga_x_origin); // @TODO + STBI_NOTUSED(tga_y_origin); // @TODO + + if (tga_height > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (tga_width > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + // do a tiny bit of precessing + if ( tga_image_type >= 8 ) + { + tga_image_type -= 8; + tga_is_RLE = 1; + } + tga_inverted = 1 - ((tga_inverted >> 5) & 1); + + // If I'm paletted, then I'll use the number of bits from the palette + if ( tga_indexed ) tga_comp = stbi__tga_get_comp(tga_palette_bits, 0, &tga_rgb16); + else tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3), &tga_rgb16); + + if(!tga_comp) // shouldn't really happen, stbi__tga_test() should have ensured basic consistency + return stbi__errpuc("bad format", "Can't find out TGA pixelformat"); + + // tga info + *x = tga_width; + *y = tga_height; + if (comp) *comp = tga_comp; + + if (!stbi__mad3sizes_valid(tga_width, tga_height, tga_comp, 0)) + return stbi__errpuc("too large", "Corrupt TGA"); + + tga_data = (unsigned char*)stbi__malloc_mad3(tga_width, tga_height, tga_comp, 0); + if (!tga_data) return stbi__errpuc("outofmem", "Out of memory"); + + // skip to the data's starting position (offset usually = 0) + stbi__skip(s, tga_offset ); + + if ( !tga_indexed && !tga_is_RLE && !tga_rgb16 ) { + for (i=0; i < tga_height; ++i) { + int row = tga_inverted ? tga_height -i - 1 : i; + stbi_uc *tga_row = tga_data + row*tga_width*tga_comp; + stbi__getn(s, tga_row, tga_width * tga_comp); + } + } else { + // do I need to load a palette? + if ( tga_indexed) + { + if (tga_palette_len == 0) { /* you have to have at least one entry! */ + STBI_FREE(tga_data); + return stbi__errpuc("bad palette", "Corrupt TGA"); + } + + // any data to skip? (offset usually = 0) + stbi__skip(s, tga_palette_start ); + // load the palette + tga_palette = (unsigned char*)stbi__malloc_mad2(tga_palette_len, tga_comp, 0); + if (!tga_palette) { + STBI_FREE(tga_data); + return stbi__errpuc("outofmem", "Out of memory"); + } + if (tga_rgb16) { + stbi_uc *pal_entry = tga_palette; + STBI_ASSERT(tga_comp == STBI_rgb); + for (i=0; i < tga_palette_len; ++i) { + stbi__tga_read_rgb16(s, pal_entry); + pal_entry += tga_comp; + } + } else if (!stbi__getn(s, tga_palette, tga_palette_len * tga_comp)) { + STBI_FREE(tga_data); + STBI_FREE(tga_palette); + return stbi__errpuc("bad palette", "Corrupt TGA"); + } + } + // load the data + for (i=0; i < tga_width * tga_height; ++i) + { + // if I'm in RLE mode, do I need to get a RLE stbi__pngchunk? + if ( tga_is_RLE ) + { + if ( RLE_count == 0 ) + { + // yep, get the next byte as a RLE command + int RLE_cmd = stbi__get8(s); + RLE_count = 1 + (RLE_cmd & 127); + RLE_repeating = RLE_cmd >> 7; + read_next_pixel = 1; + } else if ( !RLE_repeating ) + { + read_next_pixel = 1; + } + } else + { + read_next_pixel = 1; + } + // OK, if I need to read a pixel, do it now + if ( read_next_pixel ) + { + // load however much data we did have + if ( tga_indexed ) + { + // read in index, then perform the lookup + int pal_idx = (tga_bits_per_pixel == 8) ? stbi__get8(s) : stbi__get16le(s); + if ( pal_idx >= tga_palette_len ) { + // invalid index + pal_idx = 0; + } + pal_idx *= tga_comp; + for (j = 0; j < tga_comp; ++j) { + raw_data[j] = tga_palette[pal_idx+j]; + } + } else if(tga_rgb16) { + STBI_ASSERT(tga_comp == STBI_rgb); + stbi__tga_read_rgb16(s, raw_data); + } else { + // read in the data raw + for (j = 0; j < tga_comp; ++j) { + raw_data[j] = stbi__get8(s); + } + } + // clear the reading flag for the next pixel + read_next_pixel = 0; + } // end of reading a pixel + + // copy data + for (j = 0; j < tga_comp; ++j) + tga_data[i*tga_comp+j] = raw_data[j]; + + // in case we're in RLE mode, keep counting down + --RLE_count; + } + // do I need to invert the image? + if ( tga_inverted ) + { + for (j = 0; j*2 < tga_height; ++j) + { + int index1 = j * tga_width * tga_comp; + int index2 = (tga_height - 1 - j) * tga_width * tga_comp; + for (i = tga_width * tga_comp; i > 0; --i) + { + unsigned char temp = tga_data[index1]; + tga_data[index1] = tga_data[index2]; + tga_data[index2] = temp; + ++index1; + ++index2; + } + } + } + // clear my palette, if I had one + if ( tga_palette != NULL ) + { + STBI_FREE( tga_palette ); + } + } + + // swap RGB - if the source data was RGB16, it already is in the right order + if (tga_comp >= 3 && !tga_rgb16) + { + unsigned char* tga_pixel = tga_data; + for (i=0; i < tga_width * tga_height; ++i) + { + unsigned char temp = tga_pixel[0]; + tga_pixel[0] = tga_pixel[2]; + tga_pixel[2] = temp; + tga_pixel += tga_comp; + } + } + + // convert to target component count + if (req_comp && req_comp != tga_comp) + tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height); + + // the things I do to get rid of an error message, and yet keep + // Microsoft's C compilers happy... [8^( + tga_palette_start = tga_palette_len = tga_palette_bits = + tga_x_origin = tga_y_origin = 0; + STBI_NOTUSED(tga_palette_start); + // OK, done + return tga_data; +} +#endif + +// ************************************************************************************************* +// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB + +#ifndef STBI_NO_PSD +static int stbi__psd_test(stbi__context *s) +{ + int r = (stbi__get32be(s) == 0x38425053); + stbi__rewind(s); + return r; +} + +static int stbi__psd_decode_rle(stbi__context *s, stbi_uc *p, int pixelCount) +{ + int count, nleft, len; + + count = 0; + while ((nleft = pixelCount - count) > 0) { + len = stbi__get8(s); + if (len == 128) { + // No-op. + } else if (len < 128) { + // Copy next len+1 bytes literally. + len++; + if (len > nleft) return 0; // corrupt data + count += len; + while (len) { + *p = stbi__get8(s); + p += 4; + len--; + } + } else if (len > 128) { + stbi_uc val; + // Next -len+1 bytes in the dest are replicated from next source byte. + // (Interpret len as a negative 8-bit int.) + len = 257 - len; + if (len > nleft) return 0; // corrupt data + val = stbi__get8(s); + count += len; + while (len) { + *p = val; + p += 4; + len--; + } + } + } + + return 1; +} + +static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) +{ + int pixelCount; + int channelCount, compression; + int channel, i; + int bitdepth; + int w,h; + stbi_uc *out; + STBI_NOTUSED(ri); + + // Check identifier + if (stbi__get32be(s) != 0x38425053) // "8BPS" + return stbi__errpuc("not PSD", "Corrupt PSD image"); + + // Check file type version. + if (stbi__get16be(s) != 1) + return stbi__errpuc("wrong version", "Unsupported version of PSD image"); + + // Skip 6 reserved bytes. + stbi__skip(s, 6 ); + + // Read the number of channels (R, G, B, A, etc). + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) + return stbi__errpuc("wrong channel count", "Unsupported number of channels in PSD image"); + + // Read the rows and columns of the image. + h = stbi__get32be(s); + w = stbi__get32be(s); + + if (h > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (w > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + // Make sure the depth is 8 bits. + bitdepth = stbi__get16be(s); + if (bitdepth != 8 && bitdepth != 16) + return stbi__errpuc("unsupported bit depth", "PSD bit depth is not 8 or 16 bit"); + + // Make sure the color mode is RGB. + // Valid options are: + // 0: Bitmap + // 1: Grayscale + // 2: Indexed color + // 3: RGB color + // 4: CMYK color + // 7: Multichannel + // 8: Duotone + // 9: Lab color + if (stbi__get16be(s) != 3) + return stbi__errpuc("wrong color format", "PSD is not in RGB color format"); + + // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.) + stbi__skip(s,stbi__get32be(s) ); + + // Skip the image resources. (resolution, pen tool paths, etc) + stbi__skip(s, stbi__get32be(s) ); + + // Skip the reserved data. + stbi__skip(s, stbi__get32be(s) ); + + // Find out if the data is compressed. + // Known values: + // 0: no compression + // 1: RLE compressed + compression = stbi__get16be(s); + if (compression > 1) + return stbi__errpuc("bad compression", "PSD has an unknown compression format"); + + // Check size + if (!stbi__mad3sizes_valid(4, w, h, 0)) + return stbi__errpuc("too large", "Corrupt PSD"); + + // Create the destination image. + + if (!compression && bitdepth == 16 && bpc == 16) { + out = (stbi_uc *) stbi__malloc_mad3(8, w, h, 0); + ri->bits_per_channel = 16; + } else + out = (stbi_uc *) stbi__malloc(4 * w*h); + + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + pixelCount = w*h; + + // Initialize the data to zero. + //memset( out, 0, pixelCount * 4 ); + + // Finally, the image data. + if (compression) { + // RLE as used by .PSD and .TIFF + // Loop until you get the number of unpacked bytes you are expecting: + // Read the next source byte into n. + // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally. + // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times. + // Else if n is 128, noop. + // Endloop + + // The RLE-compressed data is preceded by a 2-byte data count for each row in the data, + // which we're going to just skip. + stbi__skip(s, h * channelCount * 2 ); + + // Read the RLE data by channel. + for (channel = 0; channel < 4; channel++) { + stbi_uc *p; + + p = out+channel; + if (channel >= channelCount) { + // Fill this channel with default data. + for (i = 0; i < pixelCount; i++, p += 4) + *p = (channel == 3 ? 255 : 0); + } else { + // Read the RLE data. + if (!stbi__psd_decode_rle(s, p, pixelCount)) { + STBI_FREE(out); + return stbi__errpuc("corrupt", "bad RLE data"); + } + } + } + + } else { + // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...) + // where each channel consists of an 8-bit (or 16-bit) value for each pixel in the image. + + // Read the data by channel. + for (channel = 0; channel < 4; channel++) { + if (channel >= channelCount) { + // Fill this channel with default data. + if (bitdepth == 16 && bpc == 16) { + stbi__uint16 *q = ((stbi__uint16 *) out) + channel; + stbi__uint16 val = channel == 3 ? 65535 : 0; + for (i = 0; i < pixelCount; i++, q += 4) + *q = val; + } else { + stbi_uc *p = out+channel; + stbi_uc val = channel == 3 ? 255 : 0; + for (i = 0; i < pixelCount; i++, p += 4) + *p = val; + } + } else { + if (ri->bits_per_channel == 16) { // output bpc + stbi__uint16 *q = ((stbi__uint16 *) out) + channel; + for (i = 0; i < pixelCount; i++, q += 4) + *q = (stbi__uint16) stbi__get16be(s); + } else { + stbi_uc *p = out+channel; + if (bitdepth == 16) { // input bpc + for (i = 0; i < pixelCount; i++, p += 4) + *p = (stbi_uc) (stbi__get16be(s) >> 8); + } else { + for (i = 0; i < pixelCount; i++, p += 4) + *p = stbi__get8(s); + } + } + } + } + } + + // remove weird white matte from PSD + if (channelCount >= 4) { + if (ri->bits_per_channel == 16) { + for (i=0; i < w*h; ++i) { + stbi__uint16 *pixel = (stbi__uint16 *) out + 4*i; + if (pixel[3] != 0 && pixel[3] != 65535) { + float a = pixel[3] / 65535.0f; + float ra = 1.0f / a; + float inv_a = 65535.0f * (1 - ra); + pixel[0] = (stbi__uint16) (pixel[0]*ra + inv_a); + pixel[1] = (stbi__uint16) (pixel[1]*ra + inv_a); + pixel[2] = (stbi__uint16) (pixel[2]*ra + inv_a); + } + } + } else { + for (i=0; i < w*h; ++i) { + unsigned char *pixel = out + 4*i; + if (pixel[3] != 0 && pixel[3] != 255) { + float a = pixel[3] / 255.0f; + float ra = 1.0f / a; + float inv_a = 255.0f * (1 - ra); + pixel[0] = (unsigned char) (pixel[0]*ra + inv_a); + pixel[1] = (unsigned char) (pixel[1]*ra + inv_a); + pixel[2] = (unsigned char) (pixel[2]*ra + inv_a); + } + } + } + } + + // convert to desired output format + if (req_comp && req_comp != 4) { + if (ri->bits_per_channel == 16) + out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, 4, req_comp, w, h); + else + out = stbi__convert_format(out, 4, req_comp, w, h); + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + + if (comp) *comp = 4; + *y = h; + *x = w; + + return out; +} +#endif + +// ************************************************************************************************* +// Softimage PIC loader +// by Tom Seddon +// +// See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format +// See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/ + +#ifndef STBI_NO_PIC +static int stbi__pic_is4(stbi__context *s,const char *str) +{ + int i; + for (i=0; i<4; ++i) + if (stbi__get8(s) != (stbi_uc)str[i]) + return 0; + + return 1; +} + +static int stbi__pic_test_core(stbi__context *s) +{ + int i; + + if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) + return 0; + + for(i=0;i<84;++i) + stbi__get8(s); + + if (!stbi__pic_is4(s,"PICT")) + return 0; + + return 1; +} + +typedef struct +{ + stbi_uc size,type,channel; +} stbi__pic_packet; + +static stbi_uc *stbi__readval(stbi__context *s, int channel, stbi_uc *dest) +{ + int mask=0x80, i; + + for (i=0; i<4; ++i, mask>>=1) { + if (channel & mask) { + if (stbi__at_eof(s)) return stbi__errpuc("bad file","PIC file too short"); + dest[i]=stbi__get8(s); + } + } + + return dest; +} + +static void stbi__copyval(int channel,stbi_uc *dest,const stbi_uc *src) +{ + int mask=0x80,i; + + for (i=0;i<4; ++i, mask>>=1) + if (channel&mask) + dest[i]=src[i]; +} + +static stbi_uc *stbi__pic_load_core(stbi__context *s,int width,int height,int *comp, stbi_uc *result) +{ + int act_comp=0,num_packets=0,y,chained; + stbi__pic_packet packets[10]; + + // this will (should...) cater for even some bizarre stuff like having data + // for the same channel in multiple packets. + do { + stbi__pic_packet *packet; + + if (num_packets==sizeof(packets)/sizeof(packets[0])) + return stbi__errpuc("bad format","too many packets"); + + packet = &packets[num_packets++]; + + chained = stbi__get8(s); + packet->size = stbi__get8(s); + packet->type = stbi__get8(s); + packet->channel = stbi__get8(s); + + act_comp |= packet->channel; + + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (reading packets)"); + if (packet->size != 8) return stbi__errpuc("bad format","packet isn't 8bpp"); + } while (chained); + + *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel? + + for(y=0; ytype) { + default: + return stbi__errpuc("bad format","packet has bad compression type"); + + case 0: {//uncompressed + int x; + + for(x=0;xchannel,dest)) + return 0; + break; + } + + case 1://Pure RLE + { + int left=width, i; + + while (left>0) { + stbi_uc count,value[4]; + + count=stbi__get8(s); + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pure read count)"); + + if (count > left) + count = (stbi_uc) left; + + if (!stbi__readval(s,packet->channel,value)) return 0; + + for(i=0; ichannel,dest,value); + left -= count; + } + } + break; + + case 2: {//Mixed RLE + int left=width; + while (left>0) { + int count = stbi__get8(s), i; + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (mixed read count)"); + + if (count >= 128) { // Repeated + stbi_uc value[4]; + + if (count==128) + count = stbi__get16be(s); + else + count -= 127; + if (count > left) + return stbi__errpuc("bad file","scanline overrun"); + + if (!stbi__readval(s,packet->channel,value)) + return 0; + + for(i=0;ichannel,dest,value); + } else { // Raw + ++count; + if (count>left) return stbi__errpuc("bad file","scanline overrun"); + + for(i=0;ichannel,dest)) + return 0; + } + left-=count; + } + break; + } + } + } + } + + return result; +} + +static void *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_comp, stbi__result_info *ri) +{ + stbi_uc *result; + int i, x,y, internal_comp; + STBI_NOTUSED(ri); + + if (!comp) comp = &internal_comp; + + for (i=0; i<92; ++i) + stbi__get8(s); + + x = stbi__get16be(s); + y = stbi__get16be(s); + + if (y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pic header)"); + if (!stbi__mad3sizes_valid(x, y, 4, 0)) return stbi__errpuc("too large", "PIC image too large to decode"); + + stbi__get32be(s); //skip `ratio' + stbi__get16be(s); //skip `fields' + stbi__get16be(s); //skip `pad' + + // intermediate buffer is RGBA + result = (stbi_uc *) stbi__malloc_mad3(x, y, 4, 0); + memset(result, 0xff, x*y*4); + + if (!stbi__pic_load_core(s,x,y,comp, result)) { + STBI_FREE(result); + result=0; + } + *px = x; + *py = y; + if (req_comp == 0) req_comp = *comp; + result=stbi__convert_format(result,4,req_comp,x,y); + + return result; +} + +static int stbi__pic_test(stbi__context *s) +{ + int r = stbi__pic_test_core(s); + stbi__rewind(s); + return r; +} +#endif + +// ************************************************************************************************* +// GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb + +#ifndef STBI_NO_GIF +typedef struct +{ + stbi__int16 prefix; + stbi_uc first; + stbi_uc suffix; +} stbi__gif_lzw; + +typedef struct +{ + int w,h; + stbi_uc *out; // output buffer (always 4 components) + stbi_uc *background; // The current "background" as far as a gif is concerned + stbi_uc *history; + int flags, bgindex, ratio, transparent, eflags; + stbi_uc pal[256][4]; + stbi_uc lpal[256][4]; + stbi__gif_lzw codes[8192]; + stbi_uc *color_table; + int parse, step; + int lflags; + int start_x, start_y; + int max_x, max_y; + int cur_x, cur_y; + int line_size; + int delay; +} stbi__gif; + +static int stbi__gif_test_raw(stbi__context *s) +{ + int sz; + if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return 0; + sz = stbi__get8(s); + if (sz != '9' && sz != '7') return 0; + if (stbi__get8(s) != 'a') return 0; + return 1; +} + +static int stbi__gif_test(stbi__context *s) +{ + int r = stbi__gif_test_raw(s); + stbi__rewind(s); + return r; +} + +static void stbi__gif_parse_colortable(stbi__context *s, stbi_uc pal[256][4], int num_entries, int transp) +{ + int i; + for (i=0; i < num_entries; ++i) { + pal[i][2] = stbi__get8(s); + pal[i][1] = stbi__get8(s); + pal[i][0] = stbi__get8(s); + pal[i][3] = transp == i ? 0 : 255; + } +} + +static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_info) +{ + stbi_uc version; + if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') + return stbi__err("not GIF", "Corrupt GIF"); + + version = stbi__get8(s); + if (version != '7' && version != '9') return stbi__err("not GIF", "Corrupt GIF"); + if (stbi__get8(s) != 'a') return stbi__err("not GIF", "Corrupt GIF"); + + stbi__g_failure_reason = ""; + g->w = stbi__get16le(s); + g->h = stbi__get16le(s); + g->flags = stbi__get8(s); + g->bgindex = stbi__get8(s); + g->ratio = stbi__get8(s); + g->transparent = -1; + + if (g->w > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + if (g->h > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + + if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments + + if (is_info) return 1; + + if (g->flags & 0x80) + stbi__gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1); + + return 1; +} + +static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp) +{ + stbi__gif* g = (stbi__gif*) stbi__malloc(sizeof(stbi__gif)); + if (!stbi__gif_header(s, g, comp, 1)) { + STBI_FREE(g); + stbi__rewind( s ); + return 0; + } + if (x) *x = g->w; + if (y) *y = g->h; + STBI_FREE(g); + return 1; +} + +static void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code) +{ + stbi_uc *p, *c; + int idx; + + // recurse to decode the prefixes, since the linked-list is backwards, + // and working backwards through an interleaved image would be nasty + if (g->codes[code].prefix >= 0) + stbi__out_gif_code(g, g->codes[code].prefix); + + if (g->cur_y >= g->max_y) return; + + idx = g->cur_x + g->cur_y; + p = &g->out[idx]; + g->history[idx / 4] = 1; + + c = &g->color_table[g->codes[code].suffix * 4]; + if (c[3] > 128) { // don't render transparent pixels; + p[0] = c[2]; + p[1] = c[1]; + p[2] = c[0]; + p[3] = c[3]; + } + g->cur_x += 4; + + if (g->cur_x >= g->max_x) { + g->cur_x = g->start_x; + g->cur_y += g->step; + + while (g->cur_y >= g->max_y && g->parse > 0) { + g->step = (1 << g->parse) * g->line_size; + g->cur_y = g->start_y + (g->step >> 1); + --g->parse; + } + } +} + +static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g) +{ + stbi_uc lzw_cs; + stbi__int32 len, init_code; + stbi__uint32 first; + stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear; + stbi__gif_lzw *p; + + lzw_cs = stbi__get8(s); + if (lzw_cs > 12) return NULL; + clear = 1 << lzw_cs; + first = 1; + codesize = lzw_cs + 1; + codemask = (1 << codesize) - 1; + bits = 0; + valid_bits = 0; + for (init_code = 0; init_code < clear; init_code++) { + g->codes[init_code].prefix = -1; + g->codes[init_code].first = (stbi_uc) init_code; + g->codes[init_code].suffix = (stbi_uc) init_code; + } + + // support no starting clear code + avail = clear+2; + oldcode = -1; + + len = 0; + for(;;) { + if (valid_bits < codesize) { + if (len == 0) { + len = stbi__get8(s); // start new block + if (len == 0) + return g->out; + } + --len; + bits |= (stbi__int32) stbi__get8(s) << valid_bits; + valid_bits += 8; + } else { + stbi__int32 code = bits & codemask; + bits >>= codesize; + valid_bits -= codesize; + // @OPTIMIZE: is there some way we can accelerate the non-clear path? + if (code == clear) { // clear code + codesize = lzw_cs + 1; + codemask = (1 << codesize) - 1; + avail = clear + 2; + oldcode = -1; + first = 0; + } else if (code == clear + 1) { // end of stream code + stbi__skip(s, len); + while ((len = stbi__get8(s)) > 0) + stbi__skip(s,len); + return g->out; + } else if (code <= avail) { + if (first) { + return stbi__errpuc("no clear code", "Corrupt GIF"); + } + + if (oldcode >= 0) { + p = &g->codes[avail++]; + if (avail > 8192) { + return stbi__errpuc("too many codes", "Corrupt GIF"); + } + + p->prefix = (stbi__int16) oldcode; + p->first = g->codes[oldcode].first; + p->suffix = (code == avail) ? p->first : g->codes[code].first; + } else if (code == avail) + return stbi__errpuc("illegal code in raster", "Corrupt GIF"); + + stbi__out_gif_code(g, (stbi__uint16) code); + + if ((avail & codemask) == 0 && avail <= 0x0FFF) { + codesize++; + codemask = (1 << codesize) - 1; + } + + oldcode = code; + } else { + return stbi__errpuc("illegal code in raster", "Corrupt GIF"); + } + } + } +} + +// this function is designed to support animated gifs, although stb_image doesn't support it +// two back is the image from two frames ago, used for a very specific disposal format +static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp, stbi_uc *two_back) +{ + int dispose; + int first_frame; + int pi; + int pcount; + STBI_NOTUSED(req_comp); + + // on first frame, any non-written pixels get the background colour (non-transparent) + first_frame = 0; + if (g->out == 0) { + if (!stbi__gif_header(s, g, comp,0)) return 0; // stbi__g_failure_reason set by stbi__gif_header + if (!stbi__mad3sizes_valid(4, g->w, g->h, 0)) + return stbi__errpuc("too large", "GIF image is too large"); + pcount = g->w * g->h; + g->out = (stbi_uc *) stbi__malloc(4 * pcount); + g->background = (stbi_uc *) stbi__malloc(4 * pcount); + g->history = (stbi_uc *) stbi__malloc(pcount); + if (!g->out || !g->background || !g->history) + return stbi__errpuc("outofmem", "Out of memory"); + + // image is treated as "transparent" at the start - ie, nothing overwrites the current background; + // background colour is only used for pixels that are not rendered first frame, after that "background" + // color refers to the color that was there the previous frame. + memset(g->out, 0x00, 4 * pcount); + memset(g->background, 0x00, 4 * pcount); // state of the background (starts transparent) + memset(g->history, 0x00, pcount); // pixels that were affected previous frame + first_frame = 1; + } else { + // second frame - how do we dispose of the previous one? + dispose = (g->eflags & 0x1C) >> 2; + pcount = g->w * g->h; + + if ((dispose == 3) && (two_back == 0)) { + dispose = 2; // if I don't have an image to revert back to, default to the old background + } + + if (dispose == 3) { // use previous graphic + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi]) { + memcpy( &g->out[pi * 4], &two_back[pi * 4], 4 ); + } + } + } else if (dispose == 2) { + // restore what was changed last frame to background before that frame; + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi]) { + memcpy( &g->out[pi * 4], &g->background[pi * 4], 4 ); + } + } + } else { + // This is a non-disposal case eithe way, so just + // leave the pixels as is, and they will become the new background + // 1: do not dispose + // 0: not specified. + } + + // background is what out is after the undoing of the previou frame; + memcpy( g->background, g->out, 4 * g->w * g->h ); + } + + // clear my history; + memset( g->history, 0x00, g->w * g->h ); // pixels that were affected previous frame + + for (;;) { + int tag = stbi__get8(s); + switch (tag) { + case 0x2C: /* Image Descriptor */ + { + stbi__int32 x, y, w, h; + stbi_uc *o; + + x = stbi__get16le(s); + y = stbi__get16le(s); + w = stbi__get16le(s); + h = stbi__get16le(s); + if (((x + w) > (g->w)) || ((y + h) > (g->h))) + return stbi__errpuc("bad Image Descriptor", "Corrupt GIF"); + + g->line_size = g->w * 4; + g->start_x = x * 4; + g->start_y = y * g->line_size; + g->max_x = g->start_x + w * 4; + g->max_y = g->start_y + h * g->line_size; + g->cur_x = g->start_x; + g->cur_y = g->start_y; + + // if the width of the specified rectangle is 0, that means + // we may not see *any* pixels or the image is malformed; + // to make sure this is caught, move the current y down to + // max_y (which is what out_gif_code checks). + if (w == 0) + g->cur_y = g->max_y; + + g->lflags = stbi__get8(s); + + if (g->lflags & 0x40) { + g->step = 8 * g->line_size; // first interlaced spacing + g->parse = 3; + } else { + g->step = g->line_size; + g->parse = 0; + } + + if (g->lflags & 0x80) { + stbi__gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1); + g->color_table = (stbi_uc *) g->lpal; + } else if (g->flags & 0x80) { + g->color_table = (stbi_uc *) g->pal; + } else + return stbi__errpuc("missing color table", "Corrupt GIF"); + + o = stbi__process_gif_raster(s, g); + if (!o) return NULL; + + // if this was the first frame, + pcount = g->w * g->h; + if (first_frame && (g->bgindex > 0)) { + // if first frame, any pixel not drawn to gets the background color + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi] == 0) { + g->pal[g->bgindex][3] = 255; // just in case it was made transparent, undo that; It will be reset next frame if need be; + memcpy( &g->out[pi * 4], &g->pal[g->bgindex], 4 ); + } + } + } + + return o; + } + + case 0x21: // Comment Extension. + { + int len; + int ext = stbi__get8(s); + if (ext == 0xF9) { // Graphic Control Extension. + len = stbi__get8(s); + if (len == 4) { + g->eflags = stbi__get8(s); + g->delay = 10 * stbi__get16le(s); // delay - 1/100th of a second, saving as 1/1000ths. + + // unset old transparent + if (g->transparent >= 0) { + g->pal[g->transparent][3] = 255; + } + if (g->eflags & 0x01) { + g->transparent = stbi__get8(s); + if (g->transparent >= 0) { + g->pal[g->transparent][3] = 0; + } + } else { + // don't need transparent + stbi__skip(s, 1); + g->transparent = -1; + } + } else { + stbi__skip(s, len); + break; + } + } + while ((len = stbi__get8(s)) != 0) { + stbi__skip(s, len); + } + break; + } + + case 0x3B: // gif stream termination code + return (stbi_uc *) s; // using '1' causes warning on some compilers + + default: + return stbi__errpuc("unknown code", "Corrupt GIF"); + } + } +} + +static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp) +{ + if (stbi__gif_test(s)) { + int layers = 0; + stbi_uc *u = 0; + stbi_uc *out = 0; + stbi_uc *two_back = 0; + stbi__gif g; + int stride; + int out_size = 0; + int delays_size = 0; + memset(&g, 0, sizeof(g)); + if (delays) { + *delays = 0; + } + + do { + u = stbi__gif_load_next(s, &g, comp, req_comp, two_back); + if (u == (stbi_uc *) s) u = 0; // end of animated gif marker + + if (u) { + *x = g.w; + *y = g.h; + ++layers; + stride = g.w * g.h * 4; + + if (out) { + void *tmp = (stbi_uc*) STBI_REALLOC_SIZED( out, out_size, layers * stride ); + if (NULL == tmp) { + STBI_FREE(g.out); + STBI_FREE(g.history); + STBI_FREE(g.background); + return stbi__errpuc("outofmem", "Out of memory"); + } + else { + out = (stbi_uc*) tmp; + out_size = layers * stride; + } + + if (delays) { + *delays = (int*) STBI_REALLOC_SIZED( *delays, delays_size, sizeof(int) * layers ); + delays_size = layers * sizeof(int); + } + } else { + out = (stbi_uc*)stbi__malloc( layers * stride ); + out_size = layers * stride; + if (delays) { + *delays = (int*) stbi__malloc( layers * sizeof(int) ); + delays_size = layers * sizeof(int); + } + } + memcpy( out + ((layers - 1) * stride), u, stride ); + if (layers >= 2) { + two_back = out - 2 * stride; + } + + if (delays) { + (*delays)[layers - 1U] = g.delay; + } + } + } while (u != 0); + + // free temp buffer; + STBI_FREE(g.out); + STBI_FREE(g.history); + STBI_FREE(g.background); + + // do the final conversion after loading everything; + if (req_comp && req_comp != 4) + out = stbi__convert_format(out, 4, req_comp, layers * g.w, g.h); + + *z = layers; + return out; + } else { + return stbi__errpuc("not GIF", "Image was not as a gif type."); + } +} + +static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi_uc *u = 0; + stbi__gif g; + memset(&g, 0, sizeof(g)); + STBI_NOTUSED(ri); + + u = stbi__gif_load_next(s, &g, comp, req_comp, 0); + if (u == (stbi_uc *) s) u = 0; // end of animated gif marker + if (u) { + *x = g.w; + *y = g.h; + + // moved conversion to after successful load so that the same + // can be done for multiple frames. + if (req_comp && req_comp != 4) + u = stbi__convert_format(u, 4, req_comp, g.w, g.h); + } else if (g.out) { + // if there was an error and we allocated an image buffer, free it! + STBI_FREE(g.out); + } + + // free buffers needed for multiple frame loading; + STBI_FREE(g.history); + STBI_FREE(g.background); + + return u; +} + +static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp) +{ + return stbi__gif_info_raw(s,x,y,comp); +} +#endif + +// ************************************************************************************************* +// Radiance RGBE HDR loader +// originally by Nicolas Schulz +#ifndef STBI_NO_HDR +static int stbi__hdr_test_core(stbi__context *s, const char *signature) +{ + int i; + for (i=0; signature[i]; ++i) + if (stbi__get8(s) != signature[i]) + return 0; + stbi__rewind(s); + return 1; +} + +static int stbi__hdr_test(stbi__context* s) +{ + int r = stbi__hdr_test_core(s, "#?RADIANCE\n"); + stbi__rewind(s); + if(!r) { + r = stbi__hdr_test_core(s, "#?RGBE\n"); + stbi__rewind(s); + } + return r; +} + +#define STBI__HDR_BUFLEN 1024 +static char *stbi__hdr_gettoken(stbi__context *z, char *buffer) +{ + int len=0; + char c = '\0'; + + c = (char) stbi__get8(z); + + while (!stbi__at_eof(z) && c != '\n') { + buffer[len++] = c; + if (len == STBI__HDR_BUFLEN-1) { + // flush to end of line + while (!stbi__at_eof(z) && stbi__get8(z) != '\n') + ; + break; + } + c = (char) stbi__get8(z); + } + + buffer[len] = 0; + return buffer; +} + +static void stbi__hdr_convert(float *output, stbi_uc *input, int req_comp) +{ + if ( input[3] != 0 ) { + float f1; + // Exponent + f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8)); + if (req_comp <= 2) + output[0] = (input[0] + input[1] + input[2]) * f1 / 3; + else { + output[0] = input[0] * f1; + output[1] = input[1] * f1; + output[2] = input[2] * f1; + } + if (req_comp == 2) output[1] = 1; + if (req_comp == 4) output[3] = 1; + } else { + switch (req_comp) { + case 4: output[3] = 1; /* fallthrough */ + case 3: output[0] = output[1] = output[2] = 0; + break; + case 2: output[1] = 1; /* fallthrough */ + case 1: output[0] = 0; + break; + } + } +} + +static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + char buffer[STBI__HDR_BUFLEN]; + char *token; + int valid = 0; + int width, height; + stbi_uc *scanline; + float *hdr_data; + int len; + unsigned char count, value; + int i, j, k, c1,c2, z; + const char *headerToken; + STBI_NOTUSED(ri); + + // Check identifier + headerToken = stbi__hdr_gettoken(s,buffer); + if (strcmp(headerToken, "#?RADIANCE") != 0 && strcmp(headerToken, "#?RGBE") != 0) + return stbi__errpf("not HDR", "Corrupt HDR image"); + + // Parse header + for(;;) { + token = stbi__hdr_gettoken(s,buffer); + if (token[0] == 0) break; + if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; + } + + if (!valid) return stbi__errpf("unsupported format", "Unsupported HDR format"); + + // Parse width and height + // can't use sscanf() if we're not using stdio! + token = stbi__hdr_gettoken(s,buffer); + if (strncmp(token, "-Y ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); + token += 3; + height = (int) strtol(token, &token, 10); + while (*token == ' ') ++token; + if (strncmp(token, "+X ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); + token += 3; + width = (int) strtol(token, NULL, 10); + + if (height > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)"); + if (width > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)"); + + *x = width; + *y = height; + + if (comp) *comp = 3; + if (req_comp == 0) req_comp = 3; + + if (!stbi__mad4sizes_valid(width, height, req_comp, sizeof(float), 0)) + return stbi__errpf("too large", "HDR image is too large"); + + // Read data + hdr_data = (float *) stbi__malloc_mad4(width, height, req_comp, sizeof(float), 0); + if (!hdr_data) + return stbi__errpf("outofmem", "Out of memory"); + + // Load image data + // image data is stored as some number of sca + if ( width < 8 || width >= 32768) { + // Read flat data + for (j=0; j < height; ++j) { + for (i=0; i < width; ++i) { + stbi_uc rgbe[4]; + main_decode_loop: + stbi__getn(s, rgbe, 4); + stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp); + } + } + } else { + // Read RLE-encoded data + scanline = NULL; + + for (j = 0; j < height; ++j) { + c1 = stbi__get8(s); + c2 = stbi__get8(s); + len = stbi__get8(s); + if (c1 != 2 || c2 != 2 || (len & 0x80)) { + // not run-length encoded, so we have to actually use THIS data as a decoded + // pixel (note this can't be a valid pixel--one of RGB must be >= 128) + stbi_uc rgbe[4]; + rgbe[0] = (stbi_uc) c1; + rgbe[1] = (stbi_uc) c2; + rgbe[2] = (stbi_uc) len; + rgbe[3] = (stbi_uc) stbi__get8(s); + stbi__hdr_convert(hdr_data, rgbe, req_comp); + i = 1; + j = 0; + STBI_FREE(scanline); + goto main_decode_loop; // yes, this makes no sense + } + len <<= 8; + len |= stbi__get8(s); + if (len != width) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("invalid decoded scanline length", "corrupt HDR"); } + if (scanline == NULL) { + scanline = (stbi_uc *) stbi__malloc_mad2(width, 4, 0); + if (!scanline) { + STBI_FREE(hdr_data); + return stbi__errpf("outofmem", "Out of memory"); + } + } + + for (k = 0; k < 4; ++k) { + int nleft; + i = 0; + while ((nleft = width - i) > 0) { + count = stbi__get8(s); + if (count > 128) { + // Run + value = stbi__get8(s); + count -= 128; + if (count > nleft) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } + for (z = 0; z < count; ++z) + scanline[i++ * 4 + k] = value; + } else { + // Dump + if (count > nleft) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } + for (z = 0; z < count; ++z) + scanline[i++ * 4 + k] = stbi__get8(s); + } + } + } + for (i=0; i < width; ++i) + stbi__hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp); + } + if (scanline) + STBI_FREE(scanline); + } + + return hdr_data; +} + +static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp) +{ + char buffer[STBI__HDR_BUFLEN]; + char *token; + int valid = 0; + int dummy; + + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + if (stbi__hdr_test(s) == 0) { + stbi__rewind( s ); + return 0; + } + + for(;;) { + token = stbi__hdr_gettoken(s,buffer); + if (token[0] == 0) break; + if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; + } + + if (!valid) { + stbi__rewind( s ); + return 0; + } + token = stbi__hdr_gettoken(s,buffer); + if (strncmp(token, "-Y ", 3)) { + stbi__rewind( s ); + return 0; + } + token += 3; + *y = (int) strtol(token, &token, 10); + while (*token == ' ') ++token; + if (strncmp(token, "+X ", 3)) { + stbi__rewind( s ); + return 0; + } + token += 3; + *x = (int) strtol(token, NULL, 10); + *comp = 3; + return 1; +} +#endif // STBI_NO_HDR + +#ifndef STBI_NO_BMP +static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp) +{ + void *p; + stbi__bmp_data info; + + info.all_a = 255; + p = stbi__bmp_parse_header(s, &info); + stbi__rewind( s ); + if (p == NULL) + return 0; + if (x) *x = s->img_x; + if (y) *y = s->img_y; + if (comp) { + if (info.bpp == 24 && info.ma == 0xff000000) + *comp = 3; + else + *comp = info.ma ? 4 : 3; + } + return 1; +} +#endif + +#ifndef STBI_NO_PSD +static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp) +{ + int channelCount, dummy, depth; + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + if (stbi__get32be(s) != 0x38425053) { + stbi__rewind( s ); + return 0; + } + if (stbi__get16be(s) != 1) { + stbi__rewind( s ); + return 0; + } + stbi__skip(s, 6); + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) { + stbi__rewind( s ); + return 0; + } + *y = stbi__get32be(s); + *x = stbi__get32be(s); + depth = stbi__get16be(s); + if (depth != 8 && depth != 16) { + stbi__rewind( s ); + return 0; + } + if (stbi__get16be(s) != 3) { + stbi__rewind( s ); + return 0; + } + *comp = 4; + return 1; +} + +static int stbi__psd_is16(stbi__context *s) +{ + int channelCount, depth; + if (stbi__get32be(s) != 0x38425053) { + stbi__rewind( s ); + return 0; + } + if (stbi__get16be(s) != 1) { + stbi__rewind( s ); + return 0; + } + stbi__skip(s, 6); + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) { + stbi__rewind( s ); + return 0; + } + (void) stbi__get32be(s); + (void) stbi__get32be(s); + depth = stbi__get16be(s); + if (depth != 16) { + stbi__rewind( s ); + return 0; + } + return 1; +} +#endif + +#ifndef STBI_NO_PIC +static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp) +{ + int act_comp=0,num_packets=0,chained,dummy; + stbi__pic_packet packets[10]; + + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) { + stbi__rewind(s); + return 0; + } + + stbi__skip(s, 88); + + *x = stbi__get16be(s); + *y = stbi__get16be(s); + if (stbi__at_eof(s)) { + stbi__rewind( s); + return 0; + } + if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) { + stbi__rewind( s ); + return 0; + } + + stbi__skip(s, 8); + + do { + stbi__pic_packet *packet; + + if (num_packets==sizeof(packets)/sizeof(packets[0])) + return 0; + + packet = &packets[num_packets++]; + chained = stbi__get8(s); + packet->size = stbi__get8(s); + packet->type = stbi__get8(s); + packet->channel = stbi__get8(s); + act_comp |= packet->channel; + + if (stbi__at_eof(s)) { + stbi__rewind( s ); + return 0; + } + if (packet->size != 8) { + stbi__rewind( s ); + return 0; + } + } while (chained); + + *comp = (act_comp & 0x10 ? 4 : 3); + + return 1; +} +#endif + +// ************************************************************************************************* +// Portable Gray Map and Portable Pixel Map loader +// by Ken Miller +// +// PGM: http://netpbm.sourceforge.net/doc/pgm.html +// PPM: http://netpbm.sourceforge.net/doc/ppm.html +// +// Known limitations: +// Does not support comments in the header section +// Does not support ASCII image data (formats P2 and P3) +// Does not support 16-bit-per-channel + +#ifndef STBI_NO_PNM + +static int stbi__pnm_test(stbi__context *s) +{ + char p, t; + p = (char) stbi__get8(s); + t = (char) stbi__get8(s); + if (p != 'P' || (t != '5' && t != '6')) { + stbi__rewind( s ); + return 0; + } + return 1; +} + +static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi_uc *out; + STBI_NOTUSED(ri); + + if (!stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n)) + return 0; + + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + *x = s->img_x; + *y = s->img_y; + if (comp) *comp = s->img_n; + + if (!stbi__mad3sizes_valid(s->img_n, s->img_x, s->img_y, 0)) + return stbi__errpuc("too large", "PNM too large"); + + out = (stbi_uc *) stbi__malloc_mad3(s->img_n, s->img_x, s->img_y, 0); + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + stbi__getn(s, out, s->img_n * s->img_x * s->img_y); + + if (req_comp && req_comp != s->img_n) { + out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y); + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + return out; +} + +static int stbi__pnm_isspace(char c) +{ + return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r'; +} + +static void stbi__pnm_skip_whitespace(stbi__context *s, char *c) +{ + for (;;) { + while (!stbi__at_eof(s) && stbi__pnm_isspace(*c)) + *c = (char) stbi__get8(s); + + if (stbi__at_eof(s) || *c != '#') + break; + + while (!stbi__at_eof(s) && *c != '\n' && *c != '\r' ) + *c = (char) stbi__get8(s); + } +} + +static int stbi__pnm_isdigit(char c) +{ + return c >= '0' && c <= '9'; +} + +static int stbi__pnm_getinteger(stbi__context *s, char *c) +{ + int value = 0; + + while (!stbi__at_eof(s) && stbi__pnm_isdigit(*c)) { + value = value*10 + (*c - '0'); + *c = (char) stbi__get8(s); + } + + return value; +} + +static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp) +{ + int maxv, dummy; + char c, p, t; + + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + stbi__rewind(s); + + // Get identifier + p = (char) stbi__get8(s); + t = (char) stbi__get8(s); + if (p != 'P' || (t != '5' && t != '6')) { + stbi__rewind(s); + return 0; + } + + *comp = (t == '6') ? 3 : 1; // '5' is 1-component .pgm; '6' is 3-component .ppm + + c = (char) stbi__get8(s); + stbi__pnm_skip_whitespace(s, &c); + + *x = stbi__pnm_getinteger(s, &c); // read width + stbi__pnm_skip_whitespace(s, &c); + + *y = stbi__pnm_getinteger(s, &c); // read height + stbi__pnm_skip_whitespace(s, &c); + + maxv = stbi__pnm_getinteger(s, &c); // read max value + + if (maxv > 255) + return stbi__err("max value > 255", "PPM image not 8-bit"); + else + return 1; +} +#endif + +static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp) +{ + #ifndef STBI_NO_JPEG + if (stbi__jpeg_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PNG + if (stbi__png_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_GIF + if (stbi__gif_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_BMP + if (stbi__bmp_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PSD + if (stbi__psd_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PIC + if (stbi__pic_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PNM + if (stbi__pnm_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_HDR + if (stbi__hdr_info(s, x, y, comp)) return 1; + #endif + + // test tga last because it's a crappy test! + #ifndef STBI_NO_TGA + if (stbi__tga_info(s, x, y, comp)) + return 1; + #endif + return stbi__err("unknown image type", "Image not of any known type, or corrupt"); +} + +static int stbi__is_16_main(stbi__context *s) +{ + #ifndef STBI_NO_PNG + if (stbi__png_is16(s)) return 1; + #endif + + #ifndef STBI_NO_PSD + if (stbi__psd_is16(s)) return 1; + #endif + + return 0; +} + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result; + if (!f) return stbi__err("can't fopen", "Unable to open file"); + result = stbi_info_from_file(f, x, y, comp); + fclose(f); + return result; +} + +STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp) +{ + int r; + stbi__context s; + long pos = ftell(f); + stbi__start_file(&s, f); + r = stbi__info_main(&s,x,y,comp); + fseek(f,pos,SEEK_SET); + return r; +} + +STBIDEF int stbi_is_16_bit(char const *filename) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result; + if (!f) return stbi__err("can't fopen", "Unable to open file"); + result = stbi_is_16_bit_from_file(f); + fclose(f); + return result; +} + +STBIDEF int stbi_is_16_bit_from_file(FILE *f) +{ + int r; + stbi__context s; + long pos = ftell(f); + stbi__start_file(&s, f); + r = stbi__is_16_main(&s); + fseek(f,pos,SEEK_SET); + return r; +} +#endif // !STBI_NO_STDIO + +STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__info_main(&s,x,y,comp); +} + +STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); + return stbi__info_main(&s,x,y,comp); +} + +STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__is_16_main(&s); +} + +STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *c, void *user) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); + return stbi__is_16_main(&s); +} + +#endif // STB_IMAGE_IMPLEMENTATION + +/* + revision history: + 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs + 2.19 (2018-02-11) fix warning + 2.18 (2018-01-30) fix warnings + 2.17 (2018-01-29) change sbti__shiftsigned to avoid clang -O2 bug + 1-bit BMP + *_is_16_bit api + avoid warnings + 2.16 (2017-07-23) all functions have 16-bit variants; + STBI_NO_STDIO works again; + compilation fixes; + fix rounding in unpremultiply; + optimize vertical flip; + disable raw_len validation; + documentation fixes + 2.15 (2017-03-18) fix png-1,2,4 bug; now all Imagenet JPGs decode; + warning fixes; disable run-time SSE detection on gcc; + uniform handling of optional "return" values; + thread-safe initialization of zlib tables + 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs + 2.13 (2016-11-29) add 16-bit API, only supported for PNG right now + 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes + 2.11 (2016-04-02) allocate large structures on the stack + remove white matting for transparent PSD + fix reported channel count for PNG & BMP + re-enable SSE2 in non-gcc 64-bit + support RGB-formatted JPEG + read 16-bit PNGs (only as 8-bit) + 2.10 (2016-01-22) avoid warning introduced in 2.09 by STBI_REALLOC_SIZED + 2.09 (2016-01-16) allow comments in PNM files + 16-bit-per-pixel TGA (not bit-per-component) + info() for TGA could break due to .hdr handling + info() for BMP to shares code instead of sloppy parse + can use STBI_REALLOC_SIZED if allocator doesn't support realloc + code cleanup + 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA + 2.07 (2015-09-13) fix compiler warnings + partial animated GIF support + limited 16-bpc PSD support + #ifdef unused functions + bug with < 92 byte PIC,PNM,HDR,TGA + 2.06 (2015-04-19) fix bug where PSD returns wrong '*comp' value + 2.05 (2015-04-19) fix bug in progressive JPEG handling, fix warning + 2.04 (2015-04-15) try to re-enable SIMD on MinGW 64-bit + 2.03 (2015-04-12) extra corruption checking (mmozeiko) + stbi_set_flip_vertically_on_load (nguillemot) + fix NEON support; fix mingw support + 2.02 (2015-01-19) fix incorrect assert, fix warning + 2.01 (2015-01-17) fix various warnings; suppress SIMD on gcc 32-bit without -msse2 + 2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG + 2.00 (2014-12-25) optimize JPG, including x86 SSE2 & NEON SIMD (ryg) + progressive JPEG (stb) + PGM/PPM support (Ken Miller) + STBI_MALLOC,STBI_REALLOC,STBI_FREE + GIF bugfix -- seemingly never worked + STBI_NO_*, STBI_ONLY_* + 1.48 (2014-12-14) fix incorrectly-named assert() + 1.47 (2014-12-14) 1/2/4-bit PNG support, both direct and paletted (Omar Cornut & stb) + optimize PNG (ryg) + fix bug in interlaced PNG with user-specified channel count (stb) + 1.46 (2014-08-26) + fix broken tRNS chunk (colorkey-style transparency) in non-paletted PNG + 1.45 (2014-08-16) + fix MSVC-ARM internal compiler error by wrapping malloc + 1.44 (2014-08-07) + various warning fixes from Ronny Chevalier + 1.43 (2014-07-15) + fix MSVC-only compiler problem in code changed in 1.42 + 1.42 (2014-07-09) + don't define _CRT_SECURE_NO_WARNINGS (affects user code) + fixes to stbi__cleanup_jpeg path + added STBI_ASSERT to avoid requiring assert.h + 1.41 (2014-06-25) + fix search&replace from 1.36 that messed up comments/error messages + 1.40 (2014-06-22) + fix gcc struct-initialization warning + 1.39 (2014-06-15) + fix to TGA optimization when req_comp != number of components in TGA; + fix to GIF loading because BMP wasn't rewinding (whoops, no GIFs in my test suite) + add support for BMP version 5 (more ignored fields) + 1.38 (2014-06-06) + suppress MSVC warnings on integer casts truncating values + fix accidental rename of 'skip' field of I/O + 1.37 (2014-06-04) + remove duplicate typedef + 1.36 (2014-06-03) + convert to header file single-file library + if de-iphone isn't set, load iphone images color-swapped instead of returning NULL + 1.35 (2014-05-27) + various warnings + fix broken STBI_SIMD path + fix bug where stbi_load_from_file no longer left file pointer in correct place + fix broken non-easy path for 32-bit BMP (possibly never used) + TGA optimization by Arseny Kapoulkine + 1.34 (unknown) + use STBI_NOTUSED in stbi__resample_row_generic(), fix one more leak in tga failure case + 1.33 (2011-07-14) + make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements + 1.32 (2011-07-13) + support for "info" function for all supported filetypes (SpartanJ) + 1.31 (2011-06-20) + a few more leak fixes, bug in PNG handling (SpartanJ) + 1.30 (2011-06-11) + added ability to load files via callbacks to accomidate custom input streams (Ben Wenger) + removed deprecated format-specific test/load functions + removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway + error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha) + fix inefficiency in decoding 32-bit BMP (David Woo) + 1.29 (2010-08-16) + various warning fixes from Aurelien Pocheville + 1.28 (2010-08-01) + fix bug in GIF palette transparency (SpartanJ) + 1.27 (2010-08-01) + cast-to-stbi_uc to fix warnings + 1.26 (2010-07-24) + fix bug in file buffering for PNG reported by SpartanJ + 1.25 (2010-07-17) + refix trans_data warning (Won Chun) + 1.24 (2010-07-12) + perf improvements reading from files on platforms with lock-heavy fgetc() + minor perf improvements for jpeg + deprecated type-specific functions so we'll get feedback if they're needed + attempt to fix trans_data warning (Won Chun) + 1.23 fixed bug in iPhone support + 1.22 (2010-07-10) + removed image *writing* support + stbi_info support from Jetro Lauha + GIF support from Jean-Marc Lienher + iPhone PNG-extensions from James Brown + warning-fixes from Nicolas Schulz and Janez Zemva (i.stbi__err. Janez (U+017D)emva) + 1.21 fix use of 'stbi_uc' in header (reported by jon blow) + 1.20 added support for Softimage PIC, by Tom Seddon + 1.19 bug in interlaced PNG corruption check (found by ryg) + 1.18 (2008-08-02) + fix a threading bug (local mutable static) + 1.17 support interlaced PNG + 1.16 major bugfix - stbi__convert_format converted one too many pixels + 1.15 initialize some fields for thread safety + 1.14 fix threadsafe conversion bug + header-file-only version (#define STBI_HEADER_FILE_ONLY before including) + 1.13 threadsafe + 1.12 const qualifiers in the API + 1.11 Support installable IDCT, colorspace conversion routines + 1.10 Fixes for 64-bit (don't use "unsigned long") + optimized upsampling by Fabian "ryg" Giesen + 1.09 Fix format-conversion for PSD code (bad global variables!) + 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz + 1.07 attempt to fix C++ warning/errors again + 1.06 attempt to fix C++ warning/errors again + 1.05 fix TGA loading to return correct *comp and use good luminance calc + 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free + 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR + 1.02 support for (subset of) HDR files, float interface for preferred access to them + 1.01 fix bug: possible bug in handling right-side up bmps... not sure + fix bug: the stbi__bmp_load() and stbi__tga_load() functions didn't work at all + 1.00 interface to zlib that skips zlib header + 0.99 correct handling of alpha in palette + 0.98 TGA loader by lonesock; dynamically add loaders (untested) + 0.97 jpeg errors on too large a file; also catch another malloc failure + 0.96 fix detection of invalid v value - particleman@mollyrocket forum + 0.95 during header scan, seek to markers in case of padding + 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same + 0.93 handle jpegtran output; verbose errors + 0.92 read 4,8,16,24,32-bit BMP files of several formats + 0.91 output 24-bit Windows 3.0 BMP files + 0.90 fix a few more warnings; bump version number to approach 1.0 + 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd + 0.60 fix compiling as c++ + 0.59 fix warnings: merge Dave Moore's -Wall fixes + 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian + 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available + 0.56 fix bug: zlib uncompressed mode len vs. nlen + 0.55 fix bug: restart_interval not initialized to 0 + 0.54 allow NULL for 'int *comp' + 0.53 fix bug in png 3->4; speedup png decoding + 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments + 0.51 obey req_comp requests, 1-component jpegs return as 1-component, + on 'test' only check type, not whether we support this variant + 0.50 (2006-11-19) + first released version +*/ + + +/* +------------------------------------------------------------------------------ +This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------ +ALTERNATIVE A - MIT License +Copyright (c) 2017 Sean Barrett +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +------------------------------------------------------------------------------ +ALTERNATIVE B - Public Domain (www.unlicense.org) +This is free and unencumbered software released into the public domain. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------------------ +*/ diff --git a/doc/extern/2013SiggraphPresentationsNotes-26915738.pdf b/doc/extern/2013SiggraphPresentationsNotes-26915738.pdf new file mode 100644 index 0000000..989658e Binary files /dev/null and b/doc/extern/2013SiggraphPresentationsNotes-26915738.pdf differ diff --git a/doc/extern/Scene Graph - CSE 167.pdf b/doc/extern/Scene Graph - CSE 167.pdf new file mode 100644 index 0000000..5fbbb10 Binary files /dev/null and b/doc/extern/Scene Graph - CSE 167.pdf differ diff --git a/doc/gfx.png b/doc/gfx.png new file mode 100644 index 0000000..e64f6e1 Binary files /dev/null and b/doc/gfx.png differ diff --git a/doc/gfx.txt b/doc/gfx.txt new file mode 100644 index 0000000..d3ce01b --- /dev/null +++ b/doc/gfx.txt @@ -0,0 +1,10 @@ +@startuml + +class Gfx { + +} + +Gfx --> Render +Gfx *-- Scene + +@enduml diff --git a/doc/gltfOverview-2.0.0b.png b/doc/gltfOverview-2.0.0b.png new file mode 100644 index 0000000..6a5bb61 Binary files /dev/null and b/doc/gltfOverview-2.0.0b.png differ diff --git a/doc/pipeline.png b/doc/pipeline.png new file mode 100644 index 0000000..426f39e Binary files /dev/null and b/doc/pipeline.png differ diff --git a/doc/pipeline.txt b/doc/pipeline.txt new file mode 100644 index 0000000..51523d6 --- /dev/null +++ b/doc/pipeline.txt @@ -0,0 +1,16 @@ +@startuml + +class RenderPipeline { + +} + +RenderPipeline *-- RenderPass + +class RenderPass { + +clear colour +} + +RenderPass --> Shader +RenderPass o-- RenderTarget + +@enduml diff --git a/doc/renderer.png b/doc/renderer.png new file mode 100644 index 0000000..d0516b0 Binary files /dev/null and b/doc/renderer.png differ diff --git a/doc/renderer.txt b/doc/renderer.txt new file mode 100644 index 0000000..90b18f8 --- /dev/null +++ b/doc/renderer.txt @@ -0,0 +1,18 @@ +@startuml + +class Render { + +} + +Render *-- RenderPipeline +Render --> Assets + +class Assets { + +} + +Assets *-- Shader +Assets *-- Geometry +Assets *-- Texture + +@enduml diff --git a/doc/scene.png b/doc/scene.png new file mode 100644 index 0000000..85d2447 Binary files /dev/null and b/doc/scene.png differ diff --git a/doc/scene.txt b/doc/scene.txt new file mode 100644 index 0000000..a771488 --- /dev/null +++ b/doc/scene.txt @@ -0,0 +1,109 @@ +@startuml + +class Scene { + +} + +Scene *-- Node + +class Camera { + +} + +class Node { + + transform +} + +Node *-- AnimationObject +Node *-- Object +Node *-- Light +Node *-- Camera +Node *-- Node + +class AnimationObject { + +} + +AnimationObject *-- Animation +AnimationObject --> AnimationState +AnimationObject --> Skeleton + +class AnimationState { + + time + + current_animation + + pose +} + +class Animation { + + name +} + +Animation *-- Keyframe + +class Keyframe { + + time + + transforms +} + +class Skeleton { + + joints +} + +class Object { + + transform +} + +Object *-- Mesh + +class Mesh { + +} + +Mesh --> BoundingVolume +Mesh --> Geometry +Mesh --> Material +Mesh --> Shader + +class Geometry { + + positions + + normals + + texcoords + + indices +} + +class BoundingVolume { + +} + +class Material { + + shader params +} + +Material o-- Texture + +class Shader { + + uniforms +} + +Shader --> VertexShader +Shader --> FragmentShader + +class VertexShader { + + pos + + normal + + texcoords + + Modelview + + Projection +} + +class FragmentShader { + + lights + + textures +} + +class Texture { + + pixels + + format +} + +@enduml diff --git a/game/CMakeLists.txt b/game/CMakeLists.txt deleted file mode 100644 index 3a88bb7..0000000 --- a/game/CMakeLists.txt +++ /dev/null @@ -1,22 +0,0 @@ -cmake_minimum_required(VERSION 3.0) - -add_subdirectory(src/plugins) - -project(game) - -add_executable(game - src/game.c) - -target_include_directories(game PRIVATE - src/) - -target_link_libraries(game PRIVATE - cstring - error - gfx - gfx-app - list - log - math - mempool - plugin) diff --git a/game/src/game.c b/game/src/game.c deleted file mode 100644 index 51f5cbe..0000000 --- a/game/src/game.c +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Main game module with entry point and game loop. - * - * The game module sets up the window and GL context and defers the core game - * logic to a plugin. - */ -#define _GNU_SOURCE 200112L // For readlink() - -#include "game.h" - -#include "plugins/plugin.h" - -#include -#include -#include -#include - -#include -#include -#include - -#include -#include -#include -#include - -#include - -#include - -#undef _GNU_SOURCE - -static const int WIDTH = 1350; -static const int HEIGHT = 900; -static const int MAX_FPS = 60; - -typedef struct GfxAppState { - Game game; -} GfxAppState; - -/// Initialize the game's plugin. -static bool init_plugin(Game* game) { - assert(game); - assert(game->plugin); - // Plugin state is allowed to be null, either when the plugin does not - // expose an init() or when init() does not initialize a state. - if (plugin_resolve(game->plugin, plugin_init, "init")) { - State* plugin_state = 0; - if (!plugin_call(game->plugin, plugin_init, "init", game, &plugin_state)) { - return false; - } - set_plugin_state(game->plugin, plugin_state); - } - return true; // Plugin does not need to expose an init(). -} - -/// Shutdown the game's plugin. -/// The game's plugin is allowed to be null in the call to this function. -static void shutdown_plugin(Game* game) { - assert(game); - if (game->plugin && - (plugin_resolve(game->plugin, plugin_shutdown, "shutdown"))) { - void* plugin_state = get_plugin_state(game->plugin); - plugin_call(game->plugin, plugin_shutdown, "shutdown", game, plugin_state); - set_plugin_state(game->plugin, 0); - } -} - -/// Boot the game's plugin. -static bool boot_plugin(Game* game) { - assert(game); - assert(game->plugin); - if (plugin_resolve(game->plugin, plugin_boot, "boot")) { - void* plugin_state = get_plugin_state(game->plugin); - return plugin_call(game->plugin, plugin_boot, "boot", game, plugin_state); - } - return true; // Plugin does not need to expose a boot(). -} - -/// Update the plugin's state. -static void update_plugin(Game* game, double t, double dt) { - assert(game); - assert(game->plugin); - if (plugin_resolve(game->plugin, plugin_update, "update")) { - void* plugin_state = get_plugin_state(game->plugin); - plugin_call( - game->plugin, plugin_update, "update", game, plugin_state, t, dt); - } -} - -/// Plugin render. -static void render_plugin(const Game* game) { - assert(game); - assert(game->plugin); - if (plugin_resolve(game->plugin, plugin_render, "render")) { - void* plugin_state = get_plugin_state(game->plugin); - plugin_call(game->plugin, plugin_render, "render", game, plugin_state); - } -} - -/// Plugin resize. -static void resize_plugin(Game* game, int width, int height) { - assert(game); - assert(game->plugin); - if (plugin_resolve(game->plugin, plugin_resize, "resize")) { - void* plugin_state = get_plugin_state(game->plugin); - plugin_call( - game->plugin, plugin_resize, "resize", game, plugin_state, width, - height); - } -} - -static void Shutdown(Game* game); - -static bool Init(Game* game, int argc, const char** argv) { - assert(game); - - if (argc <= 1) { - LOGE("Usage: %s [plugin args]", argv[0]); - return false; - } - - // Syntax: game [plugin args] - // - // Here we consume the arg so that plugins receive the remainder - // args starting from 0. - game->argc = argc - 1; - game->argv = argv + 1; - - char exe_path_buf[NAME_MAX] = {0}; - if (readlink("/proc/self/exe", exe_path_buf, sizeof(exe_path_buf)) == -1) { - LOGE("readlink(/proc/self/exe) failed"); - goto cleanup; - } - - // Replace the last / with a null terminator to remove the exe file from the - // path. This gets the file's parent directory. - *strrchr(exe_path_buf, '/') = 0; - - const mstring exe_dir = mstring_make(exe_path_buf); - const mstring plugins_path = mstring_concat_cstr(exe_dir, "/src/plugins"); - - if (!(game->plugin_engine = new_plugin_engine( - &(PluginEngineDesc){.plugins_dir = mstring_cstr(&plugins_path)}))) { - goto cleanup; - } - - const char* plugin = argv[1]; - if (!(game->plugin = load_plugin(game->plugin_engine, plugin))) { - goto cleanup; - } - - if (!(game->gfx = gfx_init())) { - goto cleanup; - } - - if (!init_plugin(game)) { - goto cleanup; - } - if (!boot_plugin(game)) { - goto cleanup; - } - - return true; - -cleanup: - LOGE("Gfx error: %s", get_error()); - Shutdown(game); - return false; -} - -static void Shutdown(Game* game) { - assert(game); - shutdown_plugin(game); - if (game->gfx) { - gfx_destroy(&game->gfx); - } - if (game->plugin) { - delete_plugin(&game->plugin); - } - if (game->plugin_engine) { - delete_plugin_engine(&game->plugin_engine); - } -} - -static void Update(Game* game, double t, double dt) { - plugin_engine_update(game->plugin_engine); - if (plugin_reloaded(game->plugin)) { - shutdown_plugin(game); - const bool result = init_plugin(game); - assert(result); // TODO: handle error better. - - // Trigger a resize just like the initial resize that occurs when the gfx - // application starts. - resize_plugin(game, game->width, game->height); - } - - update_plugin(game, t, dt); -} - -static void Render(const Game* game) { - GfxCore* gfxcore = gfx_get_core(game->gfx); - gfx_start_frame(gfxcore); - render_plugin(game); - gfx_end_frame(gfxcore); -} - -static void Resize(Game* game, int width, int height) { - game->width = width; - game->height = height; - - GfxCore* gfxcore = gfx_get_core(game->gfx); - gfx_set_viewport(gfxcore, 0, 0, width, height); - - resize_plugin(game, width, height); -} - -GFX_APP_MAIN(WIDTH, HEIGHT, MAX_FPS, "Game"); diff --git a/game/src/game.h b/game/src/game.h deleted file mode 100644 index 579ba3c..0000000 --- a/game/src/game.h +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Header file defining the game state, included by plugins. - */ -#pragma once - -typedef struct PluginEngine PluginEngine; -typedef struct Plugin Plugin; -typedef struct Gfx Gfx; -typedef struct Scene Scene; -typedef struct SceneCamera SceneCamera; - -/// Game state. -typedef struct { - int argc; - const char** argv; - PluginEngine* plugin_engine; - Plugin* plugin; - Gfx* gfx; - int width; - int height; -} Game; diff --git a/game/src/plugins/CMakeLists.txt b/game/src/plugins/CMakeLists.txt deleted file mode 100644 index 8661598..0000000 --- a/game/src/plugins/CMakeLists.txt +++ /dev/null @@ -1,29 +0,0 @@ -cmake_minimum_required(VERSION 3.0) - -project(plugins) - -set(LINK_LIBRARIES cstring math gfx gfx-app) - -# Viewer - -add_library(viewer SHARED - viewer.c) - -target_link_libraries(viewer PUBLIC - ${LINK_LIBRARIES}) - -# Texture viewer - -add_library(texture_view SHARED - texture_view.c) - -target_link_libraries(texture_view PUBLIC - ${LINK_LIBRARIES}) - -# Pong - -add_library(pong SHARED - pong.c) - -target_link_libraries(pong PUBLIC - ${LINK_LIBRARIES}) diff --git a/game/src/plugins/plugin.h b/game/src/plugins/plugin.h deleted file mode 100644 index f7219c6..0000000 --- a/game/src/plugins/plugin.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Game plugin. - */ -#pragma once - -#include "../game.h" - -#include -#include - -#include - -typedef struct State State; - -/// Initialize the plugin, which may optionally return a state object. -/// -/// This function is called every time the plugin is (re)loaded. -/// -/// It is assumed that the plugin's state is fully encapsulated in the returned -/// state object. The plugin should not store any (mutable) state outside of the -/// returned state object (e.g., no mutable global variables.) -bool init(Game*, State**); - -/// Shut down the plugin. -/// -/// This function is called before the plugin is unloaded. -/// -/// The plugin should perform any destruction needed, but not free the state -/// object; freeing the state object's memory is handled by the caller. -void shutdown(Game*, State*); - -/// Function called the first time the plugin is loaded throughout the -/// application's lifetime. This allows the plugin to do one-time initialization -/// of the game state. -bool boot(Game*, State*); - -/// Update the plugin's and the game's state. -void update(Game*, State*, double t, double dt); - -/// Render hook. -void render(const Game*, const State*); - -/// Called when the game's window is resized. -void resize(Game*, State*, int width, int height); - -// Signatures for the plugin's exposed functions. -typedef bool (*plugin_init)(Game*, State**); -typedef bool (*plugin_shutdown)(Game*, State*); -typedef bool (*plugin_boot)(Game*, State*); -typedef void (*plugin_update)(Game*, State*, double t, double dt); -typedef void (*plugin_render)(const Game*, const State*); -typedef void (*plugin_resize)(Game* game, State* state, int width, int height); diff --git a/game/src/plugins/pong.c b/game/src/plugins/pong.c deleted file mode 100644 index c1c55be..0000000 --- a/game/src/plugins/pong.c +++ /dev/null @@ -1,237 +0,0 @@ -#include "plugin.h" - -#include -#include -#include - -#include -#include -#include - -#include - -static const vec2 PAD_SIZE = (vec2){120, 20}; -static const R PLAYER_Y_OFFSET = 50; -static const R PLAYER_SPEED = 800; - -static const R ENEMY_SPEED = 2; - -static const R BALL_SIZE = 18; -static const R BALL_SPEED = 360; // In each dimension. - -static const R EPS = (R)1e-3; - -typedef struct Player { - vec2 position; -} Player; - -typedef struct Ball { - vec2 position; - vec2 velocity; -} Ball; - -typedef struct State { - bool game_started; - Player human; - Player enemy; - Ball ball; - mat4 viewProjection; -} State; - -bool init(Game* game, State** pp_state) { - assert(game); - - State* state = calloc(1, sizeof(State)); - if (!state) { - return false; - } - - *pp_state = state; - return true; - -cleanup: - free(state); - return false; -} - -void shutdown(Game* game, State* state) { - assert(game); - assert(state); -} - -static void move_ball(Ball* ball, R dt, int width, int height) { - assert(ball); - - const R offset = BALL_SIZE / 2; - - ball->position = vec2_add(ball->position, vec2_scale(ball->velocity, dt)); - - // Right wall. - if (ball->position.x + offset > (R)width) { - ball->position.x = (R)width - offset - EPS; - ball->velocity.x = -ball->velocity.x; - } - // Left wall. - else if (ball->position.x - offset < 0) { - ball->position.x = offset + EPS; - ball->velocity.x = -ball->velocity.x; - } - // Top wall. - if (ball->position.y + offset > (R)height) { - ball->position.y = (R)height - offset - EPS; - ball->velocity.y = -ball->velocity.y; - } - // Bottom wall. - else if (ball->position.y - offset < 0) { - ball->position.y = offset + EPS; - ball->velocity.y = -ball->velocity.y; - } -} - -void move_enemy_player(int width, Player* player, R t) { - const R half_width = (R)width / 2; - const R amplitude = half_width - (PAD_SIZE.x / 2); - player->position.x = half_width + amplitude * sinf(t * ENEMY_SPEED); -} - -void move_human_player(Player* player, R dt) { - assert(player); - - R speed = 0; - if (gfx_app_is_key_pressed('a')) { - speed -= PLAYER_SPEED; - } - if (gfx_app_is_key_pressed('d')) { - speed += PLAYER_SPEED; - } - - player->position.x += speed * dt; -} - -void clamp_player(Player* player, int width) { - assert(player); - - const R offset = PAD_SIZE.x / 2; - - // Left wall. - if (player->position.x + offset > (R)width) { - player->position.x = (R)width - offset; - } - // Right wall. - else if (player->position.x - offset < 0) { - player->position.x = offset; - } -} - -void collide_ball(vec2 old_ball_position, const Player* player, Ball* ball) { - assert(player); - assert(ball); - - // Discrete but simple collision. Checks for intersection and moves the ball - // back by a small epsilon. - - // Player bounding box. - const vec2 player_pmin = vec2_make( - player->position.x - PAD_SIZE.x / 2, player->position.y - PAD_SIZE.y / 2); - const vec2 player_pmax = vec2_make( - player->position.x + PAD_SIZE.x / 2, player->position.y + PAD_SIZE.y / 2); - - // Ball bounding box. - const vec2 ball_pmin = vec2_make( - ball->position.x - BALL_SIZE / 2, ball->position.y - BALL_SIZE / 2); - const vec2 ball_pmax = vec2_make( - ball->position.x + BALL_SIZE / 2, ball->position.y + BALL_SIZE / 2); - - // Check for intersection and update ball. - if (!((ball_pmax.x < player_pmin.x) || (ball_pmin.x > player_pmax.x) || - (ball_pmax.y < player_pmin.y) || (ball_pmin.y > player_pmax.y))) { - ball->position = - vec2_add(old_ball_position, vec2_scale(ball->velocity, -EPS)); - ball->velocity.y = -ball->velocity.y; - } -} - -void update(Game* game, State* state, double t, double dt) { - assert(game); - assert(state); - - // TODO: Move game width/height to GfxApp query functions? - const vec2 old_ball_position = state->ball.position; - move_ball(&state->ball, (R)dt, game->width, game->height); - move_human_player(&state->human, (R)dt); - move_enemy_player(game->width, &state->enemy, (R)t); - clamp_player(&state->human, game->width); - collide_ball(old_ball_position, &state->human, &state->ball); - collide_ball(old_ball_position, &state->enemy, &state->ball); -} - -static void draw_player(ImmRenderer* imm, const Player* player) { - assert(imm); - assert(player); - - const vec2 half_box = vec2_div(PAD_SIZE, vec2_make(2, 2)); - - const vec2 pmin = vec2_sub(player->position, half_box); - const vec2 pmax = vec2_add(player->position, half_box); - const aabb2 box = aabb2_make(pmin, pmax); - - gfx_imm_draw_aabb2(imm, box); -} - -static void draw_ball(ImmRenderer* imm, const Ball* ball) { - assert(imm); - assert(ball); - - const vec2 half_box = vec2_make(BALL_SIZE / 2, BALL_SIZE / 2); - const vec2 pmin = vec2_sub(ball->position, half_box); - const vec2 pmax = vec2_add(ball->position, half_box); - const aabb2 box = aabb2_make(pmin, pmax); - - gfx_imm_draw_aabb2(imm, box); -} - -void render(const Game* game, const State* state) { - assert(game); - assert(state); - - ImmRenderer* imm = gfx_get_imm_renderer(game->gfx); - gfx_imm_start(imm); - gfx_imm_set_view_projection_matrix(imm, &state->viewProjection); - gfx_imm_load_identity(imm); - gfx_imm_set_colour(imm, vec4_make(1, 1, 1, 1)); - draw_player(imm, &state->human); - draw_player(imm, &state->enemy); - draw_ball(imm, &state->ball); - gfx_imm_end(imm); -} - -static R clamp_to_width(int width, R x, R extent) { - return min(x, (R)width - extent); -} - -void resize(Game* game, State* state, int width, int height) { - assert(game); - assert(state); - - state->viewProjection = mat4_ortho(0, (R)width, 0, (R)height, -1, 1); - - state->human.position.y = PLAYER_Y_OFFSET; - state->enemy.position.y = (R)height - PLAYER_Y_OFFSET; - - if (!state->game_started) { - state->human.position.x = (R)width / 2; - state->enemy.position.x = (R)width / 2; - - state->ball.position = - vec2_div(vec2_make((R)width, (R)height), vec2_make(2, 2)); - - state->ball.velocity = vec2_make(BALL_SPEED, BALL_SPEED); - - state->game_started = true; - } else { - state->human.position.x = - clamp_to_width(width, state->human.position.x, PAD_SIZE.x / 2); - state->enemy.position.x = - clamp_to_width(width, state->enemy.position.x, PAD_SIZE.x / 2); - } -} diff --git a/game/src/plugins/texture_view.c b/game/src/plugins/texture_view.c deleted file mode 100644 index a8b2a94..0000000 --- a/game/src/plugins/texture_view.c +++ /dev/null @@ -1,144 +0,0 @@ -#include "plugin.h" - -#include -#include -#include -#include -#include -#include - -#include - -#include -#include - -// Default texture to load if no texture is provided. -static const char* DEFAULT_TEXTURE = "/assets/skybox/clouds1/clouds1_west.bmp"; -// static const char* DEFAULT_TEXTURE = "/assets/checkerboard.jpg"; - -struct State { - Scene* scene; - SceneCamera* camera; -}; - -bool init(Game* game, State** pp_state) { - assert(game); - assert(pp_state); - - State* state = calloc(1, sizeof(State)); - if (!state) { - goto cleanup; - } - - // Usage: [texture file] - const char* texture_file = game->argc > 1 ? game->argv[1] : DEFAULT_TEXTURE; - - GfxCore* gfxcore = gfx_get_core(game->gfx); - - const Texture* texture = gfx_load_texture( - game->gfx, &(LoadTextureCmd){ - .origin = AssetFromFile, - .type = LoadTexture, - .filtering = LinearFiltering, - .mipmaps = false, - .data.texture.filepath = mstring_make(texture_file)}); - if (!texture) { - goto cleanup; - } - - ShaderProgram* shader = gfx_make_view_texture_shader(gfxcore); - if (!shader) { - goto cleanup; - } - - Geometry* geometry = gfx_make_quad_11(gfxcore); - if (!geometry) { - goto cleanup; - } - - MaterialDesc material_desc = (MaterialDesc){.num_uniforms = 1}; - material_desc.uniforms[0] = (ShaderUniform){ - .type = UniformTexture, - .value.texture = texture, - .name = sstring_make("Texture")}; - Material* material = gfx_make_material(&material_desc); - if (!material) { - goto cleanup; - } - - const MeshDesc mesh_desc = - (MeshDesc){.geometry = geometry, .material = material, .shader = shader}; - Mesh* mesh = gfx_make_mesh(&mesh_desc); - if (!mesh) { - goto cleanup; - } - - SceneObject* object = - gfx_make_object(&(ObjectDesc){.num_meshes = 1, .meshes = {mesh}}); - if (!object) { - goto cleanup; - } - - if (!(state->scene = gfx_make_scene())) { - goto cleanup; - } - - SceneNode* node = gfx_make_object_node(object); - if (!node) { - goto cleanup; - } - SceneNode* root = gfx_get_scene_root(state->scene); - if (!root) { - goto cleanup; - } - gfx_set_node_parent(node, root); - - if (!(state->camera = gfx_make_camera())) { - goto cleanup; - } - - *pp_state = state; - return true; - -cleanup: - shutdown(game, state); - if (state) { - free(state); - } - return false; -} - -void shutdown(Game* game, State* state) { - assert(game); - if (state) { - gfx_destroy_camera(&state->camera); - gfx_destroy_scene(&state->scene); - // State freed by plugin engine. - } -} - -void render(const Game* game, const State* state) { - assert(game); - assert(state); - - Renderer* renderer = gfx_get_renderer(game->gfx); - gfx_render_scene( - renderer, &(RenderSceneParams){ - .mode = RenderDefault, - .scene = state->scene, - .camera = state->camera}); -} - -void resize(Game* game, State* state, int width, int height) { - assert(game); - assert(state); - - const R fovy = 90 * TO_RAD; - const R aspect = (R)width / (R)height; - const R near = 0.1; - const R far = 1000; - const mat4 projection = mat4_perspective(fovy, aspect, near, far); - - Camera* camera = gfx_get_camera_camera(state->camera); - camera->projection = projection; -} diff --git a/game/src/plugins/viewer.c b/game/src/plugins/viewer.c deleted file mode 100644 index 23b9ffb..0000000 --- a/game/src/plugins/viewer.c +++ /dev/null @@ -1,374 +0,0 @@ -#include "plugin.h" - -#include -#include -#include -#include -#include -#include -#include - -#include - -#include - -// Skybox. -static const char* skybox[6] = { - "/home/jeanne/Nextcloud/assets/textures/skybox/clouds1/clouds1_east.bmp", - "/home/jeanne/Nextcloud/assets/textures/skybox/clouds1/clouds1_west.bmp", - "/home/jeanne/Nextcloud/assets/textures/skybox/clouds1/clouds1_up.bmp", - "/home/jeanne/Nextcloud/assets/textures/skybox/clouds1/clouds1_down.bmp", - "/home/jeanne/Nextcloud/assets/textures/skybox/clouds1/clouds1_south.bmp", - "/home/jeanne/Nextcloud/assets/textures/skybox/clouds1/clouds1_north.bmp", -}; - -// Paths to various scene files. -static const char* BOX = "/home/jeanne/Nextcloud/assets/models/box.gltf"; -static const char* SUZANNE = - "/home/jeanne/Nextcloud/assets/models/suzanne.gltf"; -static const char* SPONZA = "/home/jeanne/Nextcloud/assets/glTF-Sample-Models/" - "2.0/Sponza/glTF/Sponza.gltf"; -static const char* FLIGHT_HELMET = - "/home/jeanne/Nextcloud/assets/glTF-Sample-Models/2.0/FlightHelmet/glTF/" - "FlightHelmet.gltf"; -static const char* DAMAGED_HELMET = - "/home/jeanne/Nextcloud/assets/glTF-Sample-Models/2.0/DamagedHelmet/glTF/" - "DamagedHelmet.gltf"; -static const char* GIRL = - "/home/jeanne/Nextcloud/assets/models/girl/girl-with-ground.gltf"; -static const char* BOXES = - "/home/jeanne/Nextcloud/assets/models/boxes/boxes.gltf"; - -#define DEFAULT_SCENE_FILE GIRL - -static const bool RenderBoundingBoxes = false; -static const R DefaultCameraSpeed = (R)6.0; -static const R DefaultMouseSensitivity = (R)(10 * TO_RAD); -static const vec3 DefaultCameraPosition = (vec3){0, 2, 5}; - -typedef struct CameraCommand { - bool CameraMoveLeft : 1; - bool CameraMoveRight : 1; - bool CameraMoveForward : 1; - bool CameraMoveBackward : 1; -} CameraCommand; - -typedef struct CameraController { - R camera_speed; // Camera movement speed. - R mouse_sensitivity; // Controls the degree with which mouse movements - // rotate the camera. - vec2 prev_mouse_position; // Mouse position in the previous frame. - bool rotating; // When true, subsequent mouse movements cause the - // camera to rotate. -} CameraController; - -typedef struct State { - Scene* scene; - Model* model; - SceneCamera* camera; - CameraController camera_controller; -} State; - -/// Load the skyquad texture. -static const Texture* load_environment_map(Gfx* gfx) { - assert(gfx); - return gfx_load_texture( - gfx, &(LoadTextureCmd){ - .origin = AssetFromFile, - .type = LoadCubemap, - .colour_space = sRGB, - .filtering = NearestFiltering, - .mipmaps = false, - .data.cubemap.filepaths = { - mstring_make(skybox[0]), mstring_make(skybox[1]), - mstring_make(skybox[2]), mstring_make(skybox[3]), - mstring_make(skybox[4]), mstring_make(skybox[5])} - }); -} - -/// Load the skyquad and return the environment light node. -static SceneNode* load_skyquad(Gfx* gfx, SceneNode* root) { - assert(gfx); - assert(root); - - GfxCore* gfxcore = gfx_get_core(gfx); - - const Texture* environment_map = load_environment_map(gfx); - if (!environment_map) { - return 0; - } - - return gfx_setup_skyquad(gfxcore, root, environment_map); -} - -/// Load the 3D scene. -/// Return the loaded model. -static Model* load_scene(Game* game, State* state, const char* scene_filepath) { - assert(game); - assert(game->gfx); - assert(state); - assert(state->scene); - - Camera* camera = gfx_get_camera_camera(state->camera); - spatial3_set_position(&camera->spatial, vec3_make(0, 0, 2)); - - SceneNode* root = gfx_get_scene_root(state->scene); - SceneNode* sky_light_node = load_skyquad(game->gfx, root); - if (!sky_light_node) { - return 0; // test - } - - Model* model = gfx_load_model( - game->gfx, &(LoadModelCmd){.origin = AssetFromFile, - .filepath = mstring_make(scene_filepath)}); - if (!model) { - return 0; - } - SceneNode* model_node = gfx_make_model_node(model); - if (!model_node) { - return 0; - } - gfx_set_node_parent(model_node, sky_light_node); - - gfx_log_node_hierarchy(root); - - return model; -} - -bool init(Game* game, State** pp_state) { - assert(game); - - // Usage: - const char* scene_filepath = - game->argc > 1 ? game->argv[1] : DEFAULT_SCENE_FILE; - - State* state = calloc(1, sizeof(State)); - if (!state) { - goto cleanup; - } - - if (!(state->scene = gfx_make_scene())) { - goto cleanup; - } - if (!(state->camera = gfx_make_camera())) { - goto cleanup; - } - - state->model = load_scene(game, state, scene_filepath); - if (!state->model) { - goto cleanup; - } - - Anima* anima = gfx_get_model_anima(state->model); - if (anima) { - gfx_play_animation( - anima, &(AnimationPlaySettings){.name = "Walk", .loop = true}); - // TODO: Interpolate animations. - /*gfx_play_animation( - anima, - &(AnimationPlaySettings){.name = "Jumping-jack-lower", .loop = true}); - gfx_play_animation( - anima, &(AnimationPlaySettings){ - .name = "Jumping-jack-arms-mid", .loop = true});*/ - } - - spatial3_set_position( - &gfx_get_camera_camera(state->camera)->spatial, DefaultCameraPosition); - - state->camera_controller.camera_speed = DefaultCameraSpeed; - state->camera_controller.mouse_sensitivity = DefaultMouseSensitivity; - - *pp_state = state; - return true; - -cleanup: - shutdown(game, state); - if (state) { - free(state); - } - return false; -} - -void shutdown(Game* game, State* state) { - assert(game); - if (state) { - gfx_destroy_camera(&state->camera); - gfx_destroy_scene(&state->scene); - // State freed by plugin engine. - } -} - -static void update_camera( - CameraController* controller, R dt, vec2 mouse_position, - CameraCommand command, Spatial3* camera) { - assert(controller); - assert(camera); - - // Translation. - const R move_x = (R)(command.CameraMoveLeft ? -1 : 0) + - (R)(command.CameraMoveRight ? 1 : 0); - const R move_y = (R)(command.CameraMoveForward ? 1 : 0) + - (R)(command.CameraMoveBackward ? -1 : 0); - const vec2 translation = - vec2_scale(vec2_make(move_x, move_y), controller->camera_speed * dt); - spatial3_move_right(camera, translation.x); - spatial3_move_forwards(camera, translation.y); - - // Rotation. - if (controller->rotating) { - const vec2 mouse_delta = - vec2_sub(mouse_position, controller->prev_mouse_position); - - const vec2 rotation = - vec2_scale(mouse_delta, controller->mouse_sensitivity * dt); - - spatial3_global_yaw(camera, -rotation.x); - spatial3_pitch(camera, -rotation.y); - } - - // Update controller state. - controller->prev_mouse_position = mouse_position; -} - -void update(Game* game, State* state, double t, double dt) { - assert(game); - assert(state); - assert(state->scene); - assert(state->camera); - - double mouse_x, mouse_y; - gfx_app_get_mouse_position(&mouse_x, &mouse_y); - const vec2 mouse_position = {(R)mouse_x, (R)mouse_y}; - - const CameraCommand camera_command = (CameraCommand){ - .CameraMoveLeft = gfx_app_is_key_pressed(KeyA), - .CameraMoveRight = gfx_app_is_key_pressed(KeyD), - .CameraMoveForward = gfx_app_is_key_pressed(KeyW), - .CameraMoveBackward = gfx_app_is_key_pressed(KeyS), - }; - - state->camera_controller.rotating = gfx_app_is_mouse_button_pressed(LMB); - - update_camera( - &state->camera_controller, (R)dt, mouse_position, camera_command, - &gfx_get_camera_camera(state->camera)->spatial); - - // const vec3 orbit_point = vec3_make(0, 2, 0); - // Camera* camera = gfx_get_camera_camera(state->camera); - // spatial3_orbit( - // &camera->spatial, orbit_point, - // /*radius=*/5, - // /*azimuth=*/(R)(t * 0.5), /*zenith=*/0); - // spatial3_lookat(&camera->spatial, orbit_point); - - gfx_update(state->scene, state->camera, (R)t); -} - -/// Render the bounding boxes of all scene objects. -static void render_bounding_boxes_rec( - ImmRenderer* imm, const Anima* anima, const mat4* parent_model_matrix, - const SceneNode* node) { - assert(imm); - assert(node); - - const mat4 model_matrix = - mat4_mul(*parent_model_matrix, gfx_get_node_transform(node)); - - const NodeType node_type = gfx_get_node_type(node); - - if (node_type == ModelNode) { - const Model* model = gfx_get_node_model(node); - const SceneNode* root = gfx_get_model_root(model); - render_bounding_boxes_rec(imm, anima, &model_matrix, root); - } else if (node_type == AnimaNode) { - anima = gfx_get_node_anima(node); - } else if (node_type == ObjectNode) { - gfx_imm_set_model_matrix(imm, &model_matrix); - - const SceneObject* obj = gfx_get_node_object(node); - const Skeleton* skeleton = gfx_get_object_skeleton(obj); - - if (skeleton) { // Animated model. - assert(anima); - const size_t num_joints = gfx_get_skeleton_num_joints(skeleton); - for (size_t i = 0; i < num_joints; ++i) { - if (gfx_joint_has_box(anima, skeleton, i)) { - const Box box = gfx_get_joint_box(anima, skeleton, i); - gfx_imm_draw_box3(imm, box.vertices); - } - } - } else { // Static model. - const aabb3 box = gfx_get_object_aabb(obj); - gfx_imm_draw_aabb3(imm, box); - } - } - - // Render children's boxes. - const SceneNode* child = gfx_get_node_child(node); - while (child) { - render_bounding_boxes_rec(imm, anima, &model_matrix, child); - child = gfx_get_node_sibling(child); - } -} - -/// Render the bounding boxes of all scene objects. -static void render_bounding_boxes(const Game* game, const State* state) { - assert(game); - assert(state); - - GfxCore* gfxcore = gfx_get_core(game->gfx); - ImmRenderer* imm = gfx_get_imm_renderer(game->gfx); - assert(gfxcore); - assert(imm); - - const mat4 id = mat4_id(); - Anima* anima = 0; - - gfx_set_blending(gfxcore, true); - gfx_set_depth_mask(gfxcore, false); - gfx_set_polygon_offset(gfxcore, -1.5f, -1.0f); - - gfx_imm_start(imm); - gfx_imm_set_camera(imm, gfx_get_camera_camera(state->camera)); - gfx_imm_set_colour(imm, vec4_make(0.3, 0.3, 0.9, 0.1)); - render_bounding_boxes_rec(imm, anima, &id, gfx_get_scene_root(state->scene)); - gfx_imm_end(imm); - - gfx_reset_polygon_offset(gfxcore); - gfx_set_depth_mask(gfxcore, true); - gfx_set_blending(gfxcore, false); -} - -void render(const Game* game, const State* state) { - assert(state); - assert(game); - assert(game->gfx); - assert(state->scene); - assert(state->camera); - - Renderer* renderer = gfx_get_renderer(game->gfx); - assert(renderer); - - gfx_render_scene( - renderer, &(RenderSceneParams){.mode = RenderDefault, - .scene = state->scene, - .camera = state->camera}); - - if (RenderBoundingBoxes) { - render_bounding_boxes(game, state); - } -} - -void resize(Game* game, State* state, int width, int height) { - assert(game); - assert(state); - - const R fovy = 60 * TO_RAD; - const R aspect = (R)width / (R)height; - const R near = 0.1; - const R far = 1000; - const mat4 projection = mat4_perspective(fovy, aspect, near, far); - - Camera* camera = gfx_get_camera_camera(state->camera); - camera->projection = projection; -} diff --git a/gfx-iso/CMakeLists.txt b/gfx-iso/CMakeLists.txt deleted file mode 100644 index e4a677d..0000000 --- a/gfx-iso/CMakeLists.txt +++ /dev/null @@ -1,42 +0,0 @@ -cmake_minimum_required(VERSION 3.0) - -project(isogfx) - -set(CMAKE_C_STANDARD 17) -set(CMAKE_C_STANDARD_REQUIRED On) -set(CMAKE_C_EXTENSIONS Off) - -# isogfx - -add_library(isogfx - src/isogfx.c) - -target_include_directories(isogfx PUBLIC - include) - -target_link_libraries(isogfx PUBLIC - filesystem - mem - mempool) - -target_compile_options(isogfx PRIVATE -Wall -Wextra -Wpedantic) - -# Backend - -add_library(isogfx-backend - src/backend.c) - -target_include_directories(isogfx-backend PUBLIC - include) - -target_link_libraries(isogfx-backend PUBLIC - isogfx) - -target_link_libraries(isogfx-backend PRIVATE - gfx) - -target_compile_options(isogfx-backend PRIVATE -Wall -Wextra -Wpedantic) - -# Demos - -add_subdirectory(demos) diff --git a/gfx-iso/demos/CMakeLists.txt b/gfx-iso/demos/CMakeLists.txt deleted file mode 100644 index c0a4101..0000000 --- a/gfx-iso/demos/CMakeLists.txt +++ /dev/null @@ -1,2 +0,0 @@ -add_subdirectory(checkerboard) -add_subdirectory(isomap) diff --git a/gfx-iso/demos/checkerboard/CMakeLists.txt b/gfx-iso/demos/checkerboard/CMakeLists.txt deleted file mode 100644 index d1691c6..0000000 --- a/gfx-iso/demos/checkerboard/CMakeLists.txt +++ /dev/null @@ -1,16 +0,0 @@ -cmake_minimum_required(VERSION 3.0) - -project(checkerboard) - -set(CMAKE_C_STANDARD 17) -set(CMAKE_C_STANDARD_REQUIRED On) -set(CMAKE_C_EXTENSIONS Off) - -add_executable(checkerboard - checkerboard.c) - -target_link_libraries(checkerboard PRIVATE - gfx-app - isogfx-backend) - -target_compile_options(checkerboard PRIVATE -Wall -Wextra -Wpedantic) diff --git a/gfx-iso/demos/checkerboard/checkerboard.c b/gfx-iso/demos/checkerboard/checkerboard.c deleted file mode 100644 index dbc817c..0000000 --- a/gfx-iso/demos/checkerboard/checkerboard.c +++ /dev/null @@ -1,166 +0,0 @@ -#include -#include - -#include - -#include -#include -#include - -static const int WINDOW_WIDTH = 1408; -static const int WINDOW_HEIGHT = 960; -static const int MAX_FPS = 60; - -// Virtual screen dimensions. -static const int SCREEN_WIDTH = 704; -static const int SCREEN_HEIGHT = 480; - -static const int TILE_WIDTH = 32; -static const int TILE_HEIGHT = TILE_WIDTH / 2; -static const int WORLD_WIDTH = 20; -static const int WORLD_HEIGHT = 20; - -static const TileDesc tile_set[] = { - {.type = TileFromColour, - .width = TILE_WIDTH, - .height = TILE_HEIGHT, - .colour = (Pixel){.r = 0x38, .g = 0x3b, .b = 0x46, .a = 0xff}}, - {.type = TileFromColour, - .width = TILE_WIDTH, - .height = TILE_HEIGHT, - .colour = (Pixel){.r = 0xA5, .g = 0xb3, .b = 0xc0, .a = 0xff}}, - {.type = TileFromColour, - .width = TILE_WIDTH, - .height = TILE_HEIGHT, - .colour = (Pixel){.r = 0xdc, .g = 0x76, .b = 0x84, .a = 0xff}}, -}; - -typedef enum Colour { - Black, - White, - Red, -} Colour; - -typedef struct GfxAppState { - IsoBackend* backend; - IsoGfx* iso; - Tile red; - int xpick; - int ypick; -} GfxAppState; - -static void make_checkerboard(IsoGfx* iso, Tile black, Tile white) { - assert(iso); - for (int y = 0; y < isogfx_world_height(iso); ++y) { - for (int x = 0; x < isogfx_world_width(iso); ++x) { - const int odd_col = x & 1; - const int odd_row = y & 1; - const Tile value = (odd_row ^ odd_col) == 0 ? black : white; - isogfx_set_tile(iso, x, y, value); - } - } -} - -static bool init(GfxAppState* state, int argc, const char** argv) { - assert(state); - - (void)argc; - (void)argv; - - if (!(state->iso = isogfx_new(&(IsoGfxDesc){ - .screen_width = SCREEN_WIDTH, .screen_height = SCREEN_HEIGHT}))) { - return false; - } - IsoGfx* iso = state->iso; - - isogfx_resize(iso, SCREEN_WIDTH, SCREEN_HEIGHT); - - if (!isogfx_make_world( - iso, &(WorldDesc){ - .tile_width = TILE_WIDTH, - .tile_height = TILE_HEIGHT, - .world_width = WORLD_WIDTH, - .world_height = WORLD_HEIGHT})) { - return false; - } - - const Tile black = isogfx_make_tile(iso, &tile_set[Black]); - const Tile white = isogfx_make_tile(iso, &tile_set[White]); - state->red = isogfx_make_tile(iso, &tile_set[Red]); - make_checkerboard(iso, black, white); - - if (!(state->backend = IsoBackendInit(iso))) { - return false; - } - - return true; -} - -static void shutdown(GfxAppState* state) { - assert(state); - - IsoBackendShutdown(&state->backend); - isogfx_del(&state->iso); -} - -static void update(GfxAppState* state, double t, double dt) { - assert(state); - (void)dt; - - IsoGfx* iso = state->iso; - - isogfx_update(iso, t); - - // Get mouse position in window coordinates. - double mouse_x, mouse_y; - gfx_app_get_mouse_position(&mouse_x, &mouse_y); - - // Map from window coordinates to virtual screen coordinates. - IsoBackendGetMousePosition( - state->backend, mouse_x, mouse_y, &mouse_x, &mouse_y); - - isogfx_pick_tile(iso, mouse_x, mouse_y, &state->xpick, &state->ypick); - - printf("Picked tile: (%d, %d)\n", state->xpick, state->ypick); -} - -static void render(GfxAppState* state) { - assert(state); - - IsoGfx* iso = state->iso; - - isogfx_render(iso); - - if ((state->xpick != -1) && (state->ypick != -1)) { - isogfx_draw_tile(iso, state->xpick, state->ypick, state->red); - } - - IsoBackendRender(state->backend, iso); -} - -static void resize(GfxAppState* state, int width, int height) { - assert(state); - - IsoBackendResizeWindow(state->backend, state->iso, width, height); -} - -int main(int argc, const char** argv) { - GfxAppState state = {0}; - gfx_app_run( - &(GfxAppDesc){ - .argc = argc, - .argv = argv, - .width = WINDOW_WIDTH, - .height = WINDOW_HEIGHT, - .max_fps = MAX_FPS, - .update_delta_time = MAX_FPS > 0 ? 1.0 / (double)MAX_FPS : 0.0, - .title = "Isometric Renderer", - .app_state = &state}, - &(GfxAppCallbacks){ - .init = init, - .update = update, - .render = render, - .resize = resize, - .shutdown = shutdown}); - return 0; -} diff --git a/gfx-iso/demos/isomap/CMakeLists.txt b/gfx-iso/demos/isomap/CMakeLists.txt deleted file mode 100644 index 2dbfd32..0000000 --- a/gfx-iso/demos/isomap/CMakeLists.txt +++ /dev/null @@ -1,16 +0,0 @@ -cmake_minimum_required(VERSION 3.0) - -project(isomap) - -set(CMAKE_C_STANDARD 17) -set(CMAKE_C_STANDARD_REQUIRED On) -set(CMAKE_C_EXTENSIONS Off) - -add_executable(isomap - isomap.c) - -target_link_libraries(isomap PRIVATE - gfx-app - isogfx-backend) - -target_compile_options(isomap PRIVATE -Wall -Wextra -Wpedantic) diff --git a/gfx-iso/demos/isomap/isomap.c b/gfx-iso/demos/isomap/isomap.c deleted file mode 100644 index a233659..0000000 --- a/gfx-iso/demos/isomap/isomap.c +++ /dev/null @@ -1,105 +0,0 @@ -#include -#include - -#include - -#include -#include - -static const int WINDOW_WIDTH = 1408; -static const int WINDOW_HEIGHT = 960; -static const int MAX_FPS = 60; - -// Virtual screen dimensions. -static const int SCREEN_WIDTH = 704; -static const int SCREEN_HEIGHT = 480; - -typedef struct GfxAppState { - IsoBackend* backend; - IsoGfx* iso; - int xpick; - int ypick; - SpriteSheet stag_sheet; - Sprite stag; -} GfxAppState; - -static bool init(GfxAppState* state, int argc, const char** argv) { - assert(state); - (void)argc; - (void)argv; - - if (!(state->iso = isogfx_new(&(IsoGfxDesc){ - .screen_width = SCREEN_WIDTH, .screen_height = SCREEN_HEIGHT}))) { - return false; - } - IsoGfx* iso = state->iso; - - isogfx_resize(iso, SCREEN_WIDTH, SCREEN_HEIGHT); - - if (!isogfx_load_world(iso, "/home/jeanne/assets/tilemaps/demo1.tm")) { - return false; - } - - if (!isogfx_load_sprite_sheet( - iso, "/home/jeanne/assets/tilesets/scrabling/critters/stag/stag.ss", - &state->stag_sheet)) { - return false; - } - - state->stag = isogfx_make_sprite(iso, state->stag_sheet); - isogfx_set_sprite_position(iso, state->stag, 5, 4); - - if (!(state->backend = IsoBackendInit(iso))) { - return false; - } - - return true; -} - -static void shutdown(GfxAppState* state) { - assert(state); - // -} - -static void update(GfxAppState* state, double t, double dt) { - assert(state); - (void)dt; - - IsoGfx* iso = state->iso; - isogfx_update(iso, t); -} - -static void render(GfxAppState* state) { - assert(state); - - IsoGfx* iso = state->iso; - isogfx_render(iso); - IsoBackendRender(state->backend, iso); -} - -static void resize(GfxAppState* state, int width, int height) { - assert(state); - - IsoBackendResizeWindow(state->backend, state->iso, width, height); -} - -int main(int argc, const char** argv) { - GfxAppState state = {0}; - gfx_app_run( - &(GfxAppDesc){ - .argc = argc, - .argv = argv, - .width = WINDOW_WIDTH, - .height = WINDOW_HEIGHT, - .max_fps = MAX_FPS, - .update_delta_time = MAX_FPS > 0 ? 1.0 / (double)MAX_FPS : 0.0, - .title = "Isometric Renderer", - .app_state = &state}, - &(GfxAppCallbacks){ - .init = init, - .update = update, - .render = render, - .resize = resize, - .shutdown = shutdown}); - return 0; -} diff --git a/gfx-iso/include/isogfx/backend.h b/gfx-iso/include/isogfx/backend.h deleted file mode 100644 index 172991d..0000000 --- a/gfx-iso/include/isogfx/backend.h +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once - -#include - -typedef struct Gfx Gfx; -typedef struct IsoGfx IsoGfx; - -typedef struct IsoBackend IsoBackend; - -/// Initialize the backend. -IsoBackend* IsoBackendInit(const IsoGfx*); - -/// Shut down the backend. -void IsoBackendShutdown(IsoBackend**); - -/// Notify the backend of a window resize event. -/// This allows the backend to determine how to position and scale the iso -/// screen buffer on the graphics window. -void IsoBackendResizeWindow(IsoBackend*, const IsoGfx*, int width, int height); - -/// Render the iso screen to the graphics window. -void IsoBackendRender(const IsoBackend*, const IsoGfx*); - -/// Map window coordinates to iso space coordinates. -/// This takes into account any possible resizing done by the backend in -/// response to calls to IsoBackendResizeWindow(). -bool IsoBackendGetMousePosition( - const IsoBackend*, double window_x, double window_y, double* x, double* y); diff --git a/gfx-iso/include/isogfx/isogfx.h b/gfx-iso/include/isogfx/isogfx.h deleted file mode 100644 index 3421a7b..0000000 --- a/gfx-iso/include/isogfx/isogfx.h +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Isometric rendering engine. - */ -#pragma once - -#include -#include - -typedef struct IsoGfx IsoGfx; - -/// Sprite sheet handle. -typedef uint16_t SpriteSheet; - -/// Sprite handle. -typedef uint16_t Sprite; - -/// Tile handle. -typedef uint16_t Tile; - -/// Colour channel. -typedef uint8_t Channel; - -typedef struct Pixel { - Channel r, g, b, a; -} Pixel; - -typedef enum TileDescType { - TileFromColour, - TileFromFile, - TileFromMemory, -} TileDescType; - -typedef struct TileDesc { - TileDescType type; - int width; /// Tile width in pixels. - int height; /// Tile height in pixels. - union { - Pixel colour; /// Constant colour tile. - struct { - const char* path; - } file; - struct { - const uint8_t* data; /// sizeof(Pixel) * width * height - } mem; - }; -} TileDesc; - -typedef struct WorldDesc { - int tile_width; /// Base tile width in pixels. - int tile_height; /// Base tile height in pixels. - int world_width; /// World width in tiles. - int world_height; /// World height in tiles. - int max_num_tiles; /// 0 for an implementation-defined default. -} WorldDesc; - -typedef struct IsoGfxDesc { - int screen_width; /// Screen width in pixels. - int screen_height; /// Screen height in pixels. - int max_num_sprites; /// 0 for an implementation-defined default. - int sprite_sheet_pool_size_bytes; /// 0 for an implementation-defined default. -} IsoGfxDesc; - -/// Create a new isometric graphics engine. -IsoGfx* isogfx_new(const IsoGfxDesc*); - -/// Destroy the isometric graphics engine. -void isogfx_del(IsoGfx**); - -/// Create an empty world. -bool isogfx_make_world(IsoGfx*, const WorldDesc*); - -/// Load a world from a tile map (.TM) file. -bool isogfx_load_world(IsoGfx*, const char* filepath); - -/// Return the world's width. -int isogfx_world_width(const IsoGfx*); - -/// Return the world's height. -int isogfx_world_height(const IsoGfx*); - -/// Create a new tile. -Tile isogfx_make_tile(IsoGfx*, const TileDesc*); - -/// Set the tile at position (x,y). -void isogfx_set_tile(IsoGfx*, int x, int y, Tile); - -/// Set the tiles in positions in the range (x0,y0) - (x1,y1). -void isogfx_set_tiles(IsoGfx*, int x0, int y0, int x1, int y1, Tile); - -/// Load a sprite sheet (.SS) file. -bool isogfx_load_sprite_sheet(IsoGfx*, const char* filepath, SpriteSheet*); - -/// Create an animated sprite. -Sprite isogfx_make_sprite(IsoGfx*, SpriteSheet); - -/// Destroy the sprite. -void isogfx_del_sprite(IsoGfx*, Sprite); - -/// Destroy all the sprites. -void isogfx_del_sprites(IsoGfx*); - -/// Set the sprite's position. -void isogfx_set_sprite_position(IsoGfx*, Sprite, int x, int y); - -/// Set the sprite's current animation. -void isogfx_set_sprite_animation(IsoGfx*, Sprite, int animation); - -/// Update the renderer. -/// -/// Currently this updates the sprite animations. -void isogfx_update(IsoGfx*, double t); - -/// Render the world. -void isogfx_render(IsoGfx*); - -/// Draw/overlay a tile at position (x,y). -/// -/// This function just renders a tile at position (x,y) and should be called -/// after isogfx_render() to obtain the correct result. To set the tile at -/// position (x,y) instead, use isogfx_set_tile(). -void isogfx_draw_tile(IsoGfx*, int x, int y, Tile); - -/// Resize the virtual screen's dimensions. -bool isogfx_resize(IsoGfx*, int screen_width, int screen_height); - -/// Get the virtual screen's dimensions. -void isogfx_get_screen_size(const IsoGfx*, int* width, int* height); - -/// Return a pointer to the virtual screen's colour buffer. -/// -/// Call after each call to isogfx_render() to retrieve the render output. -const Pixel* isogfx_get_screen_buffer(const IsoGfx*); - -/// Translate Cartesian to isometric coordinates. -void isogfx_pick_tile( - const IsoGfx*, double xcart, double ycart, int* xiso, int* yiso); diff --git a/gfx-iso/src/backend.c b/gfx-iso/src/backend.c deleted file mode 100644 index db91647..0000000 --- a/gfx-iso/src/backend.c +++ /dev/null @@ -1,199 +0,0 @@ -#include -#include - -#include -#include -#include -#include -#include -#include - -#include -#include - -typedef struct IsoBackend { - Gfx* gfx; - Scene* scene; - /// The screen or "iso screen" refers to the colour buffer of the iso graphics - /// library. This texture is used to draw the iso screen onto the graphics - /// window. - Texture* screen_texture; - /// Window size. - int window_width; - int window_height; - /// The viewport refers to the area inside the window to which screen_texture - /// is drawn. It is a scaled version of the iso screen, scaled while - /// respecting the iso screen's aspect ratio to prevent distortion. - int viewport_x, viewport_y, viewport_width, viewport_height; - double stretch; // Stretch factor from iso screen dimensions to viewport - // dimensions. -} IsoBackend; - -IsoBackend* IsoBackendInit(const IsoGfx* iso) { - assert(iso); - - IsoBackend* backend = calloc(1, sizeof(IsoBackend)); - if (!backend) { - return 0; - } - - if (!(backend->gfx = gfx_init())) { - goto cleanup; - } - GfxCore* gfxcore = gfx_get_core(backend->gfx); - - int screen_width, screen_height; - isogfx_get_screen_size(iso, &screen_width, &screen_height); - - if (!(backend->screen_texture = gfx_make_texture( - gfxcore, &(TextureDesc){ - .width = screen_width, - .height = screen_height, - .dimension = Texture2D, - .format = TextureSRGBA8, - .filtering = NearestFiltering, - .wrap = ClampToEdge, - .mipmaps = false}))) { - goto cleanup; - } - - ShaderProgram* shader = gfx_make_view_texture_shader(gfxcore); - if (!shader) { - goto cleanup; - } - - Geometry* geometry = gfx_make_quad_11(gfxcore); - if (!geometry) { - goto cleanup; - } - - MaterialDesc material_desc = (MaterialDesc){.num_uniforms = 1}; - material_desc.uniforms[0] = (ShaderUniform){ - .type = UniformTexture, - .value.texture = backend->screen_texture, - .name = sstring_make("Texture")}; - Material* material = gfx_make_material(&material_desc); - if (!material) { - return false; - } - - const MeshDesc mesh_desc = - (MeshDesc){.geometry = geometry, .material = material, .shader = shader}; - Mesh* mesh = gfx_make_mesh(&mesh_desc); - if (!mesh) { - goto cleanup; - } - - SceneObject* object = - gfx_make_object(&(ObjectDesc){.num_meshes = 1, .meshes = {mesh}}); - if (!object) { - goto cleanup; - } - - backend->scene = gfx_make_scene(); - SceneNode* node = gfx_make_object_node(object); - SceneNode* root = gfx_get_scene_root(backend->scene); - gfx_set_node_parent(node, root); - - return backend; - -cleanup: - if (backend->gfx) { - gfx_destroy(&backend->gfx); - } - free(backend); - return 0; -} - -void IsoBackendShutdown(IsoBackend** ppApp) { - assert(ppApp); - - IsoBackend* app = *ppApp; - if (!app) { - return; - } - - gfx_destroy(&app->gfx); -} - -void IsoBackendResizeWindow( - IsoBackend* app, const IsoGfx* iso, int width, int height) { - assert(app); - assert(iso); - - app->window_width = width; - app->window_height = height; - - // Virtual screen dimensions. - int screen_width, screen_height; - isogfx_get_screen_size(iso, &screen_width, &screen_height); - - // Stretch the virtual screen onto the viewport while respecting the screen's - // aspect ratio to prevent distortion. - if (width > height) { // Wide screen. - app->stretch = (double)height / (double)screen_height; - app->viewport_width = (int)((double)screen_width * app->stretch); - app->viewport_height = height; - app->viewport_x = (width - app->viewport_width) / 2; - app->viewport_y = 0; - } else { // Tall screen. - app->stretch = (double)width / (double)screen_width; - app->viewport_width = width; - app->viewport_height = (int)((float)screen_height * app->stretch); - app->viewport_x = 0; - app->viewport_y = (height - app->viewport_height) / 2; - } -} - -void IsoBackendRender(const IsoBackend* app, const IsoGfx* iso) { - assert(app); - assert(iso); - - const Pixel* screen = isogfx_get_screen_buffer(iso); - assert(screen); - gfx_update_texture(app->screen_texture, &(TextureDataDesc){.pixels = screen}); - - GfxCore* gfxcore = gfx_get_core(app->gfx); - Renderer* renderer = gfx_get_renderer(app->gfx); - - // Clear the whole window. - gfx_set_viewport(gfxcore, 0, 0, app->window_width, app->window_height); - gfx_clear(gfxcore, vec4_make(0, 0, 0, 0)); - - // Draw to the subregion where the virtual screen can stretch without - // distortion. - gfx_set_viewport( - gfxcore, app->viewport_x, app->viewport_y, app->viewport_width, - app->viewport_height); - - // Render the iso screen. - gfx_start_frame(gfxcore); - gfx_render_scene( - renderer, &(RenderSceneParams){ - .mode = RenderDefault, .scene = app->scene, .camera = 0}); - gfx_end_frame(gfxcore); -} - -bool IsoBackendGetMousePosition( - const IsoBackend* app, double window_x, double window_y, double* x, - double* y) { - assert(app); - - // Translate from window coordinates to the subregion where the stretched - // iso screen is rendered. - const double screen_x = window_x - app->viewport_x; - const double screen_y = window_y - app->viewport_y; - - // Position may be out of bounds. - if ((0 <= screen_x) && (screen_x < app->viewport_width) && (0 <= screen_y) && - (screen_y < app->viewport_height)) { - // Scale back from the stretched subregion to the iso screen dimensions. - *x = screen_x / app->stretch; - *y = screen_y / app->stretch; - return true; - } else { - *x = -1; - *y = -1; - return false; - } -} diff --git a/gfx-iso/src/isogfx.c b/gfx-iso/src/isogfx.c deleted file mode 100644 index 52c4ae2..0000000 --- a/gfx-iso/src/isogfx.c +++ /dev/null @@ -1,952 +0,0 @@ -#include - -#include -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include - -/// Maximum number of tiles unless the user specifies a value. -#define DEFAULT_MAX_NUM_TILES 1024 - -/// Maximum number of sprites unless the user specifies a value. -#define DEFAULT_MAX_NUM_SPRITES 128 - -/// Size of sprite sheet pool in bytes unless the user specifies a value. -#define DEFAULT_SPRITE_SHEET_POOL_SIZE_BYTES (8 * 1024 * 1024) - -/// Default animation speed. -#define ANIMATION_FPS 10 - -/// Time between animation updates. -#define ANIMATION_UPDATE_DELTA (1.0 / ANIMATION_FPS) - -typedef struct ivec2 { - int x, y; -} ivec2; - -typedef struct vec2 { - double x, y; -} vec2; - -// ----------------------------------------------------------------------------- -// Tile set (TS) and tile map (TM) file formats. -// ----------------------------------------------------------------------------- - -/// Maximum length of path strings in .TS and .TM files. -#define MAX_PATH_LENGTH 128 - -typedef struct Ts_Tile { - uint16_t width; /// Tile width in pixels. - uint16_t height; /// Tile height in pixels. - Pixel pixels[1]; /// Count: width * height. -} Ts_Tile; - -typedef struct Ts_TileSet { - uint16_t num_tiles; - uint16_t max_tile_width; /// Maximum tile width in pixels. - uint16_t max_tile_height; /// Maximum tile height in pixels. - Ts_Tile tiles[1]; /// Count: num_tiles. -} Ts_TileSet; - -typedef struct Tm_Layer { - union { - char tileset_path[MAX_PATH_LENGTH]; // Relative to the Tm_Map file. - }; - Tile tiles[1]; /// Count: world_width * world_height. -} Tm_Layer; - -typedef struct Tm_Map { - uint16_t world_width; /// World width in number of tiles. - uint16_t world_height; /// World height in number of tiles. - uint16_t base_tile_width; - uint16_t base_tile_height; - uint16_t num_layers; - Tm_Layer layers[1]; // Count: num_layers. -} Tm_Map; - -static inline const Tm_Layer* tm_map_get_next_layer( - const Tm_Map* map, const Tm_Layer* layer) { - assert(map); - assert(layer); - return (const Tm_Layer*)((const uint8_t*)layer + sizeof(Tm_Layer) + - ((map->world_width * map->world_height - 1) * - sizeof(Tile))); -} - -static inline const Ts_Tile* ts_tileset_get_next_tile( - const Ts_TileSet* tileset, const Ts_Tile* tile) { - assert(tileset); - assert(tile); - return (const Ts_Tile*)((const uint8_t*)tile + sizeof(Ts_Tile) + - ((tile->width * tile->height - 1) * sizeof(Pixel))); -} - -// ----------------------------------------------------------------------------- -// Sprite sheet file format. -// ----------------------------------------------------------------------------- - -/// A row of sprites in a sprite sheet. -/// -/// Each row in a sprite sheet can have a different number of columns. -/// -/// The pixels of the row follow a "sprite-major" order. It contains the -/// 'sprite_width * sprite_height' pixels for the first column/sprite, then the -/// second column/sprite, etc. -/// -/// Pixels are 8-bit indices into the sprite sheet's colour palette. -typedef struct Ss_Row { - uint16_t num_cols; /// Number of columns in this row. - uint8_t pixels[1]; /// Count: num_cols * sprite_width * sprite_height. -} Ss_Row; - -typedef struct Ss_Palette { - uint16_t num_colours; - Pixel colours[1]; /// Count: num_colors. -} Ss_Palette; - -/// Sprite sheet top-level data definition. -/// -/// Sprite width and height are assumed constant throughout the sprite sheet. -typedef struct Ss_SpriteSheet { - uint16_t sprite_width; /// Sprite width in pixels. - uint16_t sprite_height; /// Sprite height in pixels. - uint16_t num_rows; - Ss_Palette palette; /// Variable size. - Ss_Row rows[1]; /// Count: num_rows. Variable offset. -} Ss_SpriteSheet; - -static inline const Ss_Row* get_sprite_sheet_row( - const Ss_SpriteSheet* sheet, int row) { - assert(sheet); - assert(row >= 0); - assert(row < sheet->num_rows); - // Skip over the palette. - const Ss_Row* rows = - (const Ss_Row*)(&sheet->palette.colours[0] + sheet->palette.num_colours); - return &rows[row]; -} - -static inline const uint8_t* get_sprite_sheet_sprite( - const Ss_SpriteSheet* sheet, const Ss_Row* row, int col) { - assert(sheet); - assert(row); - assert(col >= 0); - assert(col < row->num_cols); - const int sprite_offset = col * sheet->sprite_width * sheet->sprite_height; - const uint8_t* sprite = &row->pixels[sprite_offset]; - return sprite; -} - -// ----------------------------------------------------------------------------- -// Renderer state. -// ----------------------------------------------------------------------------- - -typedef struct TileData { - uint16_t width; - uint16_t height; - uint16_t pixels_handle; // Handle to the tile's pixels in the pixel pool. -} TileData; - -// File format is already convenient for working in memory. -typedef Ss_Row SpriteSheetRow; -typedef Ss_SpriteSheet SpriteSheetData; - -typedef struct SpriteData { - SpriteSheet sheet; // Handle to the sprite's sheet. - ivec2 position; - int animation; // Current animation. - int frame; // Current frame of animation. -} SpriteData; - -DEF_MEMPOOL_DYN(TilePool, TileData) -DEF_MEM_DYN(PixelPool, Pixel) - -DEF_MEMPOOL_DYN(SpritePool, SpriteData) -DEF_MEM_DYN(SpriteSheetPool, SpriteSheetData) - -typedef struct IsoGfx { - int screen_width; - int screen_height; - int tile_width; - int tile_height; - int world_width; - int world_height; - int max_num_sprites; - int sprite_sheet_pool_size_bytes; - double last_animation_time; - Tile* world; - Pixel* screen; - TilePool tiles; - PixelPool pixels; - SpritePool sprites; - SpriteSheetPool sheets; -} IsoGfx; - -// ----------------------------------------------------------------------------- -// Math and world / tile / screen access. -// ----------------------------------------------------------------------------- - -static inline ivec2 ivec2_add(ivec2 a, ivec2 b) { - return (ivec2){.x = a.x + b.x, .y = a.y + b.y}; -} - -static inline ivec2 ivec2_scale(ivec2 a, int s) { - return (ivec2){.x = a.x * s, .y = a.y * s}; -} - -static inline ivec2 iso2cart(ivec2 iso, int s, int t, int w) { - return (ivec2){ - .x = (iso.x - iso.y) * (s / 2) + (w / 2), .y = (iso.x + iso.y) * (t / 2)}; -} - -// Method 1. -// static inline vec2 cart2iso(vec2 cart, int s, int t, int w) { -// const double x = cart.x - (double)(w / 2); -// const double xiso = (x * t + cart.y * s) / (double)(s * t); -// return (vec2){ -// .x = (int)(xiso), .y = (int)((2.0 / (double)t) * cart.y - xiso)}; -//} - -// Method 2. -static inline vec2 cart2iso(vec2 cart, int s, int t, int w) { - const double one_over_s = 1. / (double)s; - const double one_over_t = 1. / (double)t; - const double x = cart.x - (double)(w / 2); - return (vec2){ - .x = (one_over_s * x + one_over_t * cart.y), - .y = (-one_over_s * x + one_over_t * cart.y)}; -} - -static const Pixel* tile_xy_const_ref( - const IsoGfx* iso, const TileData* tile, int x, int y) { - assert(iso); - assert(tile); - assert(x >= 0); - assert(y >= 0); - assert(x < tile->width); - assert(y < tile->height); - return &mem_get_chunk(&iso->pixels, tile->pixels_handle)[y * tile->width + x]; -} - -// static Pixel tile_xy(const IsoGfx* iso, const TileData* tile, int x, int y) { -// return *tile_xy_const_ref(iso, tile, x, y); -// } - -static Pixel* tile_xy_mut(const IsoGfx* iso, TileData* tile, int x, int y) { - return (Pixel*)tile_xy_const_ref(iso, tile, x, y); -} - -static inline const Tile* world_xy_const_ref(const IsoGfx* iso, int x, int y) { - assert(iso); - assert(x >= 0); - assert(y >= 0); - assert(x < iso->world_width); - assert(y < iso->world_height); - return &iso->world[y * iso->world_width + x]; -} - -static inline Tile world_xy(const IsoGfx* iso, int x, int y) { - return *world_xy_const_ref(iso, x, y); -} - -static inline Tile* world_xy_mut(IsoGfx* iso, int x, int y) { - return (Tile*)world_xy_const_ref(iso, x, y); -} - -static inline const Pixel* screen_xy_const_ref( - const IsoGfx* iso, int x, int y) { - assert(iso); - assert(x >= 0); - assert(y >= 0); - assert(x < iso->screen_width); - assert(y < iso->screen_height); - return &iso->screen[y * iso->screen_width + x]; -} - -static inline Pixel screen_xy(IsoGfx* iso, int x, int y) { - return *screen_xy_const_ref(iso, x, y); -} - -static inline Pixel* screen_xy_mut(IsoGfx* iso, int x, int y) { - return (Pixel*)screen_xy_const_ref(iso, x, y); -} - -static int calc_num_tile_blocks( - int base_tile_width, int base_tile_height, int tile_width, - int tile_height) { - const int base_tile_size = base_tile_width * base_tile_height; - const int tile_size = tile_width * tile_height; - const int num_blocks = tile_size / base_tile_size; - return num_blocks; -} - -// ----------------------------------------------------------------------------- -// Renderer, world and tile management. -// ----------------------------------------------------------------------------- - -IsoGfx* isogfx_new(const IsoGfxDesc* desc) { - assert(desc->screen_width > 0); - assert(desc->screen_height > 0); - // Part of our implementation assumes even widths and heights for precision. - assert((desc->screen_width & 1) == 0); - assert((desc->screen_height & 1) == 0); - - IsoGfx* iso = calloc(1, sizeof(IsoGfx)); - if (!iso) { - return 0; - } - - iso->screen_width = desc->screen_width; - iso->screen_height = desc->screen_height; - - iso->last_animation_time = 0.0; - - iso->max_num_sprites = desc->max_num_sprites == 0 ? DEFAULT_MAX_NUM_SPRITES - : desc->max_num_sprites; - iso->sprite_sheet_pool_size_bytes = desc->sprite_sheet_pool_size_bytes == 0 - ? DEFAULT_SPRITE_SHEET_POOL_SIZE_BYTES - : desc->sprite_sheet_pool_size_bytes; - - const int screen_size = desc->screen_width * desc->screen_height; - if (!(iso->screen = calloc(screen_size, sizeof(Pixel)))) { - goto cleanup; - } - - return iso; - -cleanup: - isogfx_del(&iso); - return 0; -} - -/// Destroy the world, its tile set, and the underlying pools. -static void destroy_world(IsoGfx* iso) { - assert(iso); - if (iso->world) { - free(iso->world); - iso->world = 0; - } - mempool_del(&iso->tiles); - mem_del(&iso->pixels); -} - -/// Destroy all loaded sprites and the underlying pools. -static void destroy_sprites(IsoGfx* iso) { - assert(iso); - mempool_del(&iso->sprites); - mem_del(&iso->sheets); -} - -void isogfx_del(IsoGfx** pIso) { - assert(pIso); - IsoGfx* iso = *pIso; - if (iso) { - destroy_world(iso); - destroy_sprites(iso); - if (iso->screen) { - free(iso->screen); - iso->screen = 0; - } - free(iso); - *pIso = 0; - } -} - -bool isogfx_make_world(IsoGfx* iso, const WorldDesc* desc) { - assert(iso); - assert(desc); - assert(desc->tile_width > 0); - assert(desc->tile_height > 0); - // Part of our implementation assumes even widths and heights for greater - // precision. - assert((desc->tile_width & 1) == 0); - assert((desc->tile_height & 1) == 0); - - // Handle recreation by destroying the previous world. - destroy_world(iso); - - iso->tile_width = desc->tile_width; - iso->tile_height = desc->tile_height; - iso->world_width = desc->world_width; - iso->world_height = desc->world_height; - - const int world_size = desc->world_width * desc->world_height; - const int tile_size = desc->tile_width * desc->tile_height; - const int tile_size_bytes = tile_size * (int)sizeof(Pixel); - const int tile_pool_size = - desc->max_num_tiles > 0 ? desc->max_num_tiles : DEFAULT_MAX_NUM_TILES; - - if (!(iso->world = calloc(world_size, sizeof(Tile)))) { - goto cleanup; - } - if (!mempool_make_dyn(&iso->tiles, world_size, sizeof(TileData))) { - goto cleanup; - } - if (!mem_make_dyn(&iso->pixels, tile_pool_size, tile_size_bytes)) { - goto cleanup; - } - - return true; - -cleanup: - destroy_world(iso); - return false; -} - -bool isogfx_load_world(IsoGfx* iso, const char* filepath) { - assert(iso); - assert(filepath); - - bool success = false; - - // Handle recreation by destroying the previous world. - destroy_world(iso); - - // Load the map. - printf("Load tile map: %s\n", filepath); - Tm_Map* map = read_file(filepath); - if (!map) { - goto cleanup; - } - - // Allocate memory for the map and tile sets. - const int world_size = map->world_width * map->world_height; - const int base_tile_size = map->base_tile_width * map->base_tile_height; - const int base_tile_size_bytes = base_tile_size * (int)sizeof(Pixel); - // TODO: Need to get the total number of tiles from the map. - const int tile_pool_size = DEFAULT_MAX_NUM_TILES; - - if (!(iso->world = calloc(world_size, sizeof(Tile)))) { - goto cleanup; - } - if (!mempool_make_dyn(&iso->tiles, tile_pool_size, sizeof(TileData))) { - goto cleanup; - } - if (!mem_make_dyn(&iso->pixels, tile_pool_size, base_tile_size_bytes)) { - goto cleanup; - } - - // Load the tile sets. - const Tm_Layer* layer = &map->layers[0]; - // TODO: Handle num_layers layers. - for (int i = 0; i < 1; ++i) { - const char* ts_path = layer->tileset_path; - - // Tile set path is relative to the tile map file. Make it relative to the - // current working directory before loading. - char ts_path_cwd[PATH_MAX] = {0}; - if (!path_make_relative(filepath, ts_path, ts_path_cwd, PATH_MAX)) { - goto cleanup; - } - - Ts_TileSet* tileset = read_file(ts_path_cwd); - if (!tileset) { - goto cleanup; - }; - - // Load tile data. - const Ts_Tile* tile = &tileset->tiles[0]; - for (uint16_t j = 0; j < tileset->num_tiles; ++j) { - // Tile dimensions should be a multiple of the base tile size. - assert((tile->width % map->base_tile_width) == 0); - assert((tile->height % map->base_tile_height) == 0); - - // Allocate N base tile size blocks for the tile. - const uint16_t tile_size = tile->width * tile->height; - const int num_blocks = tile_size / base_tile_size; - Pixel* pixels = mem_alloc(&iso->pixels, num_blocks); - assert(pixels); - memcpy(pixels, tile->pixels, tile_size * sizeof(Pixel)); - - // Allocate the tile data. - TileData* tile_data = mempool_alloc(&iso->tiles); - assert(tile_data); - tile_data->width = tile->width; - tile_data->height = tile->height; - tile_data->pixels_handle = - (uint16_t)mem_get_chunk_handle(&iso->pixels, pixels); - - tile = ts_tileset_get_next_tile(tileset, tile); - } - - printf("Loaded tile set (%u tiles): %s\n", tileset->num_tiles, ts_path_cwd); - - free(tileset); - layer = tm_map_get_next_layer(map, layer); - } - - // Load the map into the world. - layer = &map->layers[0]; - // TODO: Handle num_layers layers. - for (int i = 0; i < 1; ++i) { - memcpy(iso->world, layer->tiles, world_size * sizeof(Tile)); - - // TODO: We need to handle 'firsgid' in TMX files. - for (int j = 0; j < world_size; ++j) { - iso->world[j] -= 1; - } - - layer = tm_map_get_next_layer(map, layer); - } - - iso->world_width = map->world_width; - iso->world_height = map->world_height; - iso->tile_width = map->base_tile_width; - iso->tile_height = map->base_tile_height; - - success = true; - -cleanup: - if (map) { - free(map); - } - if (!success) { - destroy_world(iso); - } - return success; -} - -int isogfx_world_width(const IsoGfx* iso) { - assert(iso); - return iso->world_width; -} - -int isogfx_world_height(const IsoGfx* iso) { - assert(iso); - return iso->world_height; -} - -/// Create a tile mask procedurally. -static void make_tile_from_colour( - const IsoGfx* iso, Pixel colour, TileData* tile) { - assert(iso); - assert(tile); - - const int width = tile->width; - const int height = tile->height; - const int r = width / height; - - for (int y = 0; y < height / 2; ++y) { - const int mask_start = width / 2 - r * y - 1; - const int mask_end = width / 2 + r * y + 1; - for (int x = 0; x < width; ++x) { - const bool mask = (mask_start <= x) && (x <= mask_end); - const Pixel val = mask ? colour : (Pixel){.r = 0, .g = 0, .b = 0, .a = 0}; - - // Top half. - *tile_xy_mut(iso, tile, x, y) = val; - - // Bottom half reflects the top half. - const int y_reflected = height - y - 1; - *tile_xy_mut(iso, tile, x, y_reflected) = val; - } - } -} - -Tile isogfx_make_tile(IsoGfx* iso, const TileDesc* desc) { - assert(iso); - assert(desc); - // Client must create world before creating tiles. - assert(iso->tile_width > 0); - assert(iso->tile_height > 0); - - TileData* tile = mempool_alloc(&iso->tiles); - assert(tile); // TODO: Make this a hard assert. - - const int num_blocks = calc_num_tile_blocks( - iso->tile_width, iso->tile_height, desc->width, desc->height); - - Pixel* pixels = mem_alloc(&iso->pixels, num_blocks); - assert(pixels); // TODO: Make this a hard assert. - - tile->width = desc->width; - tile->height = desc->height; - tile->pixels_handle = mem_get_chunk_handle(&iso->pixels, pixels); - - switch (desc->type) { - case TileFromColour: - make_tile_from_colour(iso, desc->colour, tile); - break; - case TileFromFile: - assert(false); // TODO - break; - case TileFromMemory: - assert(false); // TODO - break; - } - - return (Tile)mempool_get_block_index(&iso->tiles, tile); -} - -void isogfx_set_tile(IsoGfx* iso, int x, int y, Tile tile) { - assert(iso); - *world_xy_mut(iso, x, y) = tile; -} - -void isogfx_set_tiles(IsoGfx* iso, int x0, int y0, int x1, int y1, Tile tile) { - assert(iso); - for (int y = y0; y < y1; ++y) { - for (int x = x0; x < x1; ++x) { - isogfx_set_tile(iso, x, y, tile); - } - } -} - -bool isogfx_load_sprite_sheet( - IsoGfx* iso, const char* filepath, SpriteSheet* p_sheet) { - assert(iso); - assert(filepath); - assert(p_sheet); - - bool success = false; - - // Lazy initialization of sprite pools. - if (mempool_capacity(&iso->sprites) == 0) { - if (!mempool_make_dyn( - &iso->sprites, iso->max_num_sprites, sizeof(SpriteData))) { - return false; - } - } - if (mem_capacity(&iso->sheets) == 0) { - // Using a block size of 1 byte for sprite sheet data. - if (!mem_make_dyn(&iso->sheets, iso->sprite_sheet_pool_size_bytes, 1)) { - return false; - } - } - - // Load sprite sheet file. - printf("Load sprite sheet: %s\n", filepath); - FILE* file = fopen(filepath, "rb"); - if (file == NULL) { - goto cleanup; - } - const size_t sheet_size = get_file_size(file); - SpriteSheetData* ss_sheet = mem_alloc(&iso->sheets, sheet_size); - if (!ss_sheet) { - goto cleanup; - } - if (fread(ss_sheet, sheet_size, 1, file) != 1) { - goto cleanup; - } - - *p_sheet = mem_get_chunk_handle(&iso->sheets, ss_sheet); - success = true; - -cleanup: - // Pools remain initialized since client may attempt to load other sprites. - if (file != NULL) { - fclose(file); - } - if (!success) { - if (ss_sheet) { - mem_free(&iso->sheets, &ss_sheet); - } - } - return success; -} - -Sprite isogfx_make_sprite(IsoGfx* iso, SpriteSheet sheet) { - assert(iso); - - SpriteData* sprite = mempool_alloc(&iso->sprites); - assert(sprite); - - sprite->sheet = sheet; - - return mempool_get_block_index(&iso->sprites, sprite); -} - -#define with_sprite(SPRITE, BODY) \ - { \ - SpriteData* data = mempool_get_block(&iso->sprites, sprite); \ - assert(data); \ - BODY; \ - } - -void isogfx_set_sprite_position(IsoGfx* iso, Sprite sprite, int x, int y) { - assert(iso); - with_sprite(sprite, { - data->position.x = x; - data->position.y = y; - }); -} - -void isogfx_set_sprite_animation(IsoGfx* iso, Sprite sprite, int animation) { - assert(iso); - with_sprite(sprite, { data->animation = animation; }); -} - -void isogfx_update(IsoGfx* iso, double t) { - assert(iso); - - // If this is the first time update() is called after initialization, just - // record the starting animation time. - if (iso->last_animation_time == 0.0) { - iso->last_animation_time = t; - return; - } - - if ((t - iso->last_animation_time) >= ANIMATION_UPDATE_DELTA) { - // TODO: Consider linking animated sprites in a list so that we only walk - // over those here and not also the static sprites. - mempool_foreach(&iso->sprites, sprite, { - const SpriteSheetData* sheet = mem_get_chunk(&iso->sheets, sprite->sheet); - assert(sheet); // TODO: Make this a hard assert inside the mem/pool. - const SpriteSheetRow* row = - get_sprite_sheet_row(sheet, sprite->animation); - sprite->frame = (sprite->frame + 1) % row->num_cols; - }); - - iso->last_animation_time = t; - } -} - -// ----------------------------------------------------------------------------- -// Rendering and picking. -// ----------------------------------------------------------------------------- - -typedef struct CoordSystem { - ivec2 o; /// Origin. - ivec2 x; - ivec2 y; -} CoordSystem; - -/// Create the basis for the isometric coordinate system with origin and vectors -/// expressed in the Cartesian system. -static CoordSystem make_iso_coord_system(const IsoGfx* iso) { - assert(iso); - const ivec2 o = {iso->screen_width / 2, 0}; - const ivec2 x = {.x = iso->tile_width / 2, .y = iso->tile_height / 2}; - const ivec2 y = {.x = -iso->tile_width / 2, .y = iso->tile_height / 2}; - return (CoordSystem){o, x, y}; -} - -/// Get the screen position of the top diamond-corner of the tile at world -/// (x,y). -static ivec2 GetTileScreenOrigin( - const CoordSystem iso_space, int world_x, int world_y) { - const ivec2 vx_offset = ivec2_scale(iso_space.x, world_x); - const ivec2 vy_offset = ivec2_scale(iso_space.y, world_y); - const ivec2 screen_origin = - ivec2_add(iso_space.o, ivec2_add(vx_offset, vy_offset)); - - return screen_origin; -} - -static Pixel alpha_blend(Pixel src, Pixel dst) { - if ((src.a == 255) || (dst.a == 0)) { - return src; - } - const uint16_t one_minus_alpha = 255 - src.a; -#define blend(s, d) \ - (Channel)( \ - (double)((uint16_t)s * (uint16_t)src.a + \ - (uint16_t)d * one_minus_alpha) / \ - 255.0) - return (Pixel){ - .r = blend(src.r, dst.r), - .g = blend(src.g, dst.g), - .b = blend(src.b, dst.b), - .a = src.a}; -} - -/// Draw a rectangle (tile or sprite). -/// -/// The rectangle's top-left corner is mapped to the screen space position given -/// by 'top_left'. -/// -/// The rectangle's pixels are assumed to be arranged in a linear, row-major -/// fashion. -/// -/// If indices are given, then the image is assumed to be colour-paletted, where -/// 'pixels' is the palette and 'indices' the pixel indices. Otherwise, the -/// image is assumed to be in plain RGBA format. -static void draw_rect( - IsoGfx* iso, ivec2 top_left, int rect_width, int rect_height, - const Pixel* pixels, const uint8_t* indices) { - assert(iso); - -#define rect_pixel(X, Y) \ - (indices ? pixels[indices[Y * rect_width + X]] : pixels[Y * rect_width + X]) - - // Rect origin can be outside screen bounds, so we must offset accordingly to - // draw only the visible portion. -#define max(a, b) (a > b ? a : b) - const int px_offset = max(0, -top_left.x); - const int py_offset = max(0, -top_left.y); - - // Rect can exceed screen bounds, so clip along Y and X as we draw. - for (int py = py_offset; - (py < rect_height) && (top_left.y + py < iso->screen_height); ++py) { - const int sy = top_left.y + py; - for (int px = px_offset; - (px < rect_width) && (top_left.x + px < iso->screen_width); ++px) { - const Pixel colour = rect_pixel(px, py); - if (colour.a > 0) { - const int sx = top_left.x + px; - const Pixel dst = screen_xy(iso, sx, sy); - const Pixel final = alpha_blend(colour, dst); - *screen_xy_mut(iso, sx, sy) = final; - } - } - } -} - -/// Draw a tile. -/// -/// 'screen_origin' is the screen coordinates of the top diamond-corner of the -/// tile (the base tile for super tiles). -/// World (0, 0) -> (screen_width / 2, 0). -static void draw_tile(IsoGfx* iso, ivec2 screen_origin, Tile tile) { - assert(iso); - - const TileData* tile_data = mempool_get_block(&iso->tiles, tile); - assert(tile_data); - const Pixel* pixels = tile_xy_const_ref(iso, tile_data, 0, 0); - - // Move from the top diamond-corner to the top-left corner of the tile image. - // For regular tiles, tile height == base tile height, so the y offset is 0. - // For super tiles, move as high up as the height of the tile. - const ivec2 offset = { - -(iso->tile_width / 2), tile_data->height - iso->tile_height}; - const ivec2 top_left = ivec2_add(screen_origin, offset); - - draw_rect(iso, top_left, tile_data->width, tile_data->height, pixels, 0); -} - -static void draw_world(IsoGfx* iso) { - assert(iso); - - const int W = iso->screen_width; - const int H = iso->screen_height; - - memset(iso->screen, 0, W * H * sizeof(Pixel)); - - const CoordSystem iso_space = make_iso_coord_system(iso); - - // TODO: Culling. - // Ex: map the screen corners to tile space to cull. - // Ex: walk in screen space and fetch the tile. - // The tile-centric approach might be more cache-friendly since the - // screen-centric approach would juggle multiple tiles throughout the scan. - for (int wy = 0; wy < iso->world_height; ++wy) { - for (int wx = 0; wx < iso->world_width; ++wx) { - const Tile tile = world_xy(iso, wx, wy); - const ivec2 screen_origin = GetTileScreenOrigin(iso_space, wx, wy); - draw_tile(iso, screen_origin, tile); - } - } -} - -static void draw_sprite( - IsoGfx* iso, ivec2 origin, const SpriteData* sprite, - const SpriteSheetData* sheet) { - assert(iso); - assert(sprite); - assert(sheet); - assert(sprite->animation >= 0); - assert(sprite->animation < sheet->num_rows); - assert(sprite->frame >= 0); - - const SpriteSheetRow* row = get_sprite_sheet_row(sheet, sprite->animation); - const uint8_t* frame = get_sprite_sheet_sprite(sheet, row, sprite->frame); - draw_rect( - iso, origin, sheet->sprite_width, sheet->sprite_height, - sheet->palette.colours, frame); -} - -static void draw_sprites(IsoGfx* iso) { - assert(iso); - - const CoordSystem iso_space = make_iso_coord_system(iso); - - mempool_foreach(&iso->sprites, sprite, { - const SpriteSheetData* sheet = mem_get_chunk(&iso->sheets, sprite->sheet); - assert(sheet); - - const ivec2 screen_origin = - GetTileScreenOrigin(iso_space, sprite->position.x, sprite->position.y); - draw_sprite(iso, screen_origin, sprite, sheet); - }); -} - -void isogfx_render(IsoGfx* iso) { - assert(iso); - draw_world(iso); - draw_sprites(iso); -} - -void isogfx_draw_tile(IsoGfx* iso, int x, int y, Tile tile) { - assert(iso); - assert(x >= 0); - assert(y >= 0); - assert(x < iso->world_width); - assert(y < iso->world_height); - - const CoordSystem iso_space = make_iso_coord_system(iso); - const ivec2 screen_origin = GetTileScreenOrigin(iso_space, x, y); - draw_tile(iso, screen_origin, tile); -} - -bool isogfx_resize(IsoGfx* iso, int screen_width, int screen_height) { - assert(iso); - assert(iso->screen); - - const int current_size = iso->screen_width * iso->screen_height; - const int new_size = screen_width * screen_height; - - if (new_size > current_size) { - Pixel* new_screen = calloc(new_size, sizeof(Pixel)); - if (new_screen) { - free(iso->screen); - iso->screen = new_screen; - } else { - return false; - } - } - iso->screen_width = screen_width; - iso->screen_height = screen_height; - return true; -} - -void isogfx_get_screen_size(const IsoGfx* iso, int* width, int* height) { - assert(iso); - assert(width); - assert(height); - *width = iso->screen_width; - *height = iso->screen_height; -} - -const Pixel* isogfx_get_screen_buffer(const IsoGfx* iso) { - assert(iso); - return iso->screen; -} - -void isogfx_pick_tile( - const IsoGfx* iso, double xcart, double ycart, int* xiso, int* yiso) { - assert(iso); - assert(xiso); - assert(yiso); - - const vec2 xy_iso = cart2iso( - (vec2){.x = xcart, .y = ycart}, iso->tile_width, iso->tile_height, - iso->screen_width); - - if ((0 <= xy_iso.x) && (xy_iso.x < iso->world_width) && (0 <= xy_iso.y) && - (xy_iso.y < iso->world_height)) { - *xiso = (int)xy_iso.x; - *yiso = (int)xy_iso.y; - } else { - *xiso = -1; - *yiso = -1; - } -} diff --git a/gfx-iso/tools/mkasset.py b/gfx-iso/tools/mkasset.py deleted file mode 100644 index 3ca8a1d..0000000 --- a/gfx-iso/tools/mkasset.py +++ /dev/null @@ -1,324 +0,0 @@ -# Converts assets to binary formats (.ts, .tm, .ss) for the engine. -# -# Input file formats: -# - Tiled tile set (.tsx) -# - Tiled tile map (.tmx) -# - Sprite sheets (.jpg, .png, etc), 1 row per animation. -# -# Output file formats: -# - Binary tile set file (.ts) -# - Binary tile map file (.tm) -# - Binary sprite sheet file (.ss) -# -import argparse -import ctypes -import os -from PIL import Image -import sys -from xml.etree import ElementTree - -# Maximum length of path strings in .TS and .TM files. -# Must match the engine's value. -MAX_PATH_LENGTH = 128 - - -def drop_extension(filepath): - return filepath[:filepath.rfind('.')] - - -def to_char_array(string, length): - """Convert a string to a fixed-length ASCII char array. - - The length of str must be at most length-1 so that the resulting string can - be null-terminated. - """ - assert (len(string) < length) - chars = string.encode("ascii") - nulls = ("\0" * (length - len(string))).encode("ascii") - return chars + nulls - - -def convert_tsx(input_filepath, output_filepath): - """Converts a Tiled .tsx tileset file to a .TS tile set file.""" - xml = ElementTree.parse(input_filepath) - root = xml.getroot() - - tile_count = int(root.attrib["tilecount"]) - max_tile_width = int(root.attrib["tilewidth"]) - max_tile_height = int(root.attrib["tileheight"]) - - print(f"Tile count: {tile_count}") - print(f"Max width: {max_tile_width}") - print(f"Max height: {max_tile_height}") - - with open(output_filepath, 'bw') as output: - output.write(ctypes.c_uint16(tile_count)) - output.write(ctypes.c_uint16(max_tile_width)) - output.write(ctypes.c_uint16(max_tile_height)) - - num_tile = 0 - for tile in root: - # Skip the "grid" and other non-tile elements. - if not tile.tag == "tile": - continue - - # Assuming tiles are numbered 0..N. - tile_id = int(tile.attrib["id"]) - assert (tile_id == num_tile) - num_tile += 1 - - image = tile[0] - tile_width = int(image.attrib["width"]) - tile_height = int(image.attrib["height"]) - tile_path = image.attrib["source"] - - output.write(ctypes.c_uint16(tile_width)) - output.write(ctypes.c_uint16(tile_height)) - - with Image.open(tile_path) as im: - bytes = im.convert('RGBA').tobytes() - output.write(bytes) - - -def convert_tmx(input_filepath, output_filepath): - """Converts a Tiled .tmx file to a .TM tile map file.""" - xml = ElementTree.parse(input_filepath) - root = xml.getroot() - - map_width = int(root.attrib["width"]) - map_height = int(root.attrib["height"]) - base_tile_width = int(root.attrib["tilewidth"]) - base_tile_height = int(root.attrib["tileheight"]) - num_layers = 1 - - print(f"Map width: {map_width}") - print(f"Map height: {map_height}") - print(f"Tile width: {base_tile_width}") - print(f"Tile height: {base_tile_height}") - - with open(output_filepath, 'bw') as output: - output.write(ctypes.c_uint16(map_width)) - output.write(ctypes.c_uint16(map_height)) - output.write(ctypes.c_uint16(base_tile_width)) - output.write(ctypes.c_uint16(base_tile_height)) - output.write(ctypes.c_uint16(num_layers)) - - tileset_path = None - - for child in root: - if child.tag == "tileset": - tileset = child - tileset_path = tileset.attrib["source"] - - print(f"Tile set: {tileset_path}") - - tileset_path = tileset_path.replace("tsx", "ts") - elif child.tag == "layer": - layer = child - layer_id = int(layer.attrib["id"]) - layer_width = int(layer.attrib["width"]) - layer_height = int(layer.attrib["height"]) - - print(f"Layer: {layer_id}") - print(f"Width: {layer_width}") - print(f"Height: {layer_height}") - - assert (tileset_path) - output.write(to_char_array(tileset_path, MAX_PATH_LENGTH)) - - # Assume the layer's dimensions matches the map's. - assert (layer_width == map_width) - assert (layer_height == map_height) - - data = layer[0] - # Handle other encodings later. - assert (data.attrib["encoding"] == "csv") - - csv = data.text.strip() - rows = csv.split('\n') - for row in rows: - tile_ids = [x.strip() for x in row.split(',') if x] - for tile_id in tile_ids: - output.write(ctypes.c_uint16(int(tile_id))) - - -def get_num_cols(image, sprite_width): - """Return the number of non-empty columns in the image. - - Assumes no gaps in the columns. - """ - assert (image.width % sprite_width == 0) - num_cols = image.width // sprite_width - - # Start the search from right to left. - for col in reversed(range(1, num_cols)): - left = (col - 1) * sprite_width - right = col * sprite_width - rect = image.crop((left, 0, right, image.height)) - min_max = rect.getextrema() - for (channel_min, channel_max) in min_max: - if channel_min != 0 or channel_max != 0: - # 'col' is the rightmost non-empty column. - # Assuming no gaps, col+1 is the number of non-empty columns. - return col + 1 - - return 0 - - -def get_sprite_sheet_rows(im, sprite_width, sprite_height): - """Gets the individual rows of a sprite sheet. - - The input sprite sheet can have any number of rows. - - Returns a list of lists [[sprite]], one inner list for the columns in each - row. - """ - # Sprite sheet's width and height must be integer multiples of the - # sprite's width and height. - assert (im.width % sprite_width == 0) - assert (im.height % sprite_height == 0) - - num_rows = im.height // sprite_height - - rows = [] - for row in range(num_rows): - # Get the number of columns. - upper = row * sprite_height - lower = (row + 1) * sprite_height - whole_row = im.crop((0, upper, im.width, lower)) - num_cols = get_num_cols(whole_row, sprite_width) - assert (num_cols > 0) - - # Crop the row into N columns. - cols = [] - for i in range(num_cols): - left = i * sprite_width - right = (i + 1) * sprite_width - sprite = im.crop((left, upper, right, lower)) - cols.append(sprite) - - assert (len(cols) == num_cols) - rows.append(cols) - - return rows - - -def make_image_from_rows(rows, sprite_width, sprite_height): - """Concatenate the rows into a single RGBA image.""" - im_width = sprite_width * max(len(row) for row in rows) - im_height = len(rows) * sprite_height - im = Image.new('RGBA', (im_width, im_height)) - y = 0 - for row in rows: - x = 0 - for sprite in row: - im.paste(sprite.convert('RGBA'), (x, y)) - x += sprite_width - y += sprite_height - return im - - -def convert_sprite_sheet(input_file_paths, sprite_width, sprite_height, - output_filepath): - """Converts a set of sprite sheet images into a binary sprite sheet file - (.ss). - - The input sprite sheets can have any number of rows, one row per animation. - All rows from all sprite sheets are concatenated in the output file. - - The sprite's width and height is assumed constant throughout the input - sprite sheets. - """ - rows = [] - for input_filepath in input_file_paths: - with Image.open(input_filepath) as sprite_sheet: - rows.extend( - get_sprite_sheet_rows(sprite_sheet, sprite_width, - sprite_height)) - - im = make_image_from_rows(rows, sprite_width, sprite_height) - im = im.convert(mode="P", palette=Image.ADAPTIVE, colors=256) - - # The sprite data in 'rows' is no longer needed. - # Keep just the number of columns per row. - rows = [len(row) for row in rows] - - with open(output_filepath, 'bw') as output: - output.write(ctypes.c_uint16(sprite_width)) - output.write(ctypes.c_uint16(sprite_height)) - output.write(ctypes.c_uint16(len(rows))) - - # Write palette. - # getpalette() returns 256 colors, but the palette might use less than - # that. getcolors() returns the number of unique colors. - # getpalette() also returns a flattened list, which is why we must *4. - num_colours = len(im.getcolors()) - colours = im.getpalette(rawmode="RGBA")[:4 * num_colours] - palette = [] - for i in range(0, 4 * num_colours, 4): - palette.append((colours[i], colours[i + 1], colours[i + 2], - colours[i + 3])) - - output.write(ctypes.c_uint16(len(palette))) - output.write(bytearray(colours)) - - print(f"Sprite width: {sprite_width}") - print(f"Sprite height: {sprite_height}") - print(f"Rows: {len(rows)}") - print(f"Colours: {len(palette)}") - - # print("Palette") - # for i, colour in enumerate(palette): - # print(f"{i}: {colour}") - - for row, num_columns in enumerate(rows): - output.write(ctypes.c_uint16(num_columns)) - upper = row * sprite_height - lower = (row + 1) * sprite_height - for col in range(num_columns): - left = col * sprite_width - right = (col + 1) * sprite_width - sprite = im.crop((left, upper, right, lower)) - sprite_bytes = sprite.tobytes() - - assert (len(sprite_bytes) == sprite_width * sprite_height) - output.write(sprite_bytes) - - # if (row == 0) and (col == 0): - # print(f"Sprite: ({len(sprite_bytes)})") - # print(list(sprite_bytes)) - # sprite.save("out.png") - - -def main(): - parser = argparse.ArgumentParser() - parser.add_argument("input", - nargs="+", - help="Input file (.tsx, .tmx) or path regex (sprite sheets)") - parser.add_argument("--width", type=int, help="Sprite width in pixels") - parser.add_argument("--height", type=int, help="Sprite height in pixels") - parser.add_argument("--out", help="Output file (sprite sheets)") - args = parser.parse_args() - - if ".tsx" in args.input: - output_filepath_no_ext = drop_extension(args.input) - output_filepath = output_filepath_no_ext + ".ts" - convert_tsx(args.input, output_filepath) - elif ".tmx" in args.input: - output_filepath_no_ext = drop_extension(args.input) - output_filepath = output_filepath_no_ext + ".tm" - convert_tmx(args.input, output_filepath) - else: - # Sprite sheets. - if not args.width or not args.height: - print("Sprite width and height must be given") - return 1 - output_filepath = args.out if args.out else "out.ss" - convert_sprite_sheet(args.input, args.width, args.height, - output_filepath) - - return 0 - - -if __name__ == '__main__': - sys.exit(main()) diff --git a/gfx/CMakeLists.txt b/gfx/CMakeLists.txt deleted file mode 100644 index 7d629dc..0000000 --- a/gfx/CMakeLists.txt +++ /dev/null @@ -1,89 +0,0 @@ -cmake_minimum_required(VERSION 3.0) - -include(cmake/shader.txt) - -add_subdirectory(contrib/cgltf) -add_subdirectory(contrib/cgltf-tangents) -add_subdirectory(contrib/stb) - -project(gfx) - -add_shader_library(shaders - shaders/brdf_integration_map.frag - shaders/cook_torrance.frag - shaders/cook_torrance.vert - shaders/cubemap_filtering.vert - shaders/debug3d.frag - shaders/debug3d.vert - shaders/immediate_mode.frag - shaders/immediate_mode.vert - shaders/irradiance_map.frag - shaders/prefiltered_environment_map.frag - shaders/quad.vert - shaders/skyquad.frag - shaders/skyquad.vert - shaders/view_normal_mapped_normals.frag - shaders/view_normal_mapped_normals.vert - shaders/view_normals.frag - shaders/view_normals.vert - shaders/view_tangents.frag - shaders/view_tangents.vert - shaders/view_texture.frag - shaders/view_texture.vert) - -add_library(gfx SHARED - src/asset/asset_cache.c - src/asset/model.c - src/asset/texture.c - src/core/buffer.c - src/core/core.c - src/core/framebuffer.c - src/core/geometry.c - src/core/renderbuffer.c - src/core/shader_program.c - src/core/shader.c - src/core/texture.c - src/renderer/imm_renderer.c - src/renderer/renderer.c - src/scene/animation.c - src/scene/camera.c - src/scene/light.c - src/scene/material.c - src/scene/mesh.c - src/scene/model.c - src/scene/node.c - src/scene/object.c - src/scene/scene.c - src/scene/scene_memory.c - src/gfx.c - src/util/geometry.c - src/util/ibl.c - src/util/shader.c - src/util/skyquad.c) - -target_include_directories(gfx PUBLIC - include) - -target_include_directories(gfx PRIVATE - src) - -target_compile_options(gfx PRIVATE -std=gnu11 -Wall -Wextra -Wpedantic) - -target_link_libraries(gfx PUBLIC - cstring - math) - -target_link_libraries(gfx PRIVATE - cassert - cgltf - cgltf-tangents - error - gfx-app - log - mempool - shaders - stb - # System libraries. - GL - # Required to initialize GLAD. - -ldl) diff --git a/gfx/README.md b/gfx/README.md deleted file mode 100644 index f0b103d..0000000 --- a/gfx/README.md +++ /dev/null @@ -1,144 +0,0 @@ -# GFX - 3D Rendering Library - -A portable 3D rendering library with minimal dependencies written for -educational purposes. - -## Guiding Principles - -- Provide enough functionality for graphics applications and indie games. -- Provide a minimal interface, physically hide the implementation. Make bindings - easy. -- Establish a clean separation from the render backend and the rest of the - library to allow for additional rendering backends (e.g. Vulkan). -- Strive for a minimal set of dependencies, all of which should ship and compile - with the graphics library for ease of use. -- Rely on dynamic allocation as little as possible. Isolate dynamic allocation - to where it is strictly needed. - -## Design - -### Gfx - -The `Gfx` object represents the graphics subsystem and is at the center of the -library's high-level API. The `Gfx` object exposes a `Render` backend and a -`Renderer` and allows the caller to create `Scene`s. - -### Render Backend - -The `Render` backend is a thin abstraction layer over low-level graphics APIs -like OpenGL or Vulkan. It holds GPU resources such as geometry, textures, -shaders, etc, and exposes functions to manipulate them. - -Currently there is only one implementation of the `Render` backend based on -OpenGL. - -#### Ownership - -The `Render` backend owns all rendering resources: buffers, geometries, -textures, shaders, etc. Even resources that point to other resources do not own -those other resources (geometries pointing to buffers). - -There is no ownership tracking in the render backend. It is up to the client to -manage resource lifetime. - -### Scene - -A `Scene` encapsulates a scene graph. A scene graph contains the elements that -make up a scene: nodes, cameras, lights, objects, etc. The current scene graph -implementation includes: - -- Camera -- Light -- Material -- Mesh -- Node -- Object -- Scene - -#### Hierarchy and Parenting - -Scene graphs typically expose functions on nodes to add/remove objects, cameras, -lights, etc. This implementation forces the hierarchy to be a strict tree and -not a more general DAG. Given this, and to avoid confusion, we instead expose -functions to set the parent node of an object/camera/light. If we exposed the -former, the API could create the illusion that the hierarchy can be a DAG. - -The strict tree hierarchy should not be that restrictive in practice. Even the -glTF 2.0 spec [enforces this](https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#nodes-and-hierarchy): - -> *For Version 2.0 conformance, the glTF node hierarchy is not a directed -> acyclic graph (DAG) or scene graph, but a disjoint union of strict trees. That -> is, no node may be a direct descendant of more than one node. This restriction -> is meant to simplify implementation and facilitate conformance.* - -#### Instancing - -Two use cases for instancing seem to be: - -1. Creating N identical clones, but each with a unique transform. (Ex: N -animated characters animated in unison but located in different locations.) -2. Creating N copies of a sub-tree, each now being their own unique tree. (Ex: -The same N animated characters, but each of them now being animated separately.) - -Some scene graphs -([Panda3D](https://docs.panda3d.org/1.10/python/programming/scene-graph/instancing)) -allow two or more nodes to point to the same child, or, in other words, a node -to have multiple parents. This turns the scene graph into a DAG and adds a -number of complications for us: - -1. Shared ownership of children. We would now need some sort of ref counting or -deferred GC to delete nodes and their subtrees. -2. Nodes no longer have a unique parent. -3. Given a node, we can no longer determine its location (which parent link do -you follow?), or any attribute that is derived from its parent(s). - -In our case, we stick to strict tree hierarchies. - -Use case (1), N identical clones with unique transforms, is not a problem for -us. This is because the bulk of the data -- geometry buffers, etc. -- is stored -in the render backend anyway. So creating a full copy of the node does not -present a significant overhead since we need a unique transform for each of the -clones anyway. - -Use case (2) does present a bit more overhead and we currently do not handle it. -This could be handled in the future by special-casing a node such as -`InstanceNode` that has one child subtree and N transforms (or other -attributes), one for each unique instance of that child subtree. - -Therefore, to visit the use cases again: - -1. N character clones animated in unison in different locations -> future - `InstanceNode`. -2. N unique character copies animated on their own -> copy the character subtree - (N unique skeletons; shared mesh data and textures stored in the render - backend.) - -#### Reading - -[Panda3D Scene Graph](https://docs.panda3d.org/1.10/python/programming/scene-graph/index) - -[Pixar's USD](https://graphics.pixar.com/usd/release/intro.html) - -### Renderer - -The `Renderer` takes a `Render` backend and a `Scene` and renders the scene. -Currently, only a forward renderer is provided, but additional renderers can be -implemented in the future. - -### Util - -Code under `util/` provides functionality that need not be in the core part -of the library (Gfx, render backend, scene or renderer). This includes functions -to compute irradiance maps, create procedural geometry, etc. - -## Ideas for Future Work - -- Render graphs to allow for custom multi-pass rendering algorithms. - -## Build (Ubuntu) - -``` -sudo apt install libbsd-dev libgl-dev libglfw3-dev zlib1g-dev -``` - -TODO: Add these libraries to `contrib/`. diff --git a/gfx/bin/txt2c.py b/gfx/bin/txt2c.py deleted file mode 100755 index 1d8ff70..0000000 --- a/gfx/bin/txt2c.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/python3 - -import fileinput -import os -import sys - - -def escape_quotes(string): - return string.replace("\"", '\\"') - - -def escape_newlines(string): - return string.replace("\n", "\\n") - - -def quote(string): - return "\"" + string + "\"" - - -def main(): - if len(sys.argv) < 3: - print("Usage: {} [text files...] [C files...]".format(sys.argv[0])) - return 1 - - files = sys.argv[1:] - assert(len(files) % 2 == 0) - N = int(len(files) / 2) - text_files = files[:N] - c_files = files[N:] - - for i in range(len(text_files)): - text_file = text_files[i] - c_file = c_files[i] - h_file = c_file.replace(".c", ".h") - variable_name = os.path.basename(text_file).replace(".", "_") - - os.makedirs(os.path.join(".", os.path.dirname(c_file)), exist_ok=True) - - # Create the C file. - with open(c_file, 'w') as out_file: - out_file.write("const char {}[] =\n".format(variable_name)) - pad = " " - with open(text_file, 'r') as in_file: - for line in in_file.readlines(): - line = escape_quotes(line) - line = escape_newlines(line) - line = quote(line) - line = pad + line + "\n" - out_file.write(line) - out_file.write(pad + "\"\";") - - # Create the header file. - with open(h_file, 'w') as out_file: - out_file.write("#pragma once\n") - out_file.write("\n") - out_file.write("extern const char {}[];".format(variable_name)) - - return 0 - - -if __name__ == '__main__': - sys.exit(main()) diff --git a/gfx/cmake/shader.txt b/gfx/cmake/shader.txt deleted file mode 100644 index 8273f4d..0000000 --- a/gfx/cmake/shader.txt +++ /dev/null @@ -1,5 +0,0 @@ -include(cmake/txt2c.txt) - -macro(add_shader_library) - txt2c(${ARGN}) -endmacro() diff --git a/gfx/cmake/txt2c.txt b/gfx/cmake/txt2c.txt deleted file mode 100644 index 0cb11a9..0000000 --- a/gfx/cmake/txt2c.txt +++ /dev/null @@ -1,44 +0,0 @@ -function(txt2c target) - set(BUILD_DIR "${CMAKE_CURRENT_BINARY_DIR}/${target}") - file(MAKE_DIRECTORY ${BUILD_DIR}) - message(${BUILD_DIR}) - - set(TEXT_FILES) - set(SOURCE_FILES) - set(INCLUDE_DIRECTORIES) - foreach(filepath IN ITEMS ${ARGN}) - set(textfile "${CMAKE_CURRENT_SOURCE_DIR}/${filepath}") - list(APPEND TEXT_FILES ${textfile}) - - set(srcfile "${BUILD_DIR}/${filepath}.c") - list(APPEND SOURCE_FILES ${srcfile}) - - get_filename_component(include_dir ${srcfile} DIRECTORY) - list(APPEND INCLUDE_DIRECTORIES ${include_dir}) - endforeach() - - foreach(filepath IN ITEMS ${TEXT_FILES}) - message(${filepath}) - endforeach() - - foreach(filepath IN ITEMS ${SOURCE_FILES}) - message(${filepath}) - endforeach() - - foreach(filepath IN ITEMS ${INCLUDE_DIRECTORIES}) - message(${filepath}) - endforeach() - - add_custom_command(OUTPUT ${SOURCE_FILES} - COMMAND "${PROJECT_SOURCE_DIR}/bin/txt2c.py" ${TEXT_FILES} ${SOURCE_FILES} - WORKING_DIRECTORY ${BUILD_DIR} - DEPENDS ${ARGN} - COMMENT "Generating ${target}") - - add_library(${target} - ${SOURCE_FILES}) - - target_include_directories(${target} PUBLIC - ${BUILD_DIR} - ${INCLUDE_DIRECTORIES}) -endfunction() diff --git a/gfx/contrib/cgltf-tangents/CMakeLists.txt b/gfx/contrib/cgltf-tangents/CMakeLists.txt deleted file mode 100644 index 2c0771e..0000000 --- a/gfx/contrib/cgltf-tangents/CMakeLists.txt +++ /dev/null @@ -1,13 +0,0 @@ -cmake_minimum_required(VERSION 3.0) - -project(cgltf-tangents) - -add_library(cgltf-tangents - cgltf_tangents.c - MikkTSpace/mikktspace.c) - -target_include_directories(cgltf-tangents PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR}) - -target_link_libraries(cgltf-tangents PUBLIC - cgltf) diff --git a/gfx/contrib/cgltf-tangents/LICENSE b/gfx/contrib/cgltf-tangents/LICENSE deleted file mode 100644 index 7796e37..0000000 --- a/gfx/contrib/cgltf-tangents/LICENSE +++ /dev/null @@ -1,79 +0,0 @@ -This project has two third-party dependencies: -- MikkTSpace -- cgltf - -The license for this project and its dependencies are included below. - --------------------------------------------------------------------------------- -cgltf-tangents --------------------------------------------------------------------------------- - -Copyright 2022 Marc Sunet - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this -list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, -this list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - --------------------------------------------------------------------------------- -MikkTSpace --------------------------------------------------------------------------------- - -Copyright (C) 2011 by Morten S. Mikkelsen - -This software is provided 'as-is', without any express or implied -warranty. In no event will the authors be held liable for any damages -arising from the use of this software. - -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it -freely, subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - -2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - -3. This notice may not be removed or altered from any source distribution. - --------------------------------------------------------------------------------- -cgltf --------------------------------------------------------------------------------- - -Copyright (c) 2018-2021 Johannes Kuhlmann - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/gfx/contrib/cgltf-tangents/MikkTSpace/README.md b/gfx/contrib/cgltf-tangents/MikkTSpace/README.md deleted file mode 100644 index 9fda155..0000000 --- a/gfx/contrib/cgltf-tangents/MikkTSpace/README.md +++ /dev/null @@ -1,4 +0,0 @@ -# MikkTSpace -A common standard for tangent space used in baking tools to produce normal maps. - -More information can be found at http://www.mikktspace.com/. diff --git a/gfx/contrib/cgltf-tangents/MikkTSpace/mikktspace.c b/gfx/contrib/cgltf-tangents/MikkTSpace/mikktspace.c deleted file mode 100644 index 0342ae0..0000000 --- a/gfx/contrib/cgltf-tangents/MikkTSpace/mikktspace.c +++ /dev/null @@ -1,1899 +0,0 @@ -/** \file mikktspace/mikktspace.c - * \ingroup mikktspace - */ -/** - * Copyright (C) 2011 by Morten S. Mikkelsen - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any damages - * arising from the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software - * in a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - */ - -#include -#include -#include -#include -#include -#include - -#include "mikktspace.h" - -#define TFALSE 0 -#define TTRUE 1 - -#ifndef M_PI -#define M_PI 3.1415926535897932384626433832795 -#endif - -#define INTERNAL_RND_SORT_SEED 39871946 - -// internal structure -typedef struct { - float x, y, z; -} SVec3; - -static tbool veq( const SVec3 v1, const SVec3 v2 ) -{ - return (v1.x == v2.x) && (v1.y == v2.y) && (v1.z == v2.z); -} - -static SVec3 vadd( const SVec3 v1, const SVec3 v2 ) -{ - SVec3 vRes; - - vRes.x = v1.x + v2.x; - vRes.y = v1.y + v2.y; - vRes.z = v1.z + v2.z; - - return vRes; -} - - -static SVec3 vsub( const SVec3 v1, const SVec3 v2 ) -{ - SVec3 vRes; - - vRes.x = v1.x - v2.x; - vRes.y = v1.y - v2.y; - vRes.z = v1.z - v2.z; - - return vRes; -} - -static SVec3 vscale(const float fS, const SVec3 v) -{ - SVec3 vRes; - - vRes.x = fS * v.x; - vRes.y = fS * v.y; - vRes.z = fS * v.z; - - return vRes; -} - -static float LengthSquared( const SVec3 v ) -{ - return v.x*v.x + v.y*v.y + v.z*v.z; -} - -static float Length( const SVec3 v ) -{ - return sqrtf(LengthSquared(v)); -} - -static SVec3 Normalize( const SVec3 v ) -{ - return vscale(1 / Length(v), v); -} - -static float vdot( const SVec3 v1, const SVec3 v2) -{ - return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z; -} - - -static tbool NotZero(const float fX) -{ - // could possibly use FLT_EPSILON instead - return fabsf(fX) > FLT_MIN; -} - -static tbool VNotZero(const SVec3 v) -{ - // might change this to an epsilon based test - return NotZero(v.x) || NotZero(v.y) || NotZero(v.z); -} - - - -typedef struct { - int iNrFaces; - int * pTriMembers; -} SSubGroup; - -typedef struct { - int iNrFaces; - int * pFaceIndices; - int iVertexRepresentitive; - tbool bOrientPreservering; -} SGroup; - -// -#define MARK_DEGENERATE 1 -#define QUAD_ONE_DEGEN_TRI 2 -#define GROUP_WITH_ANY 4 -#define ORIENT_PRESERVING 8 - - - -typedef struct { - int FaceNeighbors[3]; - SGroup * AssignedGroup[3]; - - // normalized first order face derivatives - SVec3 vOs, vOt; - float fMagS, fMagT; // original magnitudes - - // determines if the current and the next triangle are a quad. - int iOrgFaceNumber; - int iFlag, iTSpacesOffs; - unsigned char vert_num[4]; -} STriInfo; - -typedef struct { - SVec3 vOs; - float fMagS; - SVec3 vOt; - float fMagT; - int iCounter; // this is to average back into quads. - tbool bOrient; -} STSpace; - -static int GenerateInitialVerticesIndexList(STriInfo pTriInfos[], int piTriList_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn); -static void GenerateSharedVerticesIndexList(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn); -static void InitTriInfo(STriInfo pTriInfos[], const int piTriListIn[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn); -static int Build4RuleGroups(STriInfo pTriInfos[], SGroup pGroups[], int piGroupTrianglesBuffer[], const int piTriListIn[], const int iNrTrianglesIn); -static tbool GenerateTSpaces(STSpace psTspace[], const STriInfo pTriInfos[], const SGroup pGroups[], - const int iNrActiveGroups, const int piTriListIn[], const float fThresCos, - const SMikkTSpaceContext * pContext); - -static int MakeIndex(const int iFace, const int iVert) -{ - assert(iVert>=0 && iVert<4 && iFace>=0); - return (iFace<<2) | (iVert&0x3); -} - -static void IndexToData(int * piFace, int * piVert, const int iIndexIn) -{ - piVert[0] = iIndexIn&0x3; - piFace[0] = iIndexIn>>2; -} - -static STSpace AvgTSpace(const STSpace * pTS0, const STSpace * pTS1) -{ - STSpace ts_res; - - // this if is important. Due to floating point precision - // averaging when ts0==ts1 will cause a slight difference - // which results in tangent space splits later on - if (pTS0->fMagS==pTS1->fMagS && pTS0->fMagT==pTS1->fMagT && - veq(pTS0->vOs,pTS1->vOs) && veq(pTS0->vOt, pTS1->vOt)) - { - ts_res.fMagS = pTS0->fMagS; - ts_res.fMagT = pTS0->fMagT; - ts_res.vOs = pTS0->vOs; - ts_res.vOt = pTS0->vOt; - } - else - { - ts_res.fMagS = 0.5f*(pTS0->fMagS+pTS1->fMagS); - ts_res.fMagT = 0.5f*(pTS0->fMagT+pTS1->fMagT); - ts_res.vOs = vadd(pTS0->vOs,pTS1->vOs); - ts_res.vOt = vadd(pTS0->vOt,pTS1->vOt); - if ( VNotZero(ts_res.vOs) ) ts_res.vOs = Normalize(ts_res.vOs); - if ( VNotZero(ts_res.vOt) ) ts_res.vOt = Normalize(ts_res.vOt); - } - - return ts_res; -} - - - -static SVec3 GetPosition(const SMikkTSpaceContext * pContext, const int index); -static SVec3 GetNormal(const SMikkTSpaceContext * pContext, const int index); -static SVec3 GetTexCoord(const SMikkTSpaceContext * pContext, const int index); - - -// degen triangles -static void DegenPrologue(STriInfo pTriInfos[], int piTriList_out[], const int iNrTrianglesIn, const int iTotTris); -static void DegenEpilogue(STSpace psTspace[], STriInfo pTriInfos[], int piTriListIn[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn, const int iTotTris); - - -tbool genTangSpaceDefault(const SMikkTSpaceContext * pContext) -{ - return genTangSpace(pContext, 180.0f); -} - -tbool genTangSpace(const SMikkTSpaceContext * pContext, const float fAngularThreshold) -{ - // count nr_triangles - int * piTriListIn = NULL, * piGroupTrianglesBuffer = NULL; - STriInfo * pTriInfos = NULL; - SGroup * pGroups = NULL; - STSpace * psTspace = NULL; - int iNrTrianglesIn = 0, f=0, t=0, i=0; - int iNrTSPaces = 0, iTotTris = 0, iDegenTriangles = 0, iNrMaxGroups = 0; - int iNrActiveGroups = 0, index = 0; - const int iNrFaces = pContext->m_pInterface->m_getNumFaces(pContext); - tbool bRes = TFALSE; - const float fThresCos = (float) cos((fAngularThreshold*(float)M_PI)/180.0f); - - // verify all call-backs have been set - if ( pContext->m_pInterface->m_getNumFaces==NULL || - pContext->m_pInterface->m_getNumVerticesOfFace==NULL || - pContext->m_pInterface->m_getPosition==NULL || - pContext->m_pInterface->m_getNormal==NULL || - pContext->m_pInterface->m_getTexCoord==NULL ) - return TFALSE; - - // count triangles on supported faces - for (f=0; fm_pInterface->m_getNumVerticesOfFace(pContext, f); - if (verts==3) ++iNrTrianglesIn; - else if (verts==4) iNrTrianglesIn += 2; - } - if (iNrTrianglesIn<=0) return TFALSE; - - // allocate memory for an index list - piTriListIn = (int *) malloc(sizeof(int)*3*iNrTrianglesIn); - pTriInfos = (STriInfo *) malloc(sizeof(STriInfo)*iNrTrianglesIn); - if (piTriListIn==NULL || pTriInfos==NULL) - { - if (piTriListIn!=NULL) free(piTriListIn); - if (pTriInfos!=NULL) free(pTriInfos); - return TFALSE; - } - - // make an initial triangle --> face index list - iNrTSPaces = GenerateInitialVerticesIndexList(pTriInfos, piTriListIn, pContext, iNrTrianglesIn); - - // make a welded index list of identical positions and attributes (pos, norm, texc) - //printf("gen welded index list begin\n"); - GenerateSharedVerticesIndexList(piTriListIn, pContext, iNrTrianglesIn); - //printf("gen welded index list end\n"); - - // Mark all degenerate triangles - iTotTris = iNrTrianglesIn; - iDegenTriangles = 0; - for (t=0; tm_pInterface->m_getNumVerticesOfFace(pContext, f); - if (verts!=3 && verts!=4) continue; - - - // I've decided to let degenerate triangles and group-with-anythings - // vary between left/right hand coordinate systems at the vertices. - // All healthy triangles on the other hand are built to always be either or. - - /*// force the coordinate system orientation to be uniform for every face. - // (this is already the case for good triangles but not for - // degenerate ones and those with bGroupWithAnything==true) - bool bOrient = psTspace[index].bOrient; - if (psTspace[index].iCounter == 0) // tspace was not derived from a group - { - // look for a space created in GenerateTSpaces() by iCounter>0 - bool bNotFound = true; - int i=1; - while (i 0) bNotFound=false; - else ++i; - } - if (!bNotFound) bOrient = psTspace[index+i].bOrient; - }*/ - - // set data - for (i=0; ivOs.x, pTSpace->vOs.y, pTSpace->vOs.z}; - float bitang[] = {pTSpace->vOt.x, pTSpace->vOt.y, pTSpace->vOt.z}; - if (pContext->m_pInterface->m_setTSpace!=NULL) - pContext->m_pInterface->m_setTSpace(pContext, tang, bitang, pTSpace->fMagS, pTSpace->fMagT, pTSpace->bOrient, f, i); - if (pContext->m_pInterface->m_setTSpaceBasic!=NULL) - pContext->m_pInterface->m_setTSpaceBasic(pContext, tang, pTSpace->bOrient==TTRUE ? 1.0f : (-1.0f), f, i); - - ++index; - } - } - - free(psTspace); - - - return TTRUE; -} - -/////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -typedef struct { - float vert[3]; - int index; -} STmpVert; - -static const int g_iCells = 2048; - -#ifdef _MSC_VER -# define NOINLINE __declspec(noinline) -#else -# define NOINLINE __attribute__ ((noinline)) -#endif - -// it is IMPORTANT that this function is called to evaluate the hash since -// inlining could potentially reorder instructions and generate different -// results for the same effective input value fVal. -static NOINLINE int FindGridCell(const float fMin, const float fMax, const float fVal) -{ - const float fIndex = g_iCells * ((fVal-fMin)/(fMax-fMin)); - const int iIndex = (int)fIndex; - return iIndex < g_iCells ? (iIndex >= 0 ? iIndex : 0) : (g_iCells - 1); -} - -static void MergeVertsFast(int piTriList_in_and_out[], STmpVert pTmpVert[], const SMikkTSpaceContext * pContext, const int iL_in, const int iR_in); -static void MergeVertsSlow(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int pTable[], const int iEntries); -static void GenerateSharedVerticesIndexListSlow(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn); - -static void GenerateSharedVerticesIndexList(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn) -{ - - // Generate bounding box - int * piHashTable=NULL, * piHashCount=NULL, * piHashOffsets=NULL, * piHashCount2=NULL; - STmpVert * pTmpVert = NULL; - int i=0, iChannel=0, k=0, e=0; - int iMaxCount=0; - SVec3 vMin = GetPosition(pContext, 0), vMax = vMin, vDim; - float fMin, fMax; - for (i=1; i<(iNrTrianglesIn*3); i++) - { - const int index = piTriList_in_and_out[i]; - - const SVec3 vP = GetPosition(pContext, index); - if (vMin.x > vP.x) vMin.x = vP.x; - else if (vMax.x < vP.x) vMax.x = vP.x; - if (vMin.y > vP.y) vMin.y = vP.y; - else if (vMax.y < vP.y) vMax.y = vP.y; - if (vMin.z > vP.z) vMin.z = vP.z; - else if (vMax.z < vP.z) vMax.z = vP.z; - } - - vDim = vsub(vMax,vMin); - iChannel = 0; - fMin = vMin.x; fMax=vMax.x; - if (vDim.y>vDim.x && vDim.y>vDim.z) - { - iChannel=1; - fMin = vMin.y; - fMax = vMax.y; - } - else if (vDim.z>vDim.x) - { - iChannel=2; - fMin = vMin.z; - fMax = vMax.z; - } - - // make allocations - piHashTable = (int *) malloc(sizeof(int)*iNrTrianglesIn*3); - piHashCount = (int *) malloc(sizeof(int)*g_iCells); - piHashOffsets = (int *) malloc(sizeof(int)*g_iCells); - piHashCount2 = (int *) malloc(sizeof(int)*g_iCells); - - if (piHashTable==NULL || piHashCount==NULL || piHashOffsets==NULL || piHashCount2==NULL) - { - if (piHashTable!=NULL) free(piHashTable); - if (piHashCount!=NULL) free(piHashCount); - if (piHashOffsets!=NULL) free(piHashOffsets); - if (piHashCount2!=NULL) free(piHashCount2); - GenerateSharedVerticesIndexListSlow(piTriList_in_and_out, pContext, iNrTrianglesIn); - return; - } - memset(piHashCount, 0, sizeof(int)*g_iCells); - memset(piHashCount2, 0, sizeof(int)*g_iCells); - - // count amount of elements in each cell unit - for (i=0; i<(iNrTrianglesIn*3); i++) - { - const int index = piTriList_in_and_out[i]; - const SVec3 vP = GetPosition(pContext, index); - const float fVal = iChannel==0 ? vP.x : (iChannel==1 ? vP.y : vP.z); - const int iCell = FindGridCell(fMin, fMax, fVal); - ++piHashCount[iCell]; - } - - // evaluate start index of each cell. - piHashOffsets[0]=0; - for (k=1; kpTmpVert[l].vert[c]) fvMin[c]=pTmpVert[l].vert[c]; - if (fvMax[c]dx && dy>dz) channel=1; - else if (dz>dx) channel=2; - - fSep = 0.5f*(fvMax[channel]+fvMin[channel]); - - // stop if all vertices are NaNs - if (!isfinite(fSep)) - return; - - // terminate recursion when the separation/average value - // is no longer strictly between fMin and fMax values. - if (fSep>=fvMax[channel] || fSep<=fvMin[channel]) - { - // complete the weld - for (l=iL_in; l<=iR_in; l++) - { - int i = pTmpVert[l].index; - const int index = piTriList_in_and_out[i]; - const SVec3 vP = GetPosition(pContext, index); - const SVec3 vN = GetNormal(pContext, index); - const SVec3 vT = GetTexCoord(pContext, index); - - tbool bNotFound = TTRUE; - int l2=iL_in, i2rec=-1; - while (l20); // at least 2 entries - - // separate (by fSep) all points between iL_in and iR_in in pTmpVert[] - while (iL < iR) - { - tbool bReadyLeftSwap = TFALSE, bReadyRightSwap = TFALSE; - while ((!bReadyLeftSwap) && iL=iL_in && iL<=iR_in); - bReadyLeftSwap = !(pTmpVert[iL].vert[channel]=iL_in && iR<=iR_in); - bReadyRightSwap = pTmpVert[iR].vert[channel]m_pInterface->m_getNumFaces(pContext); f++) - { - const int verts = pContext->m_pInterface->m_getNumVerticesOfFace(pContext, f); - if (verts!=3 && verts!=4) continue; - - pTriInfos[iDstTriIndex].iOrgFaceNumber = f; - pTriInfos[iDstTriIndex].iTSpacesOffs = iTSpacesOffs; - - if (verts==3) - { - unsigned char * pVerts = pTriInfos[iDstTriIndex].vert_num; - pVerts[0]=0; pVerts[1]=1; pVerts[2]=2; - piTriList_out[iDstTriIndex*3+0] = MakeIndex(f, 0); - piTriList_out[iDstTriIndex*3+1] = MakeIndex(f, 1); - piTriList_out[iDstTriIndex*3+2] = MakeIndex(f, 2); - ++iDstTriIndex; // next - } - else - { - { - pTriInfos[iDstTriIndex+1].iOrgFaceNumber = f; - pTriInfos[iDstTriIndex+1].iTSpacesOffs = iTSpacesOffs; - } - - { - // need an order independent way to evaluate - // tspace on quads. This is done by splitting - // along the shortest diagonal. - const int i0 = MakeIndex(f, 0); - const int i1 = MakeIndex(f, 1); - const int i2 = MakeIndex(f, 2); - const int i3 = MakeIndex(f, 3); - const SVec3 T0 = GetTexCoord(pContext, i0); - const SVec3 T1 = GetTexCoord(pContext, i1); - const SVec3 T2 = GetTexCoord(pContext, i2); - const SVec3 T3 = GetTexCoord(pContext, i3); - const float distSQ_02 = LengthSquared(vsub(T2,T0)); - const float distSQ_13 = LengthSquared(vsub(T3,T1)); - tbool bQuadDiagIs_02; - if (distSQ_02m_pInterface->m_getPosition(pContext, pos, iF, iI); - res.x=pos[0]; res.y=pos[1]; res.z=pos[2]; - return res; -} - -static SVec3 GetNormal(const SMikkTSpaceContext * pContext, const int index) -{ - int iF, iI; - SVec3 res; float norm[3]; - IndexToData(&iF, &iI, index); - pContext->m_pInterface->m_getNormal(pContext, norm, iF, iI); - res.x=norm[0]; res.y=norm[1]; res.z=norm[2]; - return res; -} - -static SVec3 GetTexCoord(const SMikkTSpaceContext * pContext, const int index) -{ - int iF, iI; - SVec3 res; float texc[2]; - IndexToData(&iF, &iI, index); - pContext->m_pInterface->m_getTexCoord(pContext, texc, iF, iI); - res.x=texc[0]; res.y=texc[1]; res.z=1.0f; - return res; -} - -///////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////// - -typedef union { - struct - { - int i0, i1, f; - }; - int array[3]; -} SEdge; - -static void BuildNeighborsFast(STriInfo pTriInfos[], SEdge * pEdges, const int piTriListIn[], const int iNrTrianglesIn); -static void BuildNeighborsSlow(STriInfo pTriInfos[], const int piTriListIn[], const int iNrTrianglesIn); - -// returns the texture area times 2 -static float CalcTexArea(const SMikkTSpaceContext * pContext, const int indices[]) -{ - const SVec3 t1 = GetTexCoord(pContext, indices[0]); - const SVec3 t2 = GetTexCoord(pContext, indices[1]); - const SVec3 t3 = GetTexCoord(pContext, indices[2]); - - const float t21x = t2.x-t1.x; - const float t21y = t2.y-t1.y; - const float t31x = t3.x-t1.x; - const float t31y = t3.y-t1.y; - - const float fSignedAreaSTx2 = t21x*t31y - t21y*t31x; - - return fSignedAreaSTx2<0 ? (-fSignedAreaSTx2) : fSignedAreaSTx2; -} - -static void InitTriInfo(STriInfo pTriInfos[], const int piTriListIn[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn) -{ - int f=0, i=0, t=0; - // pTriInfos[f].iFlag is cleared in GenerateInitialVerticesIndexList() which is called before this function. - - // generate neighbor info list - for (f=0; f0 ? ORIENT_PRESERVING : 0); - - if ( NotZero(fSignedAreaSTx2) ) - { - const float fAbsArea = fabsf(fSignedAreaSTx2); - const float fLenOs = Length(vOs); - const float fLenOt = Length(vOt); - const float fS = (pTriInfos[f].iFlag&ORIENT_PRESERVING)==0 ? (-1.0f) : 1.0f; - if ( NotZero(fLenOs) ) pTriInfos[f].vOs = vscale(fS/fLenOs, vOs); - if ( NotZero(fLenOt) ) pTriInfos[f].vOt = vscale(fS/fLenOt, vOt); - - // evaluate magnitudes prior to normalization of vOs and vOt - pTriInfos[f].fMagS = fLenOs / fAbsArea; - pTriInfos[f].fMagT = fLenOt / fAbsArea; - - // if this is a good triangle - if ( NotZero(pTriInfos[f].fMagS) && NotZero(pTriInfos[f].fMagT)) - pTriInfos[f].iFlag &= (~GROUP_WITH_ANY); - } - } - - // force otherwise healthy quads to a fixed orientation - while (t<(iNrTrianglesIn-1)) - { - const int iFO_a = pTriInfos[t].iOrgFaceNumber; - const int iFO_b = pTriInfos[t+1].iOrgFaceNumber; - if (iFO_a==iFO_b) // this is a quad - { - const tbool bIsDeg_a = (pTriInfos[t].iFlag&MARK_DEGENERATE)!=0 ? TTRUE : TFALSE; - const tbool bIsDeg_b = (pTriInfos[t+1].iFlag&MARK_DEGENERATE)!=0 ? TTRUE : TFALSE; - - // bad triangles should already have been removed by - // DegenPrologue(), but just in case check bIsDeg_a and bIsDeg_a are false - if ((bIsDeg_a||bIsDeg_b)==TFALSE) - { - const tbool bOrientA = (pTriInfos[t].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE; - const tbool bOrientB = (pTriInfos[t+1].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE; - // if this happens the quad has extremely bad mapping!! - if (bOrientA!=bOrientB) - { - //printf("found quad with bad mapping\n"); - tbool bChooseOrientFirstTri = TFALSE; - if ((pTriInfos[t+1].iFlag&GROUP_WITH_ANY)!=0) bChooseOrientFirstTri = TTRUE; - else if ( CalcTexArea(pContext, &piTriListIn[t*3+0]) >= CalcTexArea(pContext, &piTriListIn[(t+1)*3+0]) ) - bChooseOrientFirstTri = TTRUE; - - // force match - { - const int t0 = bChooseOrientFirstTri ? t : (t+1); - const int t1 = bChooseOrientFirstTri ? (t+1) : t; - pTriInfos[t1].iFlag &= (~ORIENT_PRESERVING); // clear first - pTriInfos[t1].iFlag |= (pTriInfos[t0].iFlag&ORIENT_PRESERVING); // copy bit - } - } - } - t += 2; - } - else - ++t; - } - - // match up edge pairs - { - SEdge * pEdges = (SEdge *) malloc(sizeof(SEdge)*iNrTrianglesIn*3); - if (pEdges==NULL) - BuildNeighborsSlow(pTriInfos, piTriListIn, iNrTrianglesIn); - else - { - BuildNeighborsFast(pTriInfos, pEdges, piTriListIn, iNrTrianglesIn); - - free(pEdges); - } - } -} - -///////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////// - -static tbool AssignRecur(const int piTriListIn[], STriInfo psTriInfos[], const int iMyTriIndex, SGroup * pGroup); -static void AddTriToGroup(SGroup * pGroup, const int iTriIndex); - -static int Build4RuleGroups(STriInfo pTriInfos[], SGroup pGroups[], int piGroupTrianglesBuffer[], const int piTriListIn[], const int iNrTrianglesIn) -{ - const int iNrMaxGroups = iNrTrianglesIn*3; - int iNrActiveGroups = 0; - int iOffset = 0, f=0, i=0; - (void)iNrMaxGroups; /* quiet warnings in non debug mode */ - for (f=0; fiVertexRepresentitive = vert_index; - pTriInfos[f].AssignedGroup[i]->bOrientPreservering = (pTriInfos[f].iFlag&ORIENT_PRESERVING)!=0; - pTriInfos[f].AssignedGroup[i]->iNrFaces = 0; - pTriInfos[f].AssignedGroup[i]->pFaceIndices = &piGroupTrianglesBuffer[iOffset]; - ++iNrActiveGroups; - - AddTriToGroup(pTriInfos[f].AssignedGroup[i], f); - bOrPre = (pTriInfos[f].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE; - neigh_indexL = pTriInfos[f].FaceNeighbors[i]; - neigh_indexR = pTriInfos[f].FaceNeighbors[i>0?(i-1):2]; - if (neigh_indexL>=0) // neighbor - { - const tbool bAnswer = - AssignRecur(piTriListIn, pTriInfos, neigh_indexL, - pTriInfos[f].AssignedGroup[i] ); - - const tbool bOrPre2 = (pTriInfos[neigh_indexL].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE; - const tbool bDiff = bOrPre!=bOrPre2 ? TTRUE : TFALSE; - assert(bAnswer || bDiff); - (void)bAnswer, (void)bDiff; /* quiet warnings in non debug mode */ - } - if (neigh_indexR>=0) // neighbor - { - const tbool bAnswer = - AssignRecur(piTriListIn, pTriInfos, neigh_indexR, - pTriInfos[f].AssignedGroup[i] ); - - const tbool bOrPre2 = (pTriInfos[neigh_indexR].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE; - const tbool bDiff = bOrPre!=bOrPre2 ? TTRUE : TFALSE; - assert(bAnswer || bDiff); - (void)bAnswer, (void)bDiff; /* quiet warnings in non debug mode */ - } - - // update offset - iOffset += pTriInfos[f].AssignedGroup[i]->iNrFaces; - // since the groups are disjoint a triangle can never - // belong to more than 3 groups. Subsequently something - // is completely screwed if this assertion ever hits. - assert(iOffset <= iNrMaxGroups); - } - } - } - - return iNrActiveGroups; -} - -static void AddTriToGroup(SGroup * pGroup, const int iTriIndex) -{ - pGroup->pFaceIndices[pGroup->iNrFaces] = iTriIndex; - ++pGroup->iNrFaces; -} - -static tbool AssignRecur(const int piTriListIn[], STriInfo psTriInfos[], - const int iMyTriIndex, SGroup * pGroup) -{ - STriInfo * pMyTriInfo = &psTriInfos[iMyTriIndex]; - - // track down vertex - const int iVertRep = pGroup->iVertexRepresentitive; - const int * pVerts = &piTriListIn[3*iMyTriIndex+0]; - int i=-1; - if (pVerts[0]==iVertRep) i=0; - else if (pVerts[1]==iVertRep) i=1; - else if (pVerts[2]==iVertRep) i=2; - assert(i>=0 && i<3); - - // early out - if (pMyTriInfo->AssignedGroup[i] == pGroup) return TTRUE; - else if (pMyTriInfo->AssignedGroup[i]!=NULL) return TFALSE; - if ((pMyTriInfo->iFlag&GROUP_WITH_ANY)!=0) - { - // first to group with a group-with-anything triangle - // determines it's orientation. - // This is the only existing order dependency in the code!! - if ( pMyTriInfo->AssignedGroup[0] == NULL && - pMyTriInfo->AssignedGroup[1] == NULL && - pMyTriInfo->AssignedGroup[2] == NULL ) - { - pMyTriInfo->iFlag &= (~ORIENT_PRESERVING); - pMyTriInfo->iFlag |= (pGroup->bOrientPreservering ? ORIENT_PRESERVING : 0); - } - } - { - const tbool bOrient = (pMyTriInfo->iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE; - if (bOrient != pGroup->bOrientPreservering) return TFALSE; - } - - AddTriToGroup(pGroup, iMyTriIndex); - pMyTriInfo->AssignedGroup[i] = pGroup; - - { - const int neigh_indexL = pMyTriInfo->FaceNeighbors[i]; - const int neigh_indexR = pMyTriInfo->FaceNeighbors[i>0?(i-1):2]; - if (neigh_indexL>=0) - AssignRecur(piTriListIn, psTriInfos, neigh_indexL, pGroup); - if (neigh_indexR>=0) - AssignRecur(piTriListIn, psTriInfos, neigh_indexR, pGroup); - } - - - - return TTRUE; -} - -///////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////// - -static tbool CompareSubGroups(const SSubGroup * pg1, const SSubGroup * pg2); -static void QuickSort(int* pSortBuffer, int iLeft, int iRight, unsigned int uSeed); -static STSpace EvalTspace(int face_indices[], const int iFaces, const int piTriListIn[], const STriInfo pTriInfos[], const SMikkTSpaceContext * pContext, const int iVertexRepresentitive); - -static tbool GenerateTSpaces(STSpace psTspace[], const STriInfo pTriInfos[], const SGroup pGroups[], - const int iNrActiveGroups, const int piTriListIn[], const float fThresCos, - const SMikkTSpaceContext * pContext) -{ - STSpace * pSubGroupTspace = NULL; - SSubGroup * pUniSubGroups = NULL; - int * pTmpMembers = NULL; - int iMaxNrFaces=0, iUniqueTspaces=0, g=0, i=0; - for (g=0; giNrFaces; i++) // triangles - { - const int f = pGroup->pFaceIndices[i]; // triangle number - int index=-1, iVertIndex=-1, iOF_1=-1, iMembers=0, j=0, l=0; - SSubGroup tmp_group; - tbool bFound; - SVec3 n, vOs, vOt; - if (pTriInfos[f].AssignedGroup[0]==pGroup) index=0; - else if (pTriInfos[f].AssignedGroup[1]==pGroup) index=1; - else if (pTriInfos[f].AssignedGroup[2]==pGroup) index=2; - assert(index>=0 && index<3); - - iVertIndex = piTriListIn[f*3+index]; - assert(iVertIndex==pGroup->iVertexRepresentitive); - - // is normalized already - n = GetNormal(pContext, iVertIndex); - - // project - vOs = vsub(pTriInfos[f].vOs, vscale(vdot(n,pTriInfos[f].vOs), n)); - vOt = vsub(pTriInfos[f].vOt, vscale(vdot(n,pTriInfos[f].vOt), n)); - if ( VNotZero(vOs) ) vOs = Normalize(vOs); - if ( VNotZero(vOt) ) vOt = Normalize(vOt); - - // original face number - iOF_1 = pTriInfos[f].iOrgFaceNumber; - - iMembers = 0; - for (j=0; jiNrFaces; j++) - { - const int t = pGroup->pFaceIndices[j]; // triangle number - const int iOF_2 = pTriInfos[t].iOrgFaceNumber; - - // project - SVec3 vOs2 = vsub(pTriInfos[t].vOs, vscale(vdot(n,pTriInfos[t].vOs), n)); - SVec3 vOt2 = vsub(pTriInfos[t].vOt, vscale(vdot(n,pTriInfos[t].vOt), n)); - if ( VNotZero(vOs2) ) vOs2 = Normalize(vOs2); - if ( VNotZero(vOt2) ) vOt2 = Normalize(vOt2); - - { - const tbool bAny = ( (pTriInfos[f].iFlag | pTriInfos[t].iFlag) & GROUP_WITH_ANY )!=0 ? TTRUE : TFALSE; - // make sure triangles which belong to the same quad are joined. - const tbool bSameOrgFace = iOF_1==iOF_2 ? TTRUE : TFALSE; - - const float fCosS = vdot(vOs,vOs2); - const float fCosT = vdot(vOt,vOt2); - - assert(f!=t || bSameOrgFace); // sanity check - if (bAny || bSameOrgFace || (fCosS>fThresCos && fCosT>fThresCos)) - pTmpMembers[iMembers++] = t; - } - } - - // sort pTmpMembers - tmp_group.iNrFaces = iMembers; - tmp_group.pTriMembers = pTmpMembers; - if (iMembers>1) - { - unsigned int uSeed = INTERNAL_RND_SORT_SEED; // could replace with a random seed? - QuickSort(pTmpMembers, 0, iMembers-1, uSeed); - } - - // look for an existing match - bFound = TFALSE; - l=0; - while (liVertexRepresentitive); - ++iUniqueSubGroups; - } - - // output tspace - { - const int iOffs = pTriInfos[f].iTSpacesOffs; - const int iVert = pTriInfos[f].vert_num[index]; - STSpace * pTS_out = &psTspace[iOffs+iVert]; - assert(pTS_out->iCounter<2); - assert(((pTriInfos[f].iFlag&ORIENT_PRESERVING)!=0) == pGroup->bOrientPreservering); - if (pTS_out->iCounter==1) - { - *pTS_out = AvgTSpace(pTS_out, &pSubGroupTspace[l]); - pTS_out->iCounter = 2; // update counter - pTS_out->bOrient = pGroup->bOrientPreservering; - } - else - { - assert(pTS_out->iCounter==0); - *pTS_out = pSubGroupTspace[l]; - pTS_out->iCounter = 1; // update counter - pTS_out->bOrient = pGroup->bOrientPreservering; - } - } - } - - // clean up and offset iUniqueTspaces - for (s=0; s=0 && i<3); - - // project - index = piTriListIn[3*f+i]; - n = GetNormal(pContext, index); - vOs = vsub(pTriInfos[f].vOs, vscale(vdot(n,pTriInfos[f].vOs), n)); - vOt = vsub(pTriInfos[f].vOt, vscale(vdot(n,pTriInfos[f].vOt), n)); - if ( VNotZero(vOs) ) vOs = Normalize(vOs); - if ( VNotZero(vOt) ) vOt = Normalize(vOt); - - i2 = piTriListIn[3*f + (i<2?(i+1):0)]; - i1 = piTriListIn[3*f + i]; - i0 = piTriListIn[3*f + (i>0?(i-1):2)]; - - p0 = GetPosition(pContext, i0); - p1 = GetPosition(pContext, i1); - p2 = GetPosition(pContext, i2); - v1 = vsub(p0,p1); - v2 = vsub(p2,p1); - - // project - v1 = vsub(v1, vscale(vdot(n,v1),n)); if ( VNotZero(v1) ) v1 = Normalize(v1); - v2 = vsub(v2, vscale(vdot(n,v2),n)); if ( VNotZero(v2) ) v2 = Normalize(v2); - - // weight contribution by the angle - // between the two edge vectors - fCos = vdot(v1,v2); fCos=fCos>1?1:(fCos<(-1) ? (-1) : fCos); - fAngle = (float) acos(fCos); - fMagS = pTriInfos[f].fMagS; - fMagT = pTriInfos[f].fMagT; - - res.vOs=vadd(res.vOs, vscale(fAngle,vOs)); - res.vOt=vadd(res.vOt,vscale(fAngle,vOt)); - res.fMagS+=(fAngle*fMagS); - res.fMagT+=(fAngle*fMagT); - fAngleSum += fAngle; - } - } - - // normalize - if ( VNotZero(res.vOs) ) res.vOs = Normalize(res.vOs); - if ( VNotZero(res.vOt) ) res.vOt = Normalize(res.vOt); - if (fAngleSum>0) - { - res.fMagS /= fAngleSum; - res.fMagT /= fAngleSum; - } - - return res; -} - -static tbool CompareSubGroups(const SSubGroup * pg1, const SSubGroup * pg2) -{ - tbool bStillSame=TTRUE; - int i=0; - if (pg1->iNrFaces!=pg2->iNrFaces) return TFALSE; - while (iiNrFaces && bStillSame) - { - bStillSame = pg1->pTriMembers[i]==pg2->pTriMembers[i] ? TTRUE : TFALSE; - if (bStillSame) ++i; - } - return bStillSame; -} - -static void QuickSort(int* pSortBuffer, int iLeft, int iRight, unsigned int uSeed) -{ - int iL, iR, n, index, iMid, iTmp; - - // Random - unsigned int t=uSeed&31; - t=(uSeed<>(32-t)); - uSeed=uSeed+t+3; - // Random end - - iL=iLeft; iR=iRight; - n = (iR-iL)+1; - assert(n>=0); - index = (int) (uSeed%n); - - iMid=pSortBuffer[index + iL]; - - - do - { - while (pSortBuffer[iL] < iMid) - ++iL; - while (pSortBuffer[iR] > iMid) - --iR; - - if (iL <= iR) - { - iTmp = pSortBuffer[iL]; - pSortBuffer[iL] = pSortBuffer[iR]; - pSortBuffer[iR] = iTmp; - ++iL; --iR; - } - } - while (iL <= iR); - - if (iLeft < iR) - QuickSort(pSortBuffer, iLeft, iR, uSeed); - if (iL < iRight) - QuickSort(pSortBuffer, iL, iRight, uSeed); -} - -///////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////// - -static void QuickSortEdges(SEdge * pSortBuffer, int iLeft, int iRight, const int channel, unsigned int uSeed); -static void GetEdge(int * i0_out, int * i1_out, int * edgenum_out, const int indices[], const int i0_in, const int i1_in); - -static void BuildNeighborsFast(STriInfo pTriInfos[], SEdge * pEdges, const int piTriListIn[], const int iNrTrianglesIn) -{ - // build array of edges - unsigned int uSeed = INTERNAL_RND_SORT_SEED; // could replace with a random seed? - int iEntries=0, iCurStartIndex=-1, f=0, i=0; - for (f=0; f pSortBuffer[iRight].array[channel]) - { - sTmp = pSortBuffer[iLeft]; - pSortBuffer[iLeft] = pSortBuffer[iRight]; - pSortBuffer[iRight] = sTmp; - } - return; - } - - // Random - t=uSeed&31; - t=(uSeed<>(32-t)); - uSeed=uSeed+t+3; - // Random end - - iL = iLeft; - iR = iRight; - n = (iR-iL)+1; - assert(n>=0); - index = (int) (uSeed%n); - - iMid=pSortBuffer[index + iL].array[channel]; - - do - { - while (pSortBuffer[iL].array[channel] < iMid) - ++iL; - while (pSortBuffer[iR].array[channel] > iMid) - --iR; - - if (iL <= iR) - { - sTmp = pSortBuffer[iL]; - pSortBuffer[iL] = pSortBuffer[iR]; - pSortBuffer[iR] = sTmp; - ++iL; --iR; - } - } - while (iL <= iR); - - if (iLeft < iR) - QuickSortEdges(pSortBuffer, iLeft, iR, channel, uSeed); - if (iL < iRight) - QuickSortEdges(pSortBuffer, iL, iRight, channel, uSeed); -} - -// resolve ordering and edge number -static void GetEdge(int * i0_out, int * i1_out, int * edgenum_out, const int indices[], const int i0_in, const int i1_in) -{ - *edgenum_out = -1; - - // test if first index is on the edge - if (indices[0]==i0_in || indices[0]==i1_in) - { - // test if second index is on the edge - if (indices[1]==i0_in || indices[1]==i1_in) - { - edgenum_out[0]=0; // first edge - i0_out[0]=indices[0]; - i1_out[0]=indices[1]; - } - else - { - edgenum_out[0]=2; // third edge - i0_out[0]=indices[2]; - i1_out[0]=indices[0]; - } - } - else - { - // only second and third index is on the edge - edgenum_out[0]=1; // second edge - i0_out[0]=indices[1]; - i1_out[0]=indices[2]; - } -} - - -///////////////////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////// Degenerate triangles //////////////////////////////////// - -static void DegenPrologue(STriInfo pTriInfos[], int piTriList_out[], const int iNrTrianglesIn, const int iTotTris) -{ - int iNextGoodTriangleSearchIndex=-1; - tbool bStillFindingGoodOnes; - - // locate quads with only one good triangle - int t=0; - while (t<(iTotTris-1)) - { - const int iFO_a = pTriInfos[t].iOrgFaceNumber; - const int iFO_b = pTriInfos[t+1].iOrgFaceNumber; - if (iFO_a==iFO_b) // this is a quad - { - const tbool bIsDeg_a = (pTriInfos[t].iFlag&MARK_DEGENERATE)!=0 ? TTRUE : TFALSE; - const tbool bIsDeg_b = (pTriInfos[t+1].iFlag&MARK_DEGENERATE)!=0 ? TTRUE : TFALSE; - if ((bIsDeg_a^bIsDeg_b)!=0) - { - pTriInfos[t].iFlag |= QUAD_ONE_DEGEN_TRI; - pTriInfos[t+1].iFlag |= QUAD_ONE_DEGEN_TRI; - } - t += 2; - } - else - ++t; - } - - // reorder list so all degen triangles are moved to the back - // without reordering the good triangles - iNextGoodTriangleSearchIndex = 1; - t=0; - bStillFindingGoodOnes = TTRUE; - while (t (t+1)); - - // swap triangle t0 and t1 - if (!bJustADegenerate) - { - int i=0; - for (i=0; i<3; i++) - { - const int index = piTriList_out[t0*3+i]; - piTriList_out[t0*3+i] = piTriList_out[t1*3+i]; - piTriList_out[t1*3+i] = index; - } - { - const STriInfo tri_info = pTriInfos[t0]; - pTriInfos[t0] = pTriInfos[t1]; - pTriInfos[t1] = tri_info; - } - } - else - bStillFindingGoodOnes = TFALSE; // this is not supposed to happen - } - - if (bStillFindingGoodOnes) ++t; - } - - assert(bStillFindingGoodOnes); // code will still work. - assert(iNrTrianglesIn == t); -} - -static void DegenEpilogue(STSpace psTspace[], STriInfo pTriInfos[], int piTriListIn[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn, const int iTotTris) -{ - int t=0, i=0; - // deal with degenerate triangles - // punishment for degenerate triangles is O(N^2) - for (t=iNrTrianglesIn; t http://image.diku.dk/projects/media/morten.mikkelsen.08.pdf - * Note that though the tangent spaces at the vertices are generated in an order-independent way, - * by this implementation, the interpolated tangent space is still affected by which diagonal is - * chosen to split each quad. A sensible solution is to have your tools pipeline always - * split quads by the shortest diagonal. This choice is order-independent and works with mirroring. - * If these have the same length then compare the diagonals defined by the texture coordinates. - * XNormal which is a tool for baking normal maps allows you to write your own tangent space plugin - * and also quad triangulator plugin. - */ - - -typedef int tbool; -typedef struct SMikkTSpaceContext SMikkTSpaceContext; - -typedef struct { - // Returns the number of faces (triangles/quads) on the mesh to be processed. - int (*m_getNumFaces)(const SMikkTSpaceContext * pContext); - - // Returns the number of vertices on face number iFace - // iFace is a number in the range {0, 1, ..., getNumFaces()-1} - int (*m_getNumVerticesOfFace)(const SMikkTSpaceContext * pContext, const int iFace); - - // returns the position/normal/texcoord of the referenced face of vertex number iVert. - // iVert is in the range {0,1,2} for triangles and {0,1,2,3} for quads. - void (*m_getPosition)(const SMikkTSpaceContext * pContext, float fvPosOut[], const int iFace, const int iVert); - void (*m_getNormal)(const SMikkTSpaceContext * pContext, float fvNormOut[], const int iFace, const int iVert); - void (*m_getTexCoord)(const SMikkTSpaceContext * pContext, float fvTexcOut[], const int iFace, const int iVert); - - // either (or both) of the two setTSpace callbacks can be set. - // The call-back m_setTSpaceBasic() is sufficient for basic normal mapping. - - // This function is used to return the tangent and fSign to the application. - // fvTangent is a unit length vector. - // For normal maps it is sufficient to use the following simplified version of the bitangent which is generated at pixel/vertex level. - // bitangent = fSign * cross(vN, tangent); - // Note that the results are returned unindexed. It is possible to generate a new index list - // But averaging/overwriting tangent spaces by using an already existing index list WILL produce INCRORRECT results. - // DO NOT! use an already existing index list. - void (*m_setTSpaceBasic)(const SMikkTSpaceContext * pContext, const float fvTangent[], const float fSign, const int iFace, const int iVert); - - // This function is used to return tangent space results to the application. - // fvTangent and fvBiTangent are unit length vectors and fMagS and fMagT are their - // true magnitudes which can be used for relief mapping effects. - // fvBiTangent is the "real" bitangent and thus may not be perpendicular to fvTangent. - // However, both are perpendicular to the vertex normal. - // For normal maps it is sufficient to use the following simplified version of the bitangent which is generated at pixel/vertex level. - // fSign = bIsOrientationPreserving ? 1.0f : (-1.0f); - // bitangent = fSign * cross(vN, tangent); - // Note that the results are returned unindexed. It is possible to generate a new index list - // But averaging/overwriting tangent spaces by using an already existing index list WILL produce INCRORRECT results. - // DO NOT! use an already existing index list. - void (*m_setTSpace)(const SMikkTSpaceContext * pContext, const float fvTangent[], const float fvBiTangent[], const float fMagS, const float fMagT, - const tbool bIsOrientationPreserving, const int iFace, const int iVert); -} SMikkTSpaceInterface; - -struct SMikkTSpaceContext -{ - SMikkTSpaceInterface * m_pInterface; // initialized with callback functions - void * m_pUserData; // pointer to client side mesh data etc. (passed as the first parameter with every interface call) -}; - -// these are both thread safe! -tbool genTangSpaceDefault(const SMikkTSpaceContext * pContext); // Default (recommended) fAngularThreshold is 180 degrees (which means threshold disabled) -tbool genTangSpace(const SMikkTSpaceContext * pContext, const float fAngularThreshold); - - -// To avoid visual errors (distortions/unwanted hard edges in lighting), when using sampled normal maps, the -// normal map sampler must use the exact inverse of the pixel shader transformation. -// The most efficient transformation we can possibly do in the pixel shader is -// achieved by using, directly, the "unnormalized" interpolated tangent, bitangent and vertex normal: vT, vB and vN. -// pixel shader (fast transform out) -// vNout = normalize( vNt.x * vT + vNt.y * vB + vNt.z * vN ); -// where vNt is the tangent space normal. The normal map sampler must likewise use the -// interpolated and "unnormalized" tangent, bitangent and vertex normal to be compliant with the pixel shader. -// sampler does (exact inverse of pixel shader): -// float3 row0 = cross(vB, vN); -// float3 row1 = cross(vN, vT); -// float3 row2 = cross(vT, vB); -// float fSign = dot(vT, row0)<0 ? -1 : 1; -// vNt = normalize( fSign * float3(dot(vNout,row0), dot(vNout,row1), dot(vNout,row2)) ); -// where vNout is the sampled normal in some chosen 3D space. -// -// Should you choose to reconstruct the bitangent in the pixel shader instead -// of the vertex shader, as explained earlier, then be sure to do this in the normal map sampler also. -// Finally, beware of quad triangulations. If the normal map sampler doesn't use the same triangulation of -// quads as your renderer then problems will occur since the interpolated tangent spaces will differ -// eventhough the vertex level tangent spaces match. This can be solved either by triangulating before -// sampling/exporting or by using the order-independent choice of diagonal for splitting quads suggested earlier. -// However, this must be used both by the sampler and your tools/rendering pipeline. - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/gfx/contrib/cgltf-tangents/README.md b/gfx/contrib/cgltf-tangents/README.md deleted file mode 100644 index 2a68b27..0000000 --- a/gfx/contrib/cgltf-tangents/README.md +++ /dev/null @@ -1,42 +0,0 @@ -# cgltf-tangents - -A library to compute missing tangent vectors in glTF models using MikkTSpace. - -## Example - -``` -// Load the glTF scene and buffers as usual. -cgltf_result result = cgltf_parse_file(&options, filepath, &data); -cgltf_load_buffers(&options, data, filepath); - -// Compute missing tangents. -cgltfTangentBuffer* tangent_buffers = 0; -cgltf_size num_tangent_buffers = 0; -cgltf_compute_tangents(&options, data, &tangent_buffers, &num_tangent_buffers); -``` - -## About - -This is a single-header/source library that combines -[MikkTSpace](https://github.com/mmikk/MikkTSpace) and -[cgltf](https://github.com/jkuhlmann/cgltf) to compute missing tangent vectors -for models. - -Mesh primitives in glTF may have a normal map but not necessarily tangent -vectors. An example is the -[DamagedHelmet](https://github.com/KhronosGroup/glTF-Sample-Models/tree/master/2.0/DamagedHelmet/glTF) -sample. From the -[spec](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#meshes): - -*"When tangents are not specified, client implementations SHOULD calculate -tangents using default MikkTSpace algorithms with the specified vertex -positions, normals, and texture coordinates associated with the normal texture."* - -cgltf-tangents takes an input glTF scene and scans it for mesh primitives that -have a normal map but no tangents. cgltf-tangents then invokes MikkTSpace to -compute tangents for those mesh primitives and outputs an array of tangent -buffers. The client can then upload these buffers to GPU memory for rendering. - -See `test/` for a complete example. - -MikkTSpace is packaged here for convenience. cgltf must be obtained separately. diff --git a/gfx/contrib/cgltf-tangents/cgltf_tangents.c b/gfx/contrib/cgltf-tangents/cgltf_tangents.c deleted file mode 100644 index 80b1e56..0000000 --- a/gfx/contrib/cgltf-tangents/cgltf_tangents.c +++ /dev/null @@ -1,618 +0,0 @@ -/* -Copyright 2022 Marc Sunet - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this -list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, -this list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include "cgltf_tangents.h" -#include "cgltf.h" - -#include "MikkTSpace/mikktspace.h" - -#include -#include -#include -#include -#include - -#ifdef CGLTF_TANGENTS_DEBUG -#include -#define DLOG printf -#else -#define DLOG(...) -#endif - -#include // TODO: Remove me. - -#define CGLTF_OPTIONS_MALLOC(size) \ - options->memory.alloc(options->memory.user_data, size) - -#define CGLTF_OPTIONS_FREE(ptr) \ - options->memory.free(options->memory.user_data, ptr) - -static void* cgltf_default_alloc(void* user, cgltf_size size) { - (void)user; - return malloc(size); -} - -static void cgltf_default_free(void* user, void* ptr) { - (void)user; - free(ptr); -} - -static const cgltf_size NUM_TANGENT_COMPONENTS = 4; // X,Y,Z,fSign - -static float normalize_i8(int8_t x) { return (float)x / 128.0; } -static float normalize_u8(uint8_t x) { return (float)x / 255.0; } -static float normalize_i16(int16_t x) { return (float)x / 32768.0; } -static float normalize_u16(uint16_t x) { return (float)x / 65535.0; } -static float normalize_u32(uint32_t x) { return (float)x / 4294967295.0; } - -static cgltf_size num_vertex_attrib_components(cgltf_type type) { - switch (type) { - case cgltf_type_scalar: - return 1; - case cgltf_type_vec2: - return 2; - case cgltf_type_vec3: - return 3; - case cgltf_type_vec4: - return 4; - default: - assert(false); - return 0; - } -} - -static cgltf_size cgltf_component_type_size_bytes(cgltf_component_type type) { - switch (type) { - case cgltf_component_type_r_8: - return 1; - case cgltf_component_type_r_8u: - return 1; - case cgltf_component_type_r_16: - return 2; - case cgltf_component_type_r_16u: - return 2; - case cgltf_component_type_r_32u: - return 4; - case cgltf_component_type_r_32f: - return 4; - default: - assert(false); - return 0; - } -} - -static cgltf_size default_stride(cgltf_type type, - cgltf_component_type component_type) { - return num_vertex_attrib_components(type) * - cgltf_component_type_size_bytes(component_type); -} - -// ----------------------------------------------------------------------------- -// MikkTSpace interface - -// An array of values for a given vertex attribute or for vertex indices. -// For positions and normals, glTF mandates floats. -// Texcoords and indices can be different types and vary in size: 8-bit, 16-bit, -// or 32-bit. -// We store void* pointers so that we can do byte pointer arithmetic. -typedef struct Buffer { - const void* start; // X-coordinate of the first attribute. - const void* end; // One byte past the end of the buffer. - cgltf_size stride_bytes; // Stride in bytes between each value. - cgltf_component_type type; // Type of each value in the buffer. -} Buffer; - -// User data for mesh processing. -// See: https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#meshes -// Buffer pointers have the accessor + view offsets baked in so that we do the -// addition only once. -typedef struct SMikkUserData { - const cgltf_primitive* primitive; - // Index buffer may be empty (mesh primitive has no indices). - Buffer indices; - // Vertex attributes. - Buffer positions; - Buffer normals; - Buffer texcoords; - // Output tangents. - void* tangents; -} SMikkUserData; - -static cgltf_size get_vertex_index(const SMikkUserData* data, cgltf_size iFace, - cgltf_size iVert) { - const cgltf_primitive* primitive = data->primitive; - - // First compute a vertex index as if the mesh primitive had no indices. - cgltf_size vertex_idx = 0; - switch (primitive->type) { - case cgltf_primitive_type_triangles: - vertex_idx = iFace * 3 + iVert; - break; - case cgltf_primitive_type_triangle_strip: - // For triangle strips: - // face 0 -> verts 0, 1, 2 - // face 1 -> verts 1, 3, 2 (1, 2, 3 flipped) - // face 2 -> verts 2, 3, 4 - // face 3 -> verts 3, 5, 4 (3, 4, 5 flipped) - // ... - // face N=2k -> verts N, N+1, N+2 - // face N=2k+1 -> verts N, N+2, N+1 - if (iFace & 1) { - // Flip the winding of odd faces so that the is consistent with the even - // ones. - // iVert = 0 -> vert 0 - // iVert = 1 -> vert 2 - // iVert = 2 -> vert 1 - vertex_idx = iFace + (2 - iVert); - } else { - vertex_idx = iFace + iVert; - } - break; - case cgltf_primitive_type_triangle_fan: - // For triangle fans: - // face 0 -> verts 0, 1, 2 - // face 1 -> verts 0, 2, 3 - // face 2 -> verts 0, 3, 4 - // face 3 -> verts 0, 4, 5 - // ... - // face N -> verts 0, N=1, N=2 - if (iVert == 0) { - vertex_idx = 0; - } else { - vertex_idx = iFace + iVert; - } - break; - default: - assert(false); - break; - } - - // If the mesh primitive has vertex indices, then vertex_idx is actually the - // index of the index. Index the index buffer with vertex_idx to find the - // real vertex index. - if (primitive->indices != NULL) { - const void* p_idx = - data->indices.start + vertex_idx * data->indices.stride_bytes; - switch (data->indices.type) { - case cgltf_component_type_r_8: - vertex_idx = *((int8_t*)p_idx); - break; - case cgltf_component_type_r_8u: - vertex_idx = *((uint8_t*)p_idx); - break; - case cgltf_component_type_r_16: - vertex_idx = *((int16_t*)p_idx); - break; - case cgltf_component_type_r_16u: - vertex_idx = *((uint16_t*)p_idx); - break; - case cgltf_component_type_r_32u: - vertex_idx = *((uint32_t*)p_idx); - break; - default: - assert(false); - break; - } - } - - return vertex_idx; -} - -static const void* get_vertex(const Buffer* buffer, cgltf_size index) { - // Stride is the offset in bytes between vertex attributes. - const void* vertex = buffer->start + buffer->stride_bytes * index; - assert(vertex < buffer->end); - return vertex; -} - -static const void* get_position(const SMikkUserData* data, cgltf_size index) { - return get_vertex(&data->positions, index); -} - -static const void* get_normal(const SMikkUserData* data, cgltf_size index) { - return get_vertex(&data->normals, index); -} - -static const void* get_texcoord(const SMikkUserData* data, cgltf_size index) { - return get_vertex(&data->texcoords, index); -} - -static float* get_tangent(void* buffer, cgltf_size index) { - // Tangents are tightly packed. - return (float*)(buffer) + NUM_TANGENT_COMPONENTS * index; -} - -static int SMikk_get_num_faces(const SMikkTSpaceContext* pContext) { - SMikkUserData* data = (SMikkUserData*)pContext->m_pUserData; - const cgltf_primitive* primitive = data->primitive; - - // Find the number of effective vertices (vertices or indices) in the mesh - // primitive. - // - // https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#meshes - // - // "All attribute accessors for a given primitive MUST have the same count. - // When indices property is not defined, attribute accessors' count indicates - // the number of vertices to render; when indices property is defined, it - // indicates the upper (exclusive) bound on the index values in the indices - // accessor, i.e., all index values MUST be less than attribute accessors' - // count." - const cgltf_size num_verts = (primitive->indices != NULL) - ? primitive->indices->count - : primitive->attributes_count; - - // Determine the number of faces given the number of vertices. - // - // We use the fact that glTF only supports triangles for faces. - // https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#meshes - switch (primitive->type) { - case cgltf_primitive_type_triangles: - return (int)num_verts / 3; - case cgltf_primitive_type_triangle_strip: - case cgltf_primitive_type_triangle_fan: - return (int)num_verts - 2; - default: - return 0; - } -} - -int SMikk_get_num_vertices_of_face(const SMikkTSpaceContext* pContext, - const int iFace) { - // Triangles are the only faces supported by glTF. - // https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#meshes - return 3; -} - -void SMikk_get_position(const SMikkTSpaceContext* pContext, float fvPosOut[], - const int iFace, const int iVert) { - const SMikkUserData* data = (SMikkUserData*)pContext->m_pUserData; - const cgltf_primitive* primitive = data->primitive; - - const cgltf_size idx = get_vertex_index(data, iFace, iVert); - const float* coord = get_position(data, idx); - fvPosOut[0] = *coord++; - fvPosOut[1] = *coord++; - fvPosOut[2] = *coord; - DLOG("Position (face: %d, vert: %d): %f, %f, %f; idx: %lu\n", iFace, iVert, - fvPosOut[0], fvPosOut[1], fvPosOut[2], idx); -} - -void SMikk_get_normal(const SMikkTSpaceContext* pContext, float fvNormOut[], - const int iFace, const int iVert) { - const SMikkUserData* data = (SMikkUserData*)pContext->m_pUserData; - const cgltf_primitive* primitive = data->primitive; - - const cgltf_size idx = get_vertex_index(data, iFace, iVert); - const float* coord = get_normal(data, idx); - fvNormOut[0] = *coord++; - fvNormOut[1] = *coord++; - fvNormOut[2] = *coord; - DLOG("Normal (face: %d, vert: %d): %f, %f, %f\n", iFace, iVert, fvNormOut[0], - fvNormOut[1], fvNormOut[2]); -} - -void SMikk_get_texcoord(const SMikkTSpaceContext* pContext, float fvTexcOut[], - const int iFace, const int iVert) { - const SMikkUserData* data = (SMikkUserData*)pContext->m_pUserData; - const cgltf_primitive* primitive = data->primitive; - - const cgltf_size idx = get_vertex_index(data, iFace, iVert); - const void* coord = get_texcoord(data, idx); - switch (data->texcoords.type) { - case cgltf_component_type_r_8: { - const int8_t* c = coord; - fvTexcOut[0] = normalize_i8(*c++); - fvTexcOut[1] = normalize_i8(*c); - break; - } - case cgltf_component_type_r_8u: { - const uint8_t* c = coord; - fvTexcOut[0] = normalize_u8(*c++); - fvTexcOut[1] = normalize_u8(*c); - break; - } - case cgltf_component_type_r_16: { - const int16_t* c = coord; - fvTexcOut[0] = normalize_i16(*c++); - fvTexcOut[1] = normalize_i16(*c); - break; - } - case cgltf_component_type_r_16u: { - const uint16_t* c = coord; - fvTexcOut[0] = normalize_u16(*c++); - fvTexcOut[1] = normalize_u16(*c); - break; - } - case cgltf_component_type_r_32u: { - const uint32_t* c = coord; - fvTexcOut[0] = normalize_u32(*c++); - fvTexcOut[1] = normalize_u32(*c); - break; - } - case cgltf_component_type_r_32f: { - const float* c = coord; - fvTexcOut[0] = *c++; - fvTexcOut[1] = *c; - break; - } - default: - assert(false); - break; - } - DLOG("Texcoord (face: %d, vert: %d): %f, %f\n", iFace, iVert, fvTexcOut[0], - fvTexcOut[1]); -} - -void SMikk_set_TSpace_basic(const SMikkTSpaceContext* pContext, - const float fvTangent[], const float fSign, - const int iFace, const int iVert) { - SMikkUserData* data = (SMikkUserData*)pContext->m_pUserData; - const cgltf_primitive* primitive = data->primitive; - - const cgltf_size idx = get_vertex_index(data, iFace, iVert); - float* coord = get_tangent(data->tangents, idx); - *coord++ = fvTangent[0]; - *coord++ = fvTangent[1]; - *coord++ = fvTangent[2]; - *coord = fSign; - DLOG("Tangent (face: %d, vert: %d): %f, %f, %f; sign: %f\n", iFace, iVert, - fvTangent[0], fvTangent[1], fvTangent[2], fSign); -} - -// ----------------------------------------------------------------------------- - -static bool has_normal_map(const cgltf_primitive* primitive) { - return (primitive->material != NULL) && - (primitive->material->normal_texture.texture != NULL); -} - -static const cgltf_attribute* find_attribute(const cgltf_primitive* primitive, - cgltf_attribute_type type) { - for (cgltf_size i = 0; i < primitive->attributes_count; ++i) { - const cgltf_attribute* attrib = &primitive->attributes[i]; - if (attrib->type == type) { - return attrib; - } - } - return NULL; -} - -static bool has_attribute(const cgltf_primitive* primitive, - cgltf_attribute_type type) { - return find_attribute(primitive, type) != NULL; -} - -static bool has_positions3d(const cgltf_primitive* primitive) { - const cgltf_attribute* attrib = - find_attribute(primitive, cgltf_attribute_type_position); - if (attrib) { - return attrib->data->type == cgltf_type_vec3; - } - return false; -} - -static bool has_normals(const cgltf_primitive* primitive) { - return has_attribute(primitive, cgltf_attribute_type_normal); -} - -static bool has_texcoords(const cgltf_primitive* primitive) { - return has_attribute(primitive, cgltf_attribute_type_texcoord); -} - -static bool has_tangents(const cgltf_primitive* primitive) { - return has_attribute(primitive, cgltf_attribute_type_tangent); -} - -static bool has_indices(const cgltf_primitive* primitive) { - return primitive->indices != 0; -} - -static cgltfTangentBuffer compute_tangents(const cgltf_options* options, - const cgltf_data* data, - cgltf_primitive* primitive) { - cgltfTangentBuffer buffer = {0}; - SMikkUserData user = {0}; - cgltf_size num_verts = 0; - - user.primitive = primitive; - - if (primitive->indices != NULL) { - const cgltf_accessor* accessor = primitive->indices; - const cgltf_buffer_view* view = accessor->buffer_view; - const cgltf_size offset_bytes = accessor->offset + view->offset; - const void* buffer_data = view->buffer->data + offset_bytes; - const void* buffer_end = view->buffer->data + view->offset + view->size; - - user.indices.start = buffer_data; - user.indices.end = buffer_end; - // Indices are tightly packed, stride 0. - user.indices.stride_bytes = - default_stride(accessor->type, accessor->component_type); - user.indices.type = accessor->component_type; - } - - for (cgltf_size i = 0; i < primitive->attributes_count; ++i) { - const cgltf_attribute* attrib = &primitive->attributes[i]; - - if ((attrib->type == cgltf_attribute_type_position) || - (attrib->type == cgltf_attribute_type_normal) || - (attrib->type == cgltf_attribute_type_texcoord)) { - const cgltf_accessor* accessor = attrib->data; - const cgltf_buffer_view* view = accessor->buffer_view; - const cgltf_buffer* buffer = view->buffer; - const cgltf_size offset_bytes = accessor->offset + view->offset; - const cgltf_size stride_bytes = - view->stride > 0 - ? view->stride - : default_stride(accessor->type, accessor->component_type); - // const cgltf_size size_bytes = view->size; - const void* buffer_data = view->buffer->data + offset_bytes; - const void* buffer_end = view->buffer->data + view->offset + view->size; - - Buffer* attrib_buffer = 0; - - if (attrib->type == cgltf_attribute_type_position) { - // glTF currently mandates vec3 for positions. Caller should ensure - // this. - assert(accessor->type == cgltf_type_vec3); - num_verts = attrib->data->count; - attrib_buffer = &user.positions; - } else if (attrib->type == cgltf_attribute_type_normal) { - attrib_buffer = &user.normals; - } else if (attrib->type == cgltf_attribute_type_texcoord) { - attrib_buffer = &user.texcoords; - } - - attrib_buffer->start = buffer_data; - attrib_buffer->end = buffer_end; - attrib_buffer->stride_bytes = stride_bytes; - attrib_buffer->type = accessor->component_type; - } - } - - assert(user.positions.start); - assert(user.positions.end); - assert(user.normals.start); - assert(user.normals.end); - assert(user.texcoords.start); - assert(user.texcoords.end); - assert(num_verts > 0); - - const cgltf_size tangents_size_bytes = - num_verts * NUM_TANGENT_COMPONENTS * sizeof(float); - - user.tangents = CGLTF_OPTIONS_MALLOC(tangents_size_bytes); - if (!user.tangents) { - return buffer; - } - - SMikkTSpaceInterface interface = (SMikkTSpaceInterface){ - .m_getNumFaces = SMikk_get_num_faces, - .m_getNumVerticesOfFace = SMikk_get_num_vertices_of_face, - .m_getPosition = SMikk_get_position, - .m_getNormal = SMikk_get_normal, - .m_getTexCoord = SMikk_get_texcoord, - .m_setTSpaceBasic = SMikk_set_TSpace_basic, - }; - const SMikkTSpaceContext context = (SMikkTSpaceContext){ - .m_pInterface = &interface, - .m_pUserData = &user, - }; - if (!genTangSpaceDefault(&context)) { - return buffer; - } - - buffer.data = user.tangents; - buffer.size_bytes = tangents_size_bytes; - buffer.primitive = primitive; - - return buffer; -} - -static void process_primitive(const cgltf_options* options, - const cgltf_data* data, - cgltf_primitive* primitive, - cgltfTangentBuffer* tangent_buffers, - cgltf_size* num_tangent_buffers) { - DLOG("Processing primitive\n"); - cgltf_size cur_buffer = 0; - // TODO: MikkTSpace should not be used with models with vertex indices. One - // workaround is to unindex the mesh, compute tangents, and then re-index it. - if (((primitive->type == cgltf_primitive_type_triangle_fan) || - (primitive->type == cgltf_primitive_type_triangle_strip) || - (primitive->type == cgltf_primitive_type_triangles)) && - has_normal_map(primitive) && !has_tangents(primitive) && - has_positions3d(primitive) && has_normals(primitive) && - has_texcoords(primitive) && !has_indices(primitive)) { - *num_tangent_buffers += 1; - if (tangent_buffers) { - DLOG("Model with normal map missing tangents detected\n"); - tangent_buffers[cur_buffer] = compute_tangents(options, data, primitive); - if (tangent_buffers[cur_buffer].data) { - DLOG("Tangents computed\n"); - } - cur_buffer++; - } - } -} - -cgltf_result cgltf_compute_tangents(const cgltf_options* input_options, - const cgltf_data* data, - cgltfTangentBuffer** tangent_buffers, - cgltf_size* num_tangent_buffers) { - if ((input_options == NULL) || (data == NULL)) { - return cgltf_result_invalid_options; - } - - DLOG("cgltf_compute_tangents\n"); - - cgltf_options options = *input_options; - if (options.memory.alloc == NULL) { - options.memory.alloc = &cgltf_default_alloc; - } - if (options.memory.free == NULL) { - options.memory.free = &cgltf_default_free; - } - - // First pass: compute the number of tangent buffers to be created. - *num_tangent_buffers = 0; - for (cgltf_size mesh_idx = 0; mesh_idx < data->meshes_count; ++mesh_idx) { - const cgltf_mesh* mesh = &data->meshes[mesh_idx]; - - for (cgltf_size prim_idx = 0; prim_idx < mesh->primitives_count; - ++prim_idx) { - // Pass in null for the tangent buffers to just compute the number of - // buffers. - process_primitive(&options, data, &mesh->primitives[prim_idx], 0, - num_tangent_buffers); - } - } - DLOG("Number of primitives to be patched: %lu\n", *num_tangent_buffers); - - // Second pass: compute the tangents. - if (*num_tangent_buffers > 0) { - *tangent_buffers = - options.memory.alloc(options.memory.user_data, - *num_tangent_buffers * sizeof(cgltfTangentBuffer)); - if (!*tangent_buffers) { - return cgltf_result_out_of_memory; - } - - cgltf_size tangent_buffers_computed = 0; - - for (cgltf_size mesh_idx = 0; mesh_idx < data->meshes_count; ++mesh_idx) { - const cgltf_mesh* mesh = &data->meshes[mesh_idx]; - - for (cgltf_size prim_idx = 0; prim_idx < mesh->primitives_count; - ++prim_idx) { - process_primitive(&options, data, &mesh->primitives[prim_idx], - *tangent_buffers, &tangent_buffers_computed); - } - } - - assert(tangent_buffers_computed == *num_tangent_buffers); - } - - return cgltf_result_success; -} diff --git a/gfx/contrib/cgltf-tangents/cgltf_tangents.h b/gfx/contrib/cgltf-tangents/cgltf_tangents.h deleted file mode 100644 index 79e3502..0000000 --- a/gfx/contrib/cgltf-tangents/cgltf_tangents.h +++ /dev/null @@ -1,67 +0,0 @@ -/* -Copyright 2022 Marc Sunet - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this -list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, -this list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#ifndef CGLTF_TANGENTS_H_INCLUDED__ -#define CGLTF_TANGENTS_H_INCLUDED__ - -#include - -/// A buffer that holds tangent vectors. -/// -/// Tangent vectors are tightly packed in the array. -/// -/// Tangent vectors have 4 coordinates: (X,Y,Z) for the vector, W for the sign. -/// The usual rules of MikkTSpace apply, namely that the bitangent should be -/// computed as: -/// -/// bitangent = tangent.w * cross(normal, tangent.xyz); -/// -/// Refer to the MikkTSpace documentation for more details. -/// -/// The primitive pointer points to the mesh primitive for which the tangents in -/// this buffer were computed. When your application loads mesh primitives, it -/// can scan the cgltfTangetBuffer array outputed by cgltf_compute_tangents() to -/// see whether tangents were computed for the mesh primitive. -typedef struct cgltfTangentBuffer { - void* data; // X-coordinate of the first tangent vector. - cgltf_size size_bytes; // Total Size of data in bytes. - cgltf_primitive* primitive; // The primitive these tangents belong to. -} cgltfTangentBuffer; - -/// Compute tangent vectors for normal-mapped mesh primitives missing them. -/// -/// cgltf_options can be zeroed out but must be non-null. -/// -/// cgltf_data is the scene previously loaded by cgltf. -/// -/// out_tangent_buffers is an output array of tangent buffers, one buffer per -/// mesh primitive for which tangents were computed. -/// -/// out_num_tangent_buffers is the number of tangent buffers in the output -/// array. -cgltf_result cgltf_compute_tangents(const cgltf_options*, const cgltf_data*, - cgltfTangentBuffer** out_tangent_buffers, - cgltf_size* out_num_tangent_buffers); - -#endif // CGLTF_TANGENTS_H_INCLUDED__ diff --git a/gfx/contrib/cgltf-tangents/test/CMakeLists.txt b/gfx/contrib/cgltf-tangents/test/CMakeLists.txt deleted file mode 100644 index 422c950..0000000 --- a/gfx/contrib/cgltf-tangents/test/CMakeLists.txt +++ /dev/null @@ -1,11 +0,0 @@ -cmake_minimum_required(VERSION 3.0) - -project (cgltf-test) - -add_executable(cgltf-test - main.c) - -target_link_libraries(cgltf-test - cgltf - cgltf-tangents - -lm) diff --git a/gfx/contrib/cgltf-tangents/test/main.c b/gfx/contrib/cgltf-tangents/test/main.c deleted file mode 100644 index 0d70008..0000000 --- a/gfx/contrib/cgltf-tangents/test/main.c +++ /dev/null @@ -1,86 +0,0 @@ -/* -Copyright 2022 Marc Sunet - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this -list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, -this list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -#include -#define CGLTF_IMPLEMENTATION -#include - -#include - -void print_tangent_buffer(const cgltfTangentBuffer* buffer, int max_vectors) { - printf("Tangent buffer for primitive (%p) (%lu bytes):\n", buffer->primitive, - buffer->size_bytes); - - const float* xyzw = (const float*)buffer->data; - const float* end = (const float*)(buffer->data + buffer->size_bytes); - - for (int i = 0; i < max_vectors && xyzw < end; ++i, xyzw += 4) { - printf("(%3.2f, %3.2f, %3.2f, sign: %3.2f)\n", *xyzw, *(xyzw + 1), - *(xyzw + 2), *(xyzw + 3)); - } - printf("--------------------"); -} - -void usage(const char* argv0) { - fprintf(stderr, "Usage: %s \n", argv0); -} - -int main(int argc, const char** argv) { - cgltf_options options = {0}; - cgltf_data* data = NULL; - - if (argc != 2) { - usage(argv[0]); - return 0; - } - - const char* filepath = argv[1]; - - cgltf_result result = cgltf_parse_file(&options, filepath, &data); - if (result != cgltf_result_success) { - cgltf_free(data); - return 1; - } - - // Must call cgltf_load_buffers() to load buffer data. - result = cgltf_load_buffers(&options, data, filepath); - if (result != cgltf_result_success) { - cgltf_free(data); - return 2; - } - - cgltfTangentBuffer* tangent_buffers = 0; - cgltf_size num_tangent_buffers = 0; - cgltf_compute_tangents(&options, data, &tangent_buffers, - &num_tangent_buffers); - - // cgltf scene not needed beyond this point. - cgltf_free(data); - - for (cgltf_size i = 0; i < num_tangent_buffers; ++i) { - print_tangent_buffer(tangent_buffers, 10); - } - - return 0; -} diff --git a/gfx/contrib/cgltf/CMakeLists.txt b/gfx/contrib/cgltf/CMakeLists.txt deleted file mode 100644 index 0ac840a..0000000 --- a/gfx/contrib/cgltf/CMakeLists.txt +++ /dev/null @@ -1,8 +0,0 @@ -cmake_minimum_required(VERSION 3.16) - -project(cgltf) - -add_library(cgltf INTERFACE) - -target_include_directories(cgltf INTERFACE - ${CMAKE_CURRENT_SOURCE_DIR}) diff --git a/gfx/contrib/cgltf/LICENSE b/gfx/contrib/cgltf/LICENSE deleted file mode 100644 index 0afe8c7..0000000 --- a/gfx/contrib/cgltf/LICENSE +++ /dev/null @@ -1,7 +0,0 @@ -Copyright (c) 2018 Johannes Kuhlmann - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/gfx/contrib/cgltf/README.md b/gfx/contrib/cgltf/README.md deleted file mode 100644 index 3b49d52..0000000 --- a/gfx/contrib/cgltf/README.md +++ /dev/null @@ -1,154 +0,0 @@ -# :diamond_shape_with_a_dot_inside: cgltf -**Single-file/stb-style C glTF loader and writer** - -[![Build Status](https://travis-ci.org/jkuhlmann/cgltf.svg?branch=master)](https://travis-ci.org/jkuhlmann/cgltf) - -Used in: [bgfx](https://github.com/bkaradzic/bgfx), [Filament](https://github.com/google/filament), [meshoptimizer](https://github.com/zeux/meshoptimizer), [raylib](https://github.com/raysan5/raylib), and more! - -## Usage: Loading -Loading from file: -```c -#define CGLTF_IMPLEMENTATION -#include "cgltf.h" - -cgltf_options options = {0}; -cgltf_data* data = NULL; -cgltf_result result = cgltf_parse_file(&options, "scene.gltf", &data); -if (result == cgltf_result_success) -{ - /* TODO make awesome stuff */ - cgltf_free(data); -} -``` - -Loading from memory: -```c -#define CGLTF_IMPLEMENTATION -#include "cgltf.h" - -void* buf; /* Pointer to glb or gltf file data */ -size_t size; /* Size of the file data */ - -cgltf_options options = {0}; -cgltf_data* data = NULL; -cgltf_result result = cgltf_parse(&options, buf, size, &data); -if (result == cgltf_result_success) -{ - /* TODO make awesome stuff */ - cgltf_free(data); -} -``` - -Note that cgltf does not load the contents of extra files such as buffers or images into memory by default. You'll need to read these files yourself using URIs from `data.buffers[]` or `data.images[]` respectively. -For buffer data, you can alternatively call `cgltf_load_buffers`, which will use `FILE*` APIs to open and read buffer files. - -**For more in-depth documentation and a description of the public interface refer to the top of the `cgltf.h` file.** - -## Usage: Writing -When writing glTF data, you need a valid `cgltf_data` structure that represents a valid glTF document. You can construct such a structure yourself or load it using the loader functions described above. The writer functions do not deallocate any memory. So, you either have to do it manually or call `cgltf_free()` if you got the data by loading it from a glTF document. - -Writing to file: -```c -#define CGLTF_IMPLEMENTATION -#define CGLTF_WRITE_IMPLEMENTATION -#include "cgltf_write.h" - -cgltf_options options = {0}; -cgltf_data* data = /* TODO must be valid data */; -cgltf_result result = cgltf_write_file(&options, "out.gltf", data); -if (result != cgltf_result_success) -{ - /* TODO handle error */ -} -``` - -Writing to memory: -```c -#define CGLTF_IMPLEMENTATION -#define CGLTF_WRITE_IMPLEMENTATION -#include "cgltf_write.h" -cgltf_options options = {0}; -cgltf_data* data = /* TODO must be valid data */; - -cgltf_size size = cgltf_write(&options, NULL, 0, data); - -char* buf = malloc(size); - -cgltf_size written = cgltf_write(&options, buf, size, data); -if (written != size) -{ - /* TODO handle error */ -} -``` - -Note that cgltf does not write the contents of extra files such as buffers or images. You'll need to write this data yourself. - -Writing does not yet support "extras" data. - -**For more in-depth documentation and a description of the public interface refer to the top of the `cgltf_write.h` file.** - - -## Features -cgltf supports core glTF 2.0: -- glb (binary files) and gltf (JSON files) -- meshes (including accessors, buffer views, buffers) -- materials (including textures, samplers, images) -- scenes and nodes -- skins -- animations -- cameras -- morph targets -- extras data - -cgltf also supports some glTF extensions: -- KHR_draco_mesh_compression (requires a library like [Google's Draco](https://github.com/google/draco) for decompression though) -- KHR_lights_punctual -- KHR_materials_clearcoat -- KHR_materials_ior -- KHR_materials_pbrSpecularGlossiness -- KHR_materials_specular -- KHR_materials_transmission -- KHR_materials_unlit -- KHR_texture_transform - -cgltf does **not** yet support unlisted extensions. However, unlisted extensions can be accessed via "extensions" member on objects. - -## Building -The easiest approach is to integrate the `cgltf.h` header file into your project. If you are unfamiliar with single-file C libraries (also known as stb-style libraries), this is how it goes: - -1. Include `cgltf.h` where you need the functionality. -1. Have exactly one source file that defines `CGLTF_IMPLEMENTATION` before including `cgltf.h`. -1. Use the cgltf functions as described above. - -Support for writing can be found in a separate file called `cgltf_write.h` (which includes `cgltf.h`). Building it works analogously using the `CGLTF_WRITE_IMPLEMENTATION` define. - -## Contributing -Everyone is welcome to contribute to the library. If you find any problems, you can submit them using [GitHub's issue system](https://github.com/jkuhlmann/cgltf/issues). If you want to contribute code, you should fork the project and then send a pull request. - - -## Dependencies -None. - -C headers being used by implementation: -``` -#include -#include -#include -#include -#include -#include -``` - -Note, this library has a copy of the [JSMN JSON parser](https://github.com/zserge/jsmn) embedded in its source. - -## Testing -There is a Python script in the `test/` folder that retrieves the glTF 2.0 sample files from the glTF-Sample-Models repository (https://github.com/KhronosGroup/glTF-Sample-Models/tree/master/2.0) and runs the library against all gltf and glb files. - -Here's one way to build and run the test: - - cd test ; mkdir build ; cd build ; cmake .. -DCMAKE_BUILD_TYPE=Debug - make -j - cd .. - ./test_all.py - -There is also a llvm-fuzz test in `fuzz/`. See http://llvm.org/docs/LibFuzzer.html for more information. diff --git a/gfx/contrib/cgltf/cgltf.h b/gfx/contrib/cgltf/cgltf.h deleted file mode 100644 index 077cf36..0000000 --- a/gfx/contrib/cgltf/cgltf.h +++ /dev/null @@ -1,5746 +0,0 @@ -/** - * cgltf - a single-file glTF 2.0 parser written in C99. - * - * Version: 1.7 - * - * Website: https://github.com/jkuhlmann/cgltf - * - * Distributed under the MIT License, see notice at the end of this file. - * - * Building: - * Include this file where you need the struct and function - * declarations. Have exactly one source file where you define - * `CGLTF_IMPLEMENTATION` before including this file to get the - * function definitions. - * - * Reference: - * `cgltf_result cgltf_parse(const cgltf_options*, const void*, - * cgltf_size, cgltf_data**)` parses both glTF and GLB data. If - * this function returns `cgltf_result_success`, you have to call - * `cgltf_free()` on the created `cgltf_data*` variable. - * Note that contents of external files for buffers and images are not - * automatically loaded. You'll need to read these files yourself using - * URIs in the `cgltf_data` structure. - * - * `cgltf_options` is the struct passed to `cgltf_parse()` to control - * parts of the parsing process. You can use it to force the file type - * and provide memory allocation as well as file operation callbacks. - * Should be zero-initialized to trigger default behavior. - * - * `cgltf_data` is the struct allocated and filled by `cgltf_parse()`. - * It generally mirrors the glTF format as described by the spec (see - * https://github.com/KhronosGroup/glTF/tree/master/specification/2.0). - * - * `void cgltf_free(cgltf_data*)` frees the allocated `cgltf_data` - * variable. - * - * `cgltf_result cgltf_load_buffers(const cgltf_options*, cgltf_data*, - * const char* gltf_path)` can be optionally called to open and read buffer - * files using the `FILE*` APIs. The `gltf_path` argument is the path to - * the original glTF file, which allows the parser to resolve the path to - * buffer files. - * - * `cgltf_result cgltf_load_buffer_base64(const cgltf_options* options, - * cgltf_size size, const char* base64, void** out_data)` decodes - * base64-encoded data content. Used internally by `cgltf_load_buffers()` - * and may be useful if you're not dealing with normal files. - * - * `cgltf_result cgltf_parse_file(const cgltf_options* options, const - * char* path, cgltf_data** out_data)` can be used to open the given - * file using `FILE*` APIs and parse the data using `cgltf_parse()`. - * - * `cgltf_result cgltf_validate(cgltf_data*)` can be used to do additional - * checks to make sure the parsed glTF data is valid. - * - * `cgltf_node_transform_local` converts the translation / rotation / scale properties of a node - * into a mat4. - * - * `cgltf_node_transform_world` calls `cgltf_node_transform_local` on every ancestor in order - * to compute the root-to-node transformation. - * - * `cgltf_accessor_unpack_floats` reads in the data from an accessor, applies sparse data (if any), - * and converts them to floating point. Assumes that `cgltf_load_buffers` has already been called. - * By passing null for the output pointer, users can find out how many floats are required in the - * output buffer. - * - * `cgltf_accessor_num_components` is a tiny utility that tells you the dimensionality of - * a certain accessor type. This can be used before `cgltf_accessor_unpack_floats` to help allocate - * the necessary amount of memory. - * - * `cgltf_accessor_read_float` reads a certain element from a non-sparse accessor and converts it to - * floating point, assuming that `cgltf_load_buffers` has already been called. The passed-in element - * size is the number of floats in the output buffer, which should be in the range [1, 16]. Returns - * false if the passed-in element_size is too small, or if the accessor is sparse. - * - * `cgltf_accessor_read_uint` is similar to its floating-point counterpart, but limited to reading - * vector types and does not support matrix types. The passed-in element size is the number of uints - * in the output buffer, which should be in the range [1, 4]. Returns false if the passed-in - * element_size is too small, or if the accessor is sparse. - * - * `cgltf_accessor_read_index` is similar to its floating-point counterpart, but it returns size_t - * and only works with single-component data types. - * - * `cgltf_result cgltf_copy_extras_json(const cgltf_data*, const cgltf_extras*, - * char* dest, cgltf_size* dest_size)` allows users to retrieve the "extras" data that - * can be attached to many glTF objects (which can be arbitrary JSON data). The - * `cgltf_extras` struct stores the offsets of the start and end of the extras JSON data - * as it appears in the complete glTF JSON data. This function copies the extras data - * into the provided buffer. If `dest` is NULL, the length of the data is written into - * `dest_size`. You can then parse this data using your own JSON parser - * or, if you've included the cgltf implementation using the integrated JSMN JSON parser. - */ -#ifndef CGLTF_H_INCLUDED__ -#define CGLTF_H_INCLUDED__ - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -typedef size_t cgltf_size; -typedef float cgltf_float; -typedef int cgltf_int; -typedef unsigned int cgltf_uint; -typedef int cgltf_bool; - -typedef enum cgltf_file_type -{ - cgltf_file_type_invalid, - cgltf_file_type_gltf, - cgltf_file_type_glb, -} cgltf_file_type; - -typedef enum cgltf_result -{ - cgltf_result_success, - cgltf_result_data_too_short, - cgltf_result_unknown_format, - cgltf_result_invalid_json, - cgltf_result_invalid_gltf, - cgltf_result_invalid_options, - cgltf_result_file_not_found, - cgltf_result_io_error, - cgltf_result_out_of_memory, - cgltf_result_legacy_gltf, -} cgltf_result; - -typedef struct cgltf_memory_options -{ - void* (*alloc)(void* user, cgltf_size size); - void (*free) (void* user, void* ptr); - void* user_data; -} cgltf_memory_options; - -typedef struct cgltf_file_options -{ - cgltf_result(*read)(const struct cgltf_memory_options* memory_options, const struct cgltf_file_options* file_options, const char* path, cgltf_size* size, void** data); - void (*release)(const struct cgltf_memory_options* memory_options, const struct cgltf_file_options* file_options, void* data); - void* user_data; -} cgltf_file_options; - -typedef struct cgltf_options -{ - cgltf_file_type type; /* invalid == auto detect */ - cgltf_size json_token_count; /* 0 == auto */ - cgltf_memory_options memory; - cgltf_file_options file; -} cgltf_options; - -typedef enum cgltf_buffer_view_type -{ - cgltf_buffer_view_type_invalid, - cgltf_buffer_view_type_indices, - cgltf_buffer_view_type_vertices, -} cgltf_buffer_view_type; - -typedef enum cgltf_attribute_type -{ - cgltf_attribute_type_invalid, - cgltf_attribute_type_position, - cgltf_attribute_type_normal, - cgltf_attribute_type_tangent, - cgltf_attribute_type_texcoord, - cgltf_attribute_type_color, - cgltf_attribute_type_joints, - cgltf_attribute_type_weights, -} cgltf_attribute_type; - -typedef enum cgltf_component_type -{ - cgltf_component_type_invalid, - cgltf_component_type_r_8, /* BYTE */ - cgltf_component_type_r_8u, /* UNSIGNED_BYTE */ - cgltf_component_type_r_16, /* SHORT */ - cgltf_component_type_r_16u, /* UNSIGNED_SHORT */ - cgltf_component_type_r_32u, /* UNSIGNED_INT */ - cgltf_component_type_r_32f, /* FLOAT */ -} cgltf_component_type; - -typedef enum cgltf_type -{ - cgltf_type_invalid, - cgltf_type_scalar, - cgltf_type_vec2, - cgltf_type_vec3, - cgltf_type_vec4, - cgltf_type_mat2, - cgltf_type_mat3, - cgltf_type_mat4, -} cgltf_type; - -typedef enum cgltf_primitive_type -{ - cgltf_primitive_type_points, - cgltf_primitive_type_lines, - cgltf_primitive_type_line_loop, - cgltf_primitive_type_line_strip, - cgltf_primitive_type_triangles, - cgltf_primitive_type_triangle_strip, - cgltf_primitive_type_triangle_fan, -} cgltf_primitive_type; - -typedef enum cgltf_alpha_mode -{ - cgltf_alpha_mode_opaque, - cgltf_alpha_mode_mask, - cgltf_alpha_mode_blend, -} cgltf_alpha_mode; - -typedef enum cgltf_animation_path_type { - cgltf_animation_path_type_invalid, - cgltf_animation_path_type_translation, - cgltf_animation_path_type_rotation, - cgltf_animation_path_type_scale, - cgltf_animation_path_type_weights, -} cgltf_animation_path_type; - -typedef enum cgltf_interpolation_type { - cgltf_interpolation_type_linear, - cgltf_interpolation_type_step, - cgltf_interpolation_type_cubic_spline, -} cgltf_interpolation_type; - -typedef enum cgltf_camera_type { - cgltf_camera_type_invalid, - cgltf_camera_type_perspective, - cgltf_camera_type_orthographic, -} cgltf_camera_type; - -typedef enum cgltf_light_type { - cgltf_light_type_invalid, - cgltf_light_type_directional, - cgltf_light_type_point, - cgltf_light_type_spot, -} cgltf_light_type; - -typedef struct cgltf_extras { - cgltf_size start_offset; - cgltf_size end_offset; -} cgltf_extras; - -typedef struct cgltf_extension { - char* name; - char* data; -} cgltf_extension; - -typedef struct cgltf_buffer -{ - cgltf_size size; - char* uri; - void* data; /* loaded by cgltf_load_buffers */ - cgltf_extras extras; - cgltf_size extensions_count; - cgltf_extension* extensions; -} cgltf_buffer; - -typedef struct cgltf_buffer_view -{ - cgltf_buffer* buffer; - cgltf_size offset; - cgltf_size size; - cgltf_size stride; /* 0 == automatically determined by accessor */ - cgltf_buffer_view_type type; - cgltf_extras extras; - cgltf_size extensions_count; - cgltf_extension* extensions; -} cgltf_buffer_view; - -typedef struct cgltf_accessor_sparse -{ - cgltf_size count; - cgltf_buffer_view* indices_buffer_view; - cgltf_size indices_byte_offset; - cgltf_component_type indices_component_type; - cgltf_buffer_view* values_buffer_view; - cgltf_size values_byte_offset; - cgltf_extras extras; - cgltf_extras indices_extras; - cgltf_extras values_extras; - cgltf_size extensions_count; - cgltf_extension* extensions; - cgltf_size indices_extensions_count; - cgltf_extension* indices_extensions; - cgltf_size values_extensions_count; - cgltf_extension* values_extensions; -} cgltf_accessor_sparse; - -typedef struct cgltf_accessor -{ - cgltf_component_type component_type; - cgltf_bool normalized; - cgltf_type type; - cgltf_size offset; - cgltf_size count; - cgltf_size stride; - cgltf_buffer_view* buffer_view; - cgltf_bool has_min; - cgltf_float min[16]; - cgltf_bool has_max; - cgltf_float max[16]; - cgltf_bool is_sparse; - cgltf_accessor_sparse sparse; - cgltf_extras extras; - cgltf_size extensions_count; - cgltf_extension* extensions; -} cgltf_accessor; - -typedef struct cgltf_attribute -{ - char* name; - cgltf_attribute_type type; - cgltf_int index; - cgltf_accessor* data; -} cgltf_attribute; - -typedef struct cgltf_image -{ - char* name; - char* uri; - cgltf_buffer_view* buffer_view; - char* mime_type; - cgltf_extras extras; - cgltf_size extensions_count; - cgltf_extension* extensions; -} cgltf_image; - -typedef struct cgltf_sampler -{ - cgltf_int mag_filter; - cgltf_int min_filter; - cgltf_int wrap_s; - cgltf_int wrap_t; - cgltf_extras extras; - cgltf_size extensions_count; - cgltf_extension* extensions; -} cgltf_sampler; - -typedef struct cgltf_texture -{ - char* name; - cgltf_image* image; - cgltf_sampler* sampler; - cgltf_extras extras; - cgltf_size extensions_count; - cgltf_extension* extensions; -} cgltf_texture; - -typedef struct cgltf_texture_transform -{ - cgltf_float offset[2]; - cgltf_float rotation; - cgltf_float scale[2]; - cgltf_int texcoord; -} cgltf_texture_transform; - -typedef struct cgltf_texture_view -{ - cgltf_texture* texture; - cgltf_int texcoord; - cgltf_float scale; /* equivalent to strength for occlusion_texture */ - cgltf_bool has_transform; - cgltf_texture_transform transform; - cgltf_extras extras; - cgltf_size extensions_count; - cgltf_extension* extensions; -} cgltf_texture_view; - -typedef struct cgltf_pbr_metallic_roughness -{ - cgltf_texture_view base_color_texture; - cgltf_texture_view metallic_roughness_texture; - - cgltf_float base_color_factor[4]; - cgltf_float metallic_factor; - cgltf_float roughness_factor; - - cgltf_extras extras; -} cgltf_pbr_metallic_roughness; - -typedef struct cgltf_pbr_specular_glossiness -{ - cgltf_texture_view diffuse_texture; - cgltf_texture_view specular_glossiness_texture; - - cgltf_float diffuse_factor[4]; - cgltf_float specular_factor[3]; - cgltf_float glossiness_factor; -} cgltf_pbr_specular_glossiness; - -typedef struct cgltf_clearcoat -{ - cgltf_texture_view clearcoat_texture; - cgltf_texture_view clearcoat_roughness_texture; - cgltf_texture_view clearcoat_normal_texture; - - cgltf_float clearcoat_factor; - cgltf_float clearcoat_roughness_factor; -} cgltf_clearcoat; - -typedef struct cgltf_transmission -{ - cgltf_texture_view transmission_texture; - cgltf_float transmission_factor; -} cgltf_transmission; - -typedef struct cgltf_ior -{ - cgltf_float ior; -} cgltf_ior; - -typedef struct cgltf_specular -{ - cgltf_texture_view specular_texture; - cgltf_float specular_color_factor[3]; - cgltf_float specular_factor; -} cgltf_specular; - -typedef struct cgltf_material -{ - char* name; - cgltf_bool has_pbr_metallic_roughness; - cgltf_bool has_pbr_specular_glossiness; - cgltf_bool has_clearcoat; - cgltf_bool has_transmission; - cgltf_bool has_ior; - cgltf_bool has_specular; - cgltf_pbr_metallic_roughness pbr_metallic_roughness; - cgltf_pbr_specular_glossiness pbr_specular_glossiness; - cgltf_clearcoat clearcoat; - cgltf_ior ior; - cgltf_specular specular; - cgltf_transmission transmission; - cgltf_texture_view normal_texture; - cgltf_texture_view occlusion_texture; - cgltf_texture_view emissive_texture; - cgltf_float emissive_factor[3]; - cgltf_alpha_mode alpha_mode; - cgltf_float alpha_cutoff; - cgltf_bool double_sided; - cgltf_bool unlit; - cgltf_extras extras; - cgltf_size extensions_count; - cgltf_extension* extensions; -} cgltf_material; - -typedef struct cgltf_morph_target { - cgltf_attribute* attributes; - cgltf_size attributes_count; -} cgltf_morph_target; - -typedef struct cgltf_draco_mesh_compression { - cgltf_buffer_view* buffer_view; - cgltf_attribute* attributes; - cgltf_size attributes_count; -} cgltf_draco_mesh_compression; - -typedef struct cgltf_primitive { - cgltf_primitive_type type; - cgltf_accessor* indices; - cgltf_material* material; - cgltf_attribute* attributes; - cgltf_size attributes_count; - cgltf_morph_target* targets; - cgltf_size targets_count; - cgltf_extras extras; - cgltf_bool has_draco_mesh_compression; - cgltf_draco_mesh_compression draco_mesh_compression; - cgltf_size extensions_count; - cgltf_extension* extensions; -} cgltf_primitive; - -typedef struct cgltf_mesh { - char* name; - cgltf_primitive* primitives; - cgltf_size primitives_count; - cgltf_float* weights; - cgltf_size weights_count; - char** target_names; - cgltf_size target_names_count; - cgltf_extras extras; - cgltf_size extensions_count; - cgltf_extension* extensions; -} cgltf_mesh; - -typedef struct cgltf_node cgltf_node; - -typedef struct cgltf_skin { - char* name; - cgltf_node** joints; - cgltf_size joints_count; - cgltf_node* skeleton; - cgltf_accessor* inverse_bind_matrices; - cgltf_extras extras; - cgltf_size extensions_count; - cgltf_extension* extensions; -} cgltf_skin; - -typedef struct cgltf_camera_perspective { - cgltf_float aspect_ratio; - cgltf_float yfov; - cgltf_float zfar; - cgltf_float znear; - cgltf_extras extras; -} cgltf_camera_perspective; - -typedef struct cgltf_camera_orthographic { - cgltf_float xmag; - cgltf_float ymag; - cgltf_float zfar; - cgltf_float znear; - cgltf_extras extras; -} cgltf_camera_orthographic; - -typedef struct cgltf_camera { - char* name; - cgltf_camera_type type; - union { - cgltf_camera_perspective perspective; - cgltf_camera_orthographic orthographic; - } data; - cgltf_extras extras; - cgltf_size extensions_count; - cgltf_extension* extensions; -} cgltf_camera; - -typedef struct cgltf_light { - char* name; - cgltf_float color[3]; - cgltf_float intensity; - cgltf_light_type type; - cgltf_float range; - cgltf_float spot_inner_cone_angle; - cgltf_float spot_outer_cone_angle; -} cgltf_light; - -struct cgltf_node { - char* name; - cgltf_node* parent; - cgltf_node** children; - cgltf_size children_count; - cgltf_skin* skin; - cgltf_mesh* mesh; - cgltf_camera* camera; - cgltf_light* light; - cgltf_float* weights; - cgltf_size weights_count; - cgltf_bool has_translation; - cgltf_bool has_rotation; - cgltf_bool has_scale; - cgltf_bool has_matrix; - cgltf_float translation[3]; - cgltf_float rotation[4]; - cgltf_float scale[3]; - cgltf_float matrix[16]; - cgltf_extras extras; - cgltf_size extensions_count; - cgltf_extension* extensions; -}; - -typedef struct cgltf_scene { - char* name; - cgltf_node** nodes; - cgltf_size nodes_count; - cgltf_extras extras; - cgltf_size extensions_count; - cgltf_extension* extensions; -} cgltf_scene; - -typedef struct cgltf_animation_sampler { - cgltf_accessor* input; - cgltf_accessor* output; - cgltf_interpolation_type interpolation; - cgltf_extras extras; - cgltf_size extensions_count; - cgltf_extension* extensions; -} cgltf_animation_sampler; - -typedef struct cgltf_animation_channel { - cgltf_animation_sampler* sampler; - cgltf_node* target_node; - cgltf_animation_path_type target_path; - cgltf_extras extras; - cgltf_size extensions_count; - cgltf_extension* extensions; -} cgltf_animation_channel; - -typedef struct cgltf_animation { - char* name; - cgltf_animation_sampler* samplers; - cgltf_size samplers_count; - cgltf_animation_channel* channels; - cgltf_size channels_count; - cgltf_extras extras; - cgltf_size extensions_count; - cgltf_extension* extensions; -} cgltf_animation; - -typedef struct cgltf_asset { - char* copyright; - char* generator; - char* version; - char* min_version; - cgltf_extras extras; - cgltf_size extensions_count; - cgltf_extension* extensions; -} cgltf_asset; - -typedef struct cgltf_data -{ - cgltf_file_type file_type; - void* file_data; - - cgltf_asset asset; - - cgltf_mesh* meshes; - cgltf_size meshes_count; - - cgltf_material* materials; - cgltf_size materials_count; - - cgltf_accessor* accessors; - cgltf_size accessors_count; - - cgltf_buffer_view* buffer_views; - cgltf_size buffer_views_count; - - cgltf_buffer* buffers; - cgltf_size buffers_count; - - cgltf_image* images; - cgltf_size images_count; - - cgltf_texture* textures; - cgltf_size textures_count; - - cgltf_sampler* samplers; - cgltf_size samplers_count; - - cgltf_skin* skins; - cgltf_size skins_count; - - cgltf_camera* cameras; - cgltf_size cameras_count; - - cgltf_light* lights; - cgltf_size lights_count; - - cgltf_node* nodes; - cgltf_size nodes_count; - - cgltf_scene* scenes; - cgltf_size scenes_count; - - cgltf_scene* scene; - - cgltf_animation* animations; - cgltf_size animations_count; - - cgltf_extras extras; - - cgltf_size data_extensions_count; - cgltf_extension* data_extensions; - - char** extensions_used; - cgltf_size extensions_used_count; - - char** extensions_required; - cgltf_size extensions_required_count; - - const char* json; - cgltf_size json_size; - - const void* bin; - cgltf_size bin_size; - - cgltf_memory_options memory; - cgltf_file_options file; -} cgltf_data; - -cgltf_result cgltf_parse( - const cgltf_options* options, - const void* data, - cgltf_size size, - cgltf_data** out_data); - -cgltf_result cgltf_parse_file( - const cgltf_options* options, - const char* path, - cgltf_data** out_data); - -cgltf_result cgltf_load_buffers( - const cgltf_options* options, - cgltf_data* data, - const char* gltf_path); - -cgltf_result cgltf_load_buffer_base64(const cgltf_options* options, cgltf_size size, const char* base64, void** out_data); - -void cgltf_decode_uri(char* uri); - -cgltf_result cgltf_validate(cgltf_data* data); - -void cgltf_free(cgltf_data* data); - -void cgltf_node_transform_local(const cgltf_node* node, cgltf_float* out_matrix); -void cgltf_node_transform_world(const cgltf_node* node, cgltf_float* out_matrix); - -cgltf_bool cgltf_accessor_read_float(const cgltf_accessor* accessor, cgltf_size index, cgltf_float* out, cgltf_size element_size); -cgltf_bool cgltf_accessor_read_uint(const cgltf_accessor* accessor, cgltf_size index, cgltf_uint* out, cgltf_size element_size); -cgltf_size cgltf_accessor_read_index(const cgltf_accessor* accessor, cgltf_size index); - -cgltf_size cgltf_num_components(cgltf_type type); - -cgltf_size cgltf_accessor_unpack_floats(const cgltf_accessor* accessor, cgltf_float* out, cgltf_size float_count); - -cgltf_result cgltf_copy_extras_json(const cgltf_data* data, const cgltf_extras* extras, char* dest, cgltf_size* dest_size); - -#ifdef __cplusplus -} -#endif - -#endif /* #ifndef CGLTF_H_INCLUDED__ */ - -/* - * - * Stop now, if you are only interested in the API. - * Below, you find the implementation. - * - */ - -#if defined(__INTELLISENSE__) || defined(__JETBRAINS_IDE__) -/* This makes MSVC/CLion intellisense work. */ -#define CGLTF_IMPLEMENTATION -#endif - -#ifdef CGLTF_IMPLEMENTATION - -#include /* For uint8_t, uint32_t */ -#include /* For strncpy */ -#include /* For fopen */ -#include /* For UINT_MAX etc */ - -#if !defined(CGLTF_MALLOC) || !defined(CGLTF_FREE) || !defined(CGLTF_ATOI) || !defined(CGLTF_ATOF) -#include /* For malloc, free, atoi, atof */ -#endif - -/* JSMN_PARENT_LINKS is necessary to make parsing large structures linear in input size */ -#define JSMN_PARENT_LINKS - -/* JSMN_STRICT is necessary to reject invalid JSON documents */ -#define JSMN_STRICT - -/* - * -- jsmn.h start -- - * Source: https://github.com/zserge/jsmn - * License: MIT - */ -typedef enum { - JSMN_UNDEFINED = 0, - JSMN_OBJECT = 1, - JSMN_ARRAY = 2, - JSMN_STRING = 3, - JSMN_PRIMITIVE = 4 -} jsmntype_t; -enum jsmnerr { - /* Not enough tokens were provided */ - JSMN_ERROR_NOMEM = -1, - /* Invalid character inside JSON string */ - JSMN_ERROR_INVAL = -2, - /* The string is not a full JSON packet, more bytes expected */ - JSMN_ERROR_PART = -3 -}; -typedef struct { - jsmntype_t type; - int start; - int end; - int size; -#ifdef JSMN_PARENT_LINKS - int parent; -#endif -} jsmntok_t; -typedef struct { - unsigned int pos; /* offset in the JSON string */ - unsigned int toknext; /* next token to allocate */ - int toksuper; /* superior token node, e.g parent object or array */ -} jsmn_parser; -static void jsmn_init(jsmn_parser *parser); -static int jsmn_parse(jsmn_parser *parser, const char *js, size_t len, jsmntok_t *tokens, size_t num_tokens); -/* - * -- jsmn.h end -- - */ - - -static const cgltf_size GlbHeaderSize = 12; -static const cgltf_size GlbChunkHeaderSize = 8; -static const uint32_t GlbVersion = 2; -static const uint32_t GlbMagic = 0x46546C67; -static const uint32_t GlbMagicJsonChunk = 0x4E4F534A; -static const uint32_t GlbMagicBinChunk = 0x004E4942; - -#ifndef CGLTF_MALLOC -#define CGLTF_MALLOC(size) malloc(size) -#endif -#ifndef CGLTF_FREE -#define CGLTF_FREE(ptr) free(ptr) -#endif -#ifndef CGLTF_ATOI -#define CGLTF_ATOI(str) atoi(str) -#endif -#ifndef CGLTF_ATOF -#define CGLTF_ATOF(str) atof(str) -#endif - -static void* cgltf_default_alloc(void* user, cgltf_size size) -{ - (void)user; - return CGLTF_MALLOC(size); -} - -static void cgltf_default_free(void* user, void* ptr) -{ - (void)user; - CGLTF_FREE(ptr); -} - -static void* cgltf_calloc(cgltf_options* options, size_t element_size, cgltf_size count) -{ - if (SIZE_MAX / element_size < count) - { - return NULL; - } - void* result = options->memory.alloc(options->memory.user_data, element_size * count); - if (!result) - { - return NULL; - } - memset(result, 0, element_size * count); - return result; -} - -static cgltf_result cgltf_default_file_read(const struct cgltf_memory_options* memory_options, const struct cgltf_file_options* file_options, const char* path, cgltf_size* size, void** data) -{ - (void)file_options; - void* (*memory_alloc)(void*, cgltf_size) = memory_options->alloc ? memory_options->alloc : &cgltf_default_alloc; - void (*memory_free)(void*, void*) = memory_options->free ? memory_options->free : &cgltf_default_free; - - FILE* file = fopen(path, "rb"); - if (!file) - { - return cgltf_result_file_not_found; - } - - cgltf_size file_size = size ? *size : 0; - - if (file_size == 0) - { - fseek(file, 0, SEEK_END); - - long length = ftell(file); - if (length < 0) - { - fclose(file); - return cgltf_result_io_error; - } - - fseek(file, 0, SEEK_SET); - file_size = (cgltf_size)length; - } - - char* file_data = (char*)memory_alloc(memory_options->user_data, file_size); - if (!file_data) - { - fclose(file); - return cgltf_result_out_of_memory; - } - - cgltf_size read_size = fread(file_data, 1, file_size, file); - - fclose(file); - - if (read_size != file_size) - { - memory_free(memory_options->user_data, file_data); - return cgltf_result_io_error; - } - - if (size) - { - *size = file_size; - } - if (data) - { - *data = file_data; - } - - return cgltf_result_success; -} - -static void cgltf_default_file_release(const struct cgltf_memory_options* memory_options, const struct cgltf_file_options* file_options, void* data) -{ - (void)file_options; - void (*memfree)(void*, void*) = memory_options->free ? memory_options->free : &cgltf_default_free; - memfree(memory_options->user_data, data); -} - -static cgltf_result cgltf_parse_json(cgltf_options* options, const uint8_t* json_chunk, cgltf_size size, cgltf_data** out_data); - -cgltf_result cgltf_parse(const cgltf_options* options, const void* data, cgltf_size size, cgltf_data** out_data) -{ - if (size < GlbHeaderSize) - { - return cgltf_result_data_too_short; - } - - if (options == NULL) - { - return cgltf_result_invalid_options; - } - - cgltf_options fixed_options = *options; - if (fixed_options.memory.alloc == NULL) - { - fixed_options.memory.alloc = &cgltf_default_alloc; - } - if (fixed_options.memory.free == NULL) - { - fixed_options.memory.free = &cgltf_default_free; - } - - uint32_t tmp; - // Magic - memcpy(&tmp, data, 4); - if (tmp != GlbMagic) - { - if (fixed_options.type == cgltf_file_type_invalid) - { - fixed_options.type = cgltf_file_type_gltf; - } - else if (fixed_options.type == cgltf_file_type_glb) - { - return cgltf_result_unknown_format; - } - } - - if (fixed_options.type == cgltf_file_type_gltf) - { - cgltf_result json_result = cgltf_parse_json(&fixed_options, (const uint8_t*)data, size, out_data); - if (json_result != cgltf_result_success) - { - return json_result; - } - - (*out_data)->file_type = cgltf_file_type_gltf; - - return cgltf_result_success; - } - - const uint8_t* ptr = (const uint8_t*)data; - // Version - memcpy(&tmp, ptr + 4, 4); - uint32_t version = tmp; - if (version != GlbVersion) - { - return version < GlbVersion ? cgltf_result_legacy_gltf : cgltf_result_unknown_format; - } - - // Total length - memcpy(&tmp, ptr + 8, 4); - if (tmp > size) - { - return cgltf_result_data_too_short; - } - - const uint8_t* json_chunk = ptr + GlbHeaderSize; - - if (GlbHeaderSize + GlbChunkHeaderSize > size) - { - return cgltf_result_data_too_short; - } - - // JSON chunk: length - uint32_t json_length; - memcpy(&json_length, json_chunk, 4); - if (GlbHeaderSize + GlbChunkHeaderSize + json_length > size) - { - return cgltf_result_data_too_short; - } - - // JSON chunk: magic - memcpy(&tmp, json_chunk + 4, 4); - if (tmp != GlbMagicJsonChunk) - { - return cgltf_result_unknown_format; - } - - json_chunk += GlbChunkHeaderSize; - - const void* bin = 0; - cgltf_size bin_size = 0; - - if (GlbHeaderSize + GlbChunkHeaderSize + json_length + GlbChunkHeaderSize <= size) - { - // We can read another chunk - const uint8_t* bin_chunk = json_chunk + json_length; - - // Bin chunk: length - uint32_t bin_length; - memcpy(&bin_length, bin_chunk, 4); - if (GlbHeaderSize + GlbChunkHeaderSize + json_length + GlbChunkHeaderSize + bin_length > size) - { - return cgltf_result_data_too_short; - } - - // Bin chunk: magic - memcpy(&tmp, bin_chunk + 4, 4); - if (tmp != GlbMagicBinChunk) - { - return cgltf_result_unknown_format; - } - - bin_chunk += GlbChunkHeaderSize; - - bin = bin_chunk; - bin_size = bin_length; - } - - cgltf_result json_result = cgltf_parse_json(&fixed_options, json_chunk, json_length, out_data); - if (json_result != cgltf_result_success) - { - return json_result; - } - - (*out_data)->file_type = cgltf_file_type_glb; - (*out_data)->bin = bin; - (*out_data)->bin_size = bin_size; - - return cgltf_result_success; -} - -cgltf_result cgltf_parse_file(const cgltf_options* options, const char* path, cgltf_data** out_data) -{ - if (options == NULL) - { - return cgltf_result_invalid_options; - } - - void (*memory_free)(void*, void*) = options->memory.free ? options->memory.free : &cgltf_default_free; - cgltf_result (*file_read)(const struct cgltf_memory_options*, const struct cgltf_file_options*, const char*, cgltf_size*, void**) = options->file.read ? options->file.read : &cgltf_default_file_read; - - void* file_data = NULL; - cgltf_size file_size = 0; - cgltf_result result = file_read(&options->memory, &options->file, path, &file_size, &file_data); - if (result != cgltf_result_success) - { - return result; - } - - result = cgltf_parse(options, file_data, file_size, out_data); - - if (result != cgltf_result_success) - { - memory_free(options->memory.user_data, file_data); - return result; - } - - (*out_data)->file_data = file_data; - - return cgltf_result_success; -} - -static void cgltf_combine_paths(char* path, const char* base, const char* uri) -{ - const char* s0 = strrchr(base, '/'); - const char* s1 = strrchr(base, '\\'); - const char* slash = s0 ? (s1 && s1 > s0 ? s1 : s0) : s1; - - if (slash) - { - size_t prefix = slash - base + 1; - - strncpy(path, base, prefix); - strcpy(path + prefix, uri); - } - else - { - strcpy(path, uri); - } -} - -static cgltf_result cgltf_load_buffer_file(const cgltf_options* options, cgltf_size size, const char* uri, const char* gltf_path, void** out_data) -{ - void* (*memory_alloc)(void*, cgltf_size) = options->memory.alloc ? options->memory.alloc : &cgltf_default_alloc; - void (*memory_free)(void*, void*) = options->memory.free ? options->memory.free : &cgltf_default_free; - cgltf_result (*file_read)(const struct cgltf_memory_options*, const struct cgltf_file_options*, const char*, cgltf_size*, void**) = options->file.read ? options->file.read : &cgltf_default_file_read; - - char* path = (char*)memory_alloc(options->memory.user_data, strlen(uri) + strlen(gltf_path) + 1); - if (!path) - { - return cgltf_result_out_of_memory; - } - - cgltf_combine_paths(path, gltf_path, uri); - - // after combining, the tail of the resulting path is a uri; decode_uri converts it into path - cgltf_decode_uri(path + strlen(path) - strlen(uri)); - - void* file_data = NULL; - cgltf_result result = file_read(&options->memory, &options->file, path, &size, &file_data); - - memory_free(options->memory.user_data, path); - - *out_data = (result == cgltf_result_success) ? file_data : NULL; - - return result; -} - -cgltf_result cgltf_load_buffer_base64(const cgltf_options* options, cgltf_size size, const char* base64, void** out_data) -{ - void* (*memory_alloc)(void*, cgltf_size) = options->memory.alloc ? options->memory.alloc : &cgltf_default_alloc; - void (*memory_free)(void*, void*) = options->memory.free ? options->memory.free : &cgltf_default_free; - - unsigned char* data = (unsigned char*)memory_alloc(options->memory.user_data, size); - if (!data) - { - return cgltf_result_out_of_memory; - } - - unsigned int buffer = 0; - unsigned int buffer_bits = 0; - - for (cgltf_size i = 0; i < size; ++i) - { - while (buffer_bits < 8) - { - char ch = *base64++; - - int index = - (unsigned)(ch - 'A') < 26 ? (ch - 'A') : - (unsigned)(ch - 'a') < 26 ? (ch - 'a') + 26 : - (unsigned)(ch - '0') < 10 ? (ch - '0') + 52 : - ch == '+' ? 62 : - ch == '/' ? 63 : - -1; - - if (index < 0) - { - memory_free(options->memory.user_data, data); - return cgltf_result_io_error; - } - - buffer = (buffer << 6) | index; - buffer_bits += 6; - } - - data[i] = (unsigned char)(buffer >> (buffer_bits - 8)); - buffer_bits -= 8; - } - - *out_data = data; - - return cgltf_result_success; -} - -static int cgltf_unhex(char ch) -{ - return - (unsigned)(ch - '0') < 10 ? (ch - '0') : - (unsigned)(ch - 'A') < 6 ? (ch - 'A') + 10 : - (unsigned)(ch - 'a') < 6 ? (ch - 'a') + 10 : - -1; -} - -void cgltf_decode_uri(char* uri) -{ - char* write = uri; - char* i = uri; - - while (*i) - { - if (*i == '%') - { - int ch1 = cgltf_unhex(i[1]); - - if (ch1 >= 0) - { - int ch2 = cgltf_unhex(i[2]); - - if (ch2 >= 0) - { - *write++ = (char)(ch1 * 16 + ch2); - i += 3; - continue; - } - } - } - - *write++ = *i++; - } - - *write = 0; -} - -cgltf_result cgltf_load_buffers(const cgltf_options* options, cgltf_data* data, const char* gltf_path) -{ - if (options == NULL) - { - return cgltf_result_invalid_options; - } - - if (data->buffers_count && data->buffers[0].data == NULL && data->buffers[0].uri == NULL && data->bin) - { - if (data->bin_size < data->buffers[0].size) - { - return cgltf_result_data_too_short; - } - - data->buffers[0].data = (void*)data->bin; - } - - for (cgltf_size i = 0; i < data->buffers_count; ++i) - { - if (data->buffers[i].data) - { - continue; - } - - const char* uri = data->buffers[i].uri; - - if (uri == NULL) - { - continue; - } - - if (strncmp(uri, "data:", 5) == 0) - { - const char* comma = strchr(uri, ','); - - if (comma && comma - uri >= 7 && strncmp(comma - 7, ";base64", 7) == 0) - { - cgltf_result res = cgltf_load_buffer_base64(options, data->buffers[i].size, comma + 1, &data->buffers[i].data); - - if (res != cgltf_result_success) - { - return res; - } - } - else - { - return cgltf_result_unknown_format; - } - } - else if (strstr(uri, "://") == NULL && gltf_path) - { - cgltf_result res = cgltf_load_buffer_file(options, data->buffers[i].size, uri, gltf_path, &data->buffers[i].data); - - if (res != cgltf_result_success) - { - return res; - } - } - else - { - return cgltf_result_unknown_format; - } - } - - return cgltf_result_success; -} - -static cgltf_size cgltf_calc_size(cgltf_type type, cgltf_component_type component_type); - -static cgltf_size cgltf_calc_index_bound(cgltf_buffer_view* buffer_view, cgltf_size offset, cgltf_component_type component_type, cgltf_size count) -{ - char* data = (char*)buffer_view->buffer->data + offset + buffer_view->offset; - cgltf_size bound = 0; - - switch (component_type) - { - case cgltf_component_type_r_8u: - for (size_t i = 0; i < count; ++i) - { - cgltf_size v = ((unsigned char*)data)[i]; - bound = bound > v ? bound : v; - } - break; - - case cgltf_component_type_r_16u: - for (size_t i = 0; i < count; ++i) - { - cgltf_size v = ((unsigned short*)data)[i]; - bound = bound > v ? bound : v; - } - break; - - case cgltf_component_type_r_32u: - for (size_t i = 0; i < count; ++i) - { - cgltf_size v = ((unsigned int*)data)[i]; - bound = bound > v ? bound : v; - } - break; - - default: - ; - } - - return bound; -} - -cgltf_result cgltf_validate(cgltf_data* data) -{ - for (cgltf_size i = 0; i < data->accessors_count; ++i) - { - cgltf_accessor* accessor = &data->accessors[i]; - - cgltf_size element_size = cgltf_calc_size(accessor->type, accessor->component_type); - - if (accessor->buffer_view) - { - cgltf_size req_size = accessor->offset + accessor->stride * (accessor->count - 1) + element_size; - - if (accessor->buffer_view->size < req_size) - { - return cgltf_result_data_too_short; - } - } - - if (accessor->is_sparse) - { - cgltf_accessor_sparse* sparse = &accessor->sparse; - - cgltf_size indices_component_size = cgltf_calc_size(cgltf_type_scalar, sparse->indices_component_type); - cgltf_size indices_req_size = sparse->indices_byte_offset + indices_component_size * sparse->count; - cgltf_size values_req_size = sparse->values_byte_offset + element_size * sparse->count; - - if (sparse->indices_buffer_view->size < indices_req_size || - sparse->values_buffer_view->size < values_req_size) - { - return cgltf_result_data_too_short; - } - - if (sparse->indices_component_type != cgltf_component_type_r_8u && - sparse->indices_component_type != cgltf_component_type_r_16u && - sparse->indices_component_type != cgltf_component_type_r_32u) - { - return cgltf_result_invalid_gltf; - } - - if (sparse->indices_buffer_view->buffer->data) - { - cgltf_size index_bound = cgltf_calc_index_bound(sparse->indices_buffer_view, sparse->indices_byte_offset, sparse->indices_component_type, sparse->count); - - if (index_bound >= accessor->count) - { - return cgltf_result_data_too_short; - } - } - } - } - - for (cgltf_size i = 0; i < data->buffer_views_count; ++i) - { - cgltf_size req_size = data->buffer_views[i].offset + data->buffer_views[i].size; - - if (data->buffer_views[i].buffer && data->buffer_views[i].buffer->size < req_size) - { - return cgltf_result_data_too_short; - } - } - - for (cgltf_size i = 0; i < data->meshes_count; ++i) - { - if (data->meshes[i].weights) - { - if (data->meshes[i].primitives_count && data->meshes[i].primitives[0].targets_count != data->meshes[i].weights_count) - { - return cgltf_result_invalid_gltf; - } - } - - if (data->meshes[i].target_names) - { - if (data->meshes[i].primitives_count && data->meshes[i].primitives[0].targets_count != data->meshes[i].target_names_count) - { - return cgltf_result_invalid_gltf; - } - } - - for (cgltf_size j = 0; j < data->meshes[i].primitives_count; ++j) - { - if (data->meshes[i].primitives[j].targets_count != data->meshes[i].primitives[0].targets_count) - { - return cgltf_result_invalid_gltf; - } - - if (data->meshes[i].primitives[j].attributes_count) - { - cgltf_accessor* first = data->meshes[i].primitives[j].attributes[0].data; - - for (cgltf_size k = 0; k < data->meshes[i].primitives[j].attributes_count; ++k) - { - if (data->meshes[i].primitives[j].attributes[k].data->count != first->count) - { - return cgltf_result_invalid_gltf; - } - } - - for (cgltf_size k = 0; k < data->meshes[i].primitives[j].targets_count; ++k) - { - for (cgltf_size m = 0; m < data->meshes[i].primitives[j].targets[k].attributes_count; ++m) - { - if (data->meshes[i].primitives[j].targets[k].attributes[m].data->count != first->count) - { - return cgltf_result_invalid_gltf; - } - } - } - - cgltf_accessor* indices = data->meshes[i].primitives[j].indices; - - if (indices && - indices->component_type != cgltf_component_type_r_8u && - indices->component_type != cgltf_component_type_r_16u && - indices->component_type != cgltf_component_type_r_32u) - { - return cgltf_result_invalid_gltf; - } - - if (indices && indices->buffer_view && indices->buffer_view->buffer->data) - { - cgltf_size index_bound = cgltf_calc_index_bound(indices->buffer_view, indices->offset, indices->component_type, indices->count); - - if (index_bound >= first->count) - { - return cgltf_result_data_too_short; - } - } - } - } - } - - for (cgltf_size i = 0; i < data->nodes_count; ++i) - { - if (data->nodes[i].weights && data->nodes[i].mesh) - { - if (data->nodes[i].mesh->primitives_count && data->nodes[i].mesh->primitives[0].targets_count != data->nodes[i].weights_count) - { - return cgltf_result_invalid_gltf; - } - } - } - - for (cgltf_size i = 0; i < data->nodes_count; ++i) - { - cgltf_node* p1 = data->nodes[i].parent; - cgltf_node* p2 = p1 ? p1->parent : NULL; - - while (p1 && p2) - { - if (p1 == p2) - { - return cgltf_result_invalid_gltf; - } - - p1 = p1->parent; - p2 = p2->parent ? p2->parent->parent : NULL; - } - } - - for (cgltf_size i = 0; i < data->scenes_count; ++i) - { - for (cgltf_size j = 0; j < data->scenes[i].nodes_count; ++j) - { - if (data->scenes[i].nodes[j]->parent) - { - return cgltf_result_invalid_gltf; - } - } - } - - for (cgltf_size i = 0; i < data->animations_count; ++i) - { - for (cgltf_size j = 0; j < data->animations[i].channels_count; ++j) - { - cgltf_animation_channel* channel = &data->animations[i].channels[j]; - - if (!channel->target_node) - { - continue; - } - - cgltf_size components = 1; - - if (channel->target_path == cgltf_animation_path_type_weights) - { - if (!channel->target_node->mesh || !channel->target_node->mesh->primitives_count) - { - return cgltf_result_invalid_gltf; - } - - components = channel->target_node->mesh->primitives[0].targets_count; - } - - cgltf_size values = channel->sampler->interpolation == cgltf_interpolation_type_cubic_spline ? 3 : 1; - - if (channel->sampler->input->count * components * values != channel->sampler->output->count) - { - return cgltf_result_data_too_short; - } - } - } - - return cgltf_result_success; -} - -cgltf_result cgltf_copy_extras_json(const cgltf_data* data, const cgltf_extras* extras, char* dest, cgltf_size* dest_size) -{ - cgltf_size json_size = extras->end_offset - extras->start_offset; - - if (!dest) - { - if (dest_size) - { - *dest_size = json_size + 1; - return cgltf_result_success; - } - return cgltf_result_invalid_options; - } - - if (*dest_size + 1 < json_size) - { - strncpy(dest, data->json + extras->start_offset, *dest_size - 1); - dest[*dest_size - 1] = 0; - } - else - { - strncpy(dest, data->json + extras->start_offset, json_size); - dest[json_size] = 0; - } - - return cgltf_result_success; -} - -void cgltf_free_extensions(cgltf_data* data, cgltf_extension* extensions, cgltf_size extensions_count) -{ - for (cgltf_size i = 0; i < extensions_count; ++i) - { - data->memory.free(data->memory.user_data, extensions[i].name); - data->memory.free(data->memory.user_data, extensions[i].data); - } - data->memory.free(data->memory.user_data, extensions); -} - -void cgltf_free(cgltf_data* data) -{ - if (!data) - { - return; - } - - void (*file_release)(const struct cgltf_memory_options*, const struct cgltf_file_options*, void* data) = data->file.release ? data->file.release : cgltf_default_file_release; - - data->memory.free(data->memory.user_data, data->asset.copyright); - data->memory.free(data->memory.user_data, data->asset.generator); - data->memory.free(data->memory.user_data, data->asset.version); - data->memory.free(data->memory.user_data, data->asset.min_version); - - cgltf_free_extensions(data, data->asset.extensions, data->asset.extensions_count); - - for (cgltf_size i = 0; i < data->accessors_count; ++i) - { - if(data->accessors[i].is_sparse) - { - cgltf_free_extensions(data, data->accessors[i].sparse.extensions, data->accessors[i].sparse.extensions_count); - cgltf_free_extensions(data, data->accessors[i].sparse.indices_extensions, data->accessors[i].sparse.indices_extensions_count); - cgltf_free_extensions(data, data->accessors[i].sparse.values_extensions, data->accessors[i].sparse.values_extensions_count); - } - cgltf_free_extensions(data, data->accessors[i].extensions, data->accessors[i].extensions_count); - } - data->memory.free(data->memory.user_data, data->accessors); - - for (cgltf_size i = 0; i < data->buffer_views_count; ++i) - { - cgltf_free_extensions(data, data->buffer_views[i].extensions, data->buffer_views[i].extensions_count); - } - data->memory.free(data->memory.user_data, data->buffer_views); - - for (cgltf_size i = 0; i < data->buffers_count; ++i) - { - if (data->buffers[i].data != data->bin) - { - file_release(&data->memory, &data->file, data->buffers[i].data); - } - data->memory.free(data->memory.user_data, data->buffers[i].uri); - - cgltf_free_extensions(data, data->buffers[i].extensions, data->buffers[i].extensions_count); - } - - data->memory.free(data->memory.user_data, data->buffers); - - for (cgltf_size i = 0; i < data->meshes_count; ++i) - { - data->memory.free(data->memory.user_data, data->meshes[i].name); - - for (cgltf_size j = 0; j < data->meshes[i].primitives_count; ++j) - { - for (cgltf_size k = 0; k < data->meshes[i].primitives[j].attributes_count; ++k) - { - data->memory.free(data->memory.user_data, data->meshes[i].primitives[j].attributes[k].name); - } - - data->memory.free(data->memory.user_data, data->meshes[i].primitives[j].attributes); - - for (cgltf_size k = 0; k < data->meshes[i].primitives[j].targets_count; ++k) - { - for (cgltf_size m = 0; m < data->meshes[i].primitives[j].targets[k].attributes_count; ++m) - { - data->memory.free(data->memory.user_data, data->meshes[i].primitives[j].targets[k].attributes[m].name); - } - - data->memory.free(data->memory.user_data, data->meshes[i].primitives[j].targets[k].attributes); - } - - data->memory.free(data->memory.user_data, data->meshes[i].primitives[j].targets); - - if (data->meshes[i].primitives[j].has_draco_mesh_compression) - { - for (cgltf_size k = 0; k < data->meshes[i].primitives[j].draco_mesh_compression.attributes_count; ++k) - { - data->memory.free(data->memory.user_data, data->meshes[i].primitives[j].draco_mesh_compression.attributes[k].name); - } - - data->memory.free(data->memory.user_data, data->meshes[i].primitives[j].draco_mesh_compression.attributes); - } - - cgltf_free_extensions(data, data->meshes[i].primitives[j].extensions, data->meshes[i].primitives[j].extensions_count); - } - - data->memory.free(data->memory.user_data, data->meshes[i].primitives); - data->memory.free(data->memory.user_data, data->meshes[i].weights); - - for (cgltf_size j = 0; j < data->meshes[i].target_names_count; ++j) - { - data->memory.free(data->memory.user_data, data->meshes[i].target_names[j]); - } - - cgltf_free_extensions(data, data->meshes[i].extensions, data->meshes[i].extensions_count); - - data->memory.free(data->memory.user_data, data->meshes[i].target_names); - } - - data->memory.free(data->memory.user_data, data->meshes); - - for (cgltf_size i = 0; i < data->materials_count; ++i) - { - data->memory.free(data->memory.user_data, data->materials[i].name); - - if(data->materials[i].has_pbr_metallic_roughness) - { - cgltf_free_extensions(data, data->materials[i].pbr_metallic_roughness.metallic_roughness_texture.extensions, data->materials[i].pbr_metallic_roughness.metallic_roughness_texture.extensions_count); - cgltf_free_extensions(data, data->materials[i].pbr_metallic_roughness.base_color_texture.extensions, data->materials[i].pbr_metallic_roughness.base_color_texture.extensions_count); - } - if(data->materials[i].has_pbr_specular_glossiness) - { - cgltf_free_extensions(data, data->materials[i].pbr_specular_glossiness.diffuse_texture.extensions, data->materials[i].pbr_specular_glossiness.diffuse_texture.extensions_count); - cgltf_free_extensions(data, data->materials[i].pbr_specular_glossiness.specular_glossiness_texture.extensions, data->materials[i].pbr_specular_glossiness.specular_glossiness_texture.extensions_count); - } - if(data->materials[i].has_clearcoat) - { - cgltf_free_extensions(data, data->materials[i].clearcoat.clearcoat_texture.extensions, data->materials[i].clearcoat.clearcoat_texture.extensions_count); - cgltf_free_extensions(data, data->materials[i].clearcoat.clearcoat_roughness_texture.extensions, data->materials[i].clearcoat.clearcoat_roughness_texture.extensions_count); - cgltf_free_extensions(data, data->materials[i].clearcoat.clearcoat_normal_texture.extensions, data->materials[i].clearcoat.clearcoat_normal_texture.extensions_count); - } - if(data->materials[i].has_specular) - { - cgltf_free_extensions(data, data->materials[i].specular.specular_texture.extensions, data->materials[i].specular.specular_texture.extensions_count); - } - if(data->materials[i].has_transmission) - { - cgltf_free_extensions(data, data->materials[i].transmission.transmission_texture.extensions, data->materials[i].transmission.transmission_texture.extensions_count); - } - - cgltf_free_extensions(data, data->materials[i].normal_texture.extensions, data->materials[i].normal_texture.extensions_count); - cgltf_free_extensions(data, data->materials[i].occlusion_texture.extensions, data->materials[i].occlusion_texture.extensions_count); - cgltf_free_extensions(data, data->materials[i].emissive_texture.extensions, data->materials[i].emissive_texture.extensions_count); - - cgltf_free_extensions(data, data->materials[i].extensions, data->materials[i].extensions_count); - } - - data->memory.free(data->memory.user_data, data->materials); - - for (cgltf_size i = 0; i < data->images_count; ++i) - { - data->memory.free(data->memory.user_data, data->images[i].name); - data->memory.free(data->memory.user_data, data->images[i].uri); - data->memory.free(data->memory.user_data, data->images[i].mime_type); - - cgltf_free_extensions(data, data->images[i].extensions, data->images[i].extensions_count); - } - - data->memory.free(data->memory.user_data, data->images); - - for (cgltf_size i = 0; i < data->textures_count; ++i) - { - data->memory.free(data->memory.user_data, data->textures[i].name); - cgltf_free_extensions(data, data->textures[i].extensions, data->textures[i].extensions_count); - } - - data->memory.free(data->memory.user_data, data->textures); - - for (cgltf_size i = 0; i < data->samplers_count; ++i) - { - cgltf_free_extensions(data, data->samplers[i].extensions, data->samplers[i].extensions_count); - } - - data->memory.free(data->memory.user_data, data->samplers); - - for (cgltf_size i = 0; i < data->skins_count; ++i) - { - data->memory.free(data->memory.user_data, data->skins[i].name); - data->memory.free(data->memory.user_data, data->skins[i].joints); - - cgltf_free_extensions(data, data->skins[i].extensions, data->skins[i].extensions_count); - } - - data->memory.free(data->memory.user_data, data->skins); - - for (cgltf_size i = 0; i < data->cameras_count; ++i) - { - data->memory.free(data->memory.user_data, data->cameras[i].name); - cgltf_free_extensions(data, data->cameras[i].extensions, data->cameras[i].extensions_count); - } - - data->memory.free(data->memory.user_data, data->cameras); - - for (cgltf_size i = 0; i < data->lights_count; ++i) - { - data->memory.free(data->memory.user_data, data->lights[i].name); - } - - data->memory.free(data->memory.user_data, data->lights); - - for (cgltf_size i = 0; i < data->nodes_count; ++i) - { - data->memory.free(data->memory.user_data, data->nodes[i].name); - data->memory.free(data->memory.user_data, data->nodes[i].children); - data->memory.free(data->memory.user_data, data->nodes[i].weights); - cgltf_free_extensions(data, data->nodes[i].extensions, data->nodes[i].extensions_count); - } - - data->memory.free(data->memory.user_data, data->nodes); - - for (cgltf_size i = 0; i < data->scenes_count; ++i) - { - data->memory.free(data->memory.user_data, data->scenes[i].name); - data->memory.free(data->memory.user_data, data->scenes[i].nodes); - - cgltf_free_extensions(data, data->scenes[i].extensions, data->scenes[i].extensions_count); - } - - data->memory.free(data->memory.user_data, data->scenes); - - for (cgltf_size i = 0; i < data->animations_count; ++i) - { - data->memory.free(data->memory.user_data, data->animations[i].name); - for (cgltf_size j = 0; j < data->animations[i].samplers_count; ++j) - { - cgltf_free_extensions(data, data->animations[i].samplers[j].extensions, data->animations[i].samplers[j].extensions_count); - } - data->memory.free(data->memory.user_data, data->animations[i].samplers); - - for (cgltf_size j = 0; j < data->animations[i].channels_count; ++j) - { - cgltf_free_extensions(data, data->animations[i].channels[j].extensions, data->animations[i].channels[j].extensions_count); - } - data->memory.free(data->memory.user_data, data->animations[i].channels); - - cgltf_free_extensions(data, data->animations[i].extensions, data->animations[i].extensions_count); - } - - data->memory.free(data->memory.user_data, data->animations); - - cgltf_free_extensions(data, data->data_extensions, data->data_extensions_count); - - for (cgltf_size i = 0; i < data->extensions_used_count; ++i) - { - data->memory.free(data->memory.user_data, data->extensions_used[i]); - } - - data->memory.free(data->memory.user_data, data->extensions_used); - - for (cgltf_size i = 0; i < data->extensions_required_count; ++i) - { - data->memory.free(data->memory.user_data, data->extensions_required[i]); - } - - data->memory.free(data->memory.user_data, data->extensions_required); - - file_release(&data->memory, &data->file, data->file_data); - - data->memory.free(data->memory.user_data, data); -} - -void cgltf_node_transform_local(const cgltf_node* node, cgltf_float* out_matrix) -{ - cgltf_float* lm = out_matrix; - - if (node->has_matrix) - { - memcpy(lm, node->matrix, sizeof(float) * 16); - } - else - { - float tx = node->translation[0]; - float ty = node->translation[1]; - float tz = node->translation[2]; - - float qx = node->rotation[0]; - float qy = node->rotation[1]; - float qz = node->rotation[2]; - float qw = node->rotation[3]; - - float sx = node->scale[0]; - float sy = node->scale[1]; - float sz = node->scale[2]; - - lm[0] = (1 - 2 * qy*qy - 2 * qz*qz) * sx; - lm[1] = (2 * qx*qy + 2 * qz*qw) * sx; - lm[2] = (2 * qx*qz - 2 * qy*qw) * sx; - lm[3] = 0.f; - - lm[4] = (2 * qx*qy - 2 * qz*qw) * sy; - lm[5] = (1 - 2 * qx*qx - 2 * qz*qz) * sy; - lm[6] = (2 * qy*qz + 2 * qx*qw) * sy; - lm[7] = 0.f; - - lm[8] = (2 * qx*qz + 2 * qy*qw) * sz; - lm[9] = (2 * qy*qz - 2 * qx*qw) * sz; - lm[10] = (1 - 2 * qx*qx - 2 * qy*qy) * sz; - lm[11] = 0.f; - - lm[12] = tx; - lm[13] = ty; - lm[14] = tz; - lm[15] = 1.f; - } -} - -void cgltf_node_transform_world(const cgltf_node* node, cgltf_float* out_matrix) -{ - cgltf_float* lm = out_matrix; - cgltf_node_transform_local(node, lm); - - const cgltf_node* parent = node->parent; - - while (parent) - { - float pm[16]; - cgltf_node_transform_local(parent, pm); - - for (int i = 0; i < 4; ++i) - { - float l0 = lm[i * 4 + 0]; - float l1 = lm[i * 4 + 1]; - float l2 = lm[i * 4 + 2]; - - float r0 = l0 * pm[0] + l1 * pm[4] + l2 * pm[8]; - float r1 = l0 * pm[1] + l1 * pm[5] + l2 * pm[9]; - float r2 = l0 * pm[2] + l1 * pm[6] + l2 * pm[10]; - - lm[i * 4 + 0] = r0; - lm[i * 4 + 1] = r1; - lm[i * 4 + 2] = r2; - } - - lm[12] += pm[12]; - lm[13] += pm[13]; - lm[14] += pm[14]; - - parent = parent->parent; - } -} - -static cgltf_size cgltf_component_read_index(const void* in, cgltf_component_type component_type) -{ - switch (component_type) - { - case cgltf_component_type_r_16: - return *((const int16_t*) in); - case cgltf_component_type_r_16u: - return *((const uint16_t*) in); - case cgltf_component_type_r_32u: - return *((const uint32_t*) in); - case cgltf_component_type_r_32f: - return (cgltf_size)*((const float*) in); - case cgltf_component_type_r_8: - return *((const int8_t*) in); - case cgltf_component_type_r_8u: - return *((const uint8_t*) in); - default: - return 0; - } -} - -static cgltf_float cgltf_component_read_float(const void* in, cgltf_component_type component_type, cgltf_bool normalized) -{ - if (component_type == cgltf_component_type_r_32f) - { - return *((const float*) in); - } - - if (normalized) - { - switch (component_type) - { - // note: glTF spec doesn't currently define normalized conversions for 32-bit integers - case cgltf_component_type_r_16: - return *((const int16_t*) in) / (cgltf_float)32767; - case cgltf_component_type_r_16u: - return *((const uint16_t*) in) / (cgltf_float)65535; - case cgltf_component_type_r_8: - return *((const int8_t*) in) / (cgltf_float)127; - case cgltf_component_type_r_8u: - return *((const uint8_t*) in) / (cgltf_float)255; - default: - return 0; - } - } - - return (cgltf_float)cgltf_component_read_index(in, component_type); -} - -static cgltf_size cgltf_component_size(cgltf_component_type component_type); - -static cgltf_bool cgltf_element_read_float(const uint8_t* element, cgltf_type type, cgltf_component_type component_type, cgltf_bool normalized, cgltf_float* out, cgltf_size element_size) -{ - cgltf_size num_components = cgltf_num_components(type); - - if (element_size < num_components) { - return 0; - } - - // There are three special cases for component extraction, see #data-alignment in the 2.0 spec. - - cgltf_size component_size = cgltf_component_size(component_type); - - if (type == cgltf_type_mat2 && component_size == 1) - { - out[0] = cgltf_component_read_float(element, component_type, normalized); - out[1] = cgltf_component_read_float(element + 1, component_type, normalized); - out[2] = cgltf_component_read_float(element + 4, component_type, normalized); - out[3] = cgltf_component_read_float(element + 5, component_type, normalized); - return 1; - } - - if (type == cgltf_type_mat3 && component_size == 1) - { - out[0] = cgltf_component_read_float(element, component_type, normalized); - out[1] = cgltf_component_read_float(element + 1, component_type, normalized); - out[2] = cgltf_component_read_float(element + 2, component_type, normalized); - out[3] = cgltf_component_read_float(element + 4, component_type, normalized); - out[4] = cgltf_component_read_float(element + 5, component_type, normalized); - out[5] = cgltf_component_read_float(element + 6, component_type, normalized); - out[6] = cgltf_component_read_float(element + 8, component_type, normalized); - out[7] = cgltf_component_read_float(element + 9, component_type, normalized); - out[8] = cgltf_component_read_float(element + 10, component_type, normalized); - return 1; - } - - if (type == cgltf_type_mat3 && component_size == 2) - { - out[0] = cgltf_component_read_float(element, component_type, normalized); - out[1] = cgltf_component_read_float(element + 2, component_type, normalized); - out[2] = cgltf_component_read_float(element + 4, component_type, normalized); - out[3] = cgltf_component_read_float(element + 8, component_type, normalized); - out[4] = cgltf_component_read_float(element + 10, component_type, normalized); - out[5] = cgltf_component_read_float(element + 12, component_type, normalized); - out[6] = cgltf_component_read_float(element + 16, component_type, normalized); - out[7] = cgltf_component_read_float(element + 18, component_type, normalized); - out[8] = cgltf_component_read_float(element + 20, component_type, normalized); - return 1; - } - - for (cgltf_size i = 0; i < num_components; ++i) - { - out[i] = cgltf_component_read_float(element + component_size * i, component_type, normalized); - } - return 1; -} - -cgltf_bool cgltf_accessor_read_float(const cgltf_accessor* accessor, cgltf_size index, cgltf_float* out, cgltf_size element_size) -{ - if (accessor->is_sparse) - { - return 0; - } - if (accessor->buffer_view == NULL) - { - memset(out, 0, element_size * sizeof(cgltf_float)); - return 1; - } - if (accessor->buffer_view->buffer->data == NULL) - { - return 0; - } - cgltf_size offset = accessor->offset + accessor->buffer_view->offset; - const uint8_t* element = (const uint8_t*) accessor->buffer_view->buffer->data; - element += offset + accessor->stride * index; - return cgltf_element_read_float(element, accessor->type, accessor->component_type, accessor->normalized, out, element_size); -} - -cgltf_size cgltf_accessor_unpack_floats(const cgltf_accessor* accessor, cgltf_float* out, cgltf_size float_count) -{ - cgltf_size floats_per_element = cgltf_num_components(accessor->type); - cgltf_size available_floats = accessor->count * floats_per_element; - if (out == NULL) - { - return available_floats; - } - - float_count = available_floats < float_count ? available_floats : float_count; - cgltf_size element_count = float_count / floats_per_element; - - // First pass: convert each element in the base accessor. - cgltf_float* dest = out; - cgltf_accessor dense = *accessor; - dense.is_sparse = 0; - for (cgltf_size index = 0; index < element_count; index++, dest += floats_per_element) - { - if (!cgltf_accessor_read_float(&dense, index, dest, floats_per_element)) - { - return 0; - } - } - - // Second pass: write out each element in the sparse accessor. - if (accessor->is_sparse) - { - const cgltf_accessor_sparse* sparse = &dense.sparse; - - if (sparse->indices_buffer_view->buffer->data == NULL || sparse->values_buffer_view->buffer->data == NULL) - { - return 0; - } - - const uint8_t* index_data = (const uint8_t*) sparse->indices_buffer_view->buffer->data; - index_data += sparse->indices_byte_offset + sparse->indices_buffer_view->offset; - cgltf_size index_stride = cgltf_component_size(sparse->indices_component_type); - const uint8_t* reader_head = (const uint8_t*) sparse->values_buffer_view->buffer->data; - reader_head += sparse->values_byte_offset + sparse->values_buffer_view->offset; - for (cgltf_size reader_index = 0; reader_index < sparse->count; reader_index++, index_data += index_stride) - { - size_t writer_index = cgltf_component_read_index(index_data, sparse->indices_component_type); - float* writer_head = out + writer_index * floats_per_element; - - if (!cgltf_element_read_float(reader_head, dense.type, dense.component_type, dense.normalized, writer_head, floats_per_element)) - { - return 0; - } - - reader_head += dense.stride; - } - } - - return element_count * floats_per_element; -} - -static cgltf_uint cgltf_component_read_uint(const void* in, cgltf_component_type component_type) -{ - switch (component_type) - { - case cgltf_component_type_r_8: - return *((const int8_t*) in); - - case cgltf_component_type_r_8u: - return *((const uint8_t*) in); - - case cgltf_component_type_r_16: - return *((const int16_t*) in); - - case cgltf_component_type_r_16u: - return *((const uint16_t*) in); - - case cgltf_component_type_r_32u: - return *((const uint32_t*) in); - - default: - return 0; - } -} - -static cgltf_bool cgltf_element_read_uint(const uint8_t* element, cgltf_type type, cgltf_component_type component_type, cgltf_uint* out, cgltf_size element_size) -{ - cgltf_size num_components = cgltf_num_components(type); - - if (element_size < num_components) - { - return 0; - } - - // Reading integer matrices is not a valid use case - if (type == cgltf_type_mat2 || type == cgltf_type_mat3 || type == cgltf_type_mat4) - { - return 0; - } - - cgltf_size component_size = cgltf_component_size(component_type); - - for (cgltf_size i = 0; i < num_components; ++i) - { - out[i] = cgltf_component_read_uint(element + component_size * i, component_type); - } - return 1; -} - -cgltf_bool cgltf_accessor_read_uint(const cgltf_accessor* accessor, cgltf_size index, cgltf_uint* out, cgltf_size element_size) -{ - if (accessor->is_sparse) - { - return 0; - } - if (accessor->buffer_view == NULL) - { - memset(out, 0, element_size * sizeof( cgltf_uint )); - return 1; - } - if (accessor->buffer_view->buffer->data == NULL) - { - return 0; - } - cgltf_size offset = accessor->offset + accessor->buffer_view->offset; - const uint8_t* element = (const uint8_t*) accessor->buffer_view->buffer->data; - element += offset + accessor->stride * index; - return cgltf_element_read_uint(element, accessor->type, accessor->component_type, out, element_size); -} - -cgltf_size cgltf_accessor_read_index(const cgltf_accessor* accessor, cgltf_size index) -{ - if (accessor->is_sparse) - { - return 0; // This is an error case, but we can't communicate the error with existing interface. - } - if (accessor->buffer_view == NULL) - { - return 0; - } - if (accessor->buffer_view->buffer->data == NULL) - { - return 0; // This is an error case, but we can't communicate the error with existing interface. - } - - cgltf_size offset = accessor->offset + accessor->buffer_view->offset; - const uint8_t* element = (const uint8_t*) accessor->buffer_view->buffer->data; - element += offset + accessor->stride * index; - return cgltf_component_read_index(element, accessor->component_type); -} - -#define CGLTF_ERROR_JSON -1 -#define CGLTF_ERROR_NOMEM -2 -#define CGLTF_ERROR_LEGACY -3 - -#define CGLTF_CHECK_TOKTYPE(tok_, type_) if ((tok_).type != (type_)) { return CGLTF_ERROR_JSON; } -#define CGLTF_CHECK_KEY(tok_) if ((tok_).type != JSMN_STRING || (tok_).size == 0) { return CGLTF_ERROR_JSON; } /* checking size for 0 verifies that a value follows the key */ - -#define CGLTF_PTRINDEX(type, idx) (type*)((cgltf_size)idx + 1) -#define CGLTF_PTRFIXUP(var, data, size) if (var) { if ((cgltf_size)var > size) { return CGLTF_ERROR_JSON; } var = &data[(cgltf_size)var-1]; } -#define CGLTF_PTRFIXUP_REQ(var, data, size) if (!var || (cgltf_size)var > size) { return CGLTF_ERROR_JSON; } var = &data[(cgltf_size)var-1]; - -static int cgltf_json_strcmp(jsmntok_t const* tok, const uint8_t* json_chunk, const char* str) -{ - CGLTF_CHECK_TOKTYPE(*tok, JSMN_STRING); - size_t const str_len = strlen(str); - size_t const name_length = tok->end - tok->start; - return (str_len == name_length) ? strncmp((const char*)json_chunk + tok->start, str, str_len) : 128; -} - -static int cgltf_json_to_int(jsmntok_t const* tok, const uint8_t* json_chunk) -{ - CGLTF_CHECK_TOKTYPE(*tok, JSMN_PRIMITIVE); - char tmp[128]; - int size = (cgltf_size)(tok->end - tok->start) < sizeof(tmp) ? tok->end - tok->start : (int)(sizeof(tmp) - 1); - strncpy(tmp, (const char*)json_chunk + tok->start, size); - tmp[size] = 0; - return CGLTF_ATOI(tmp); -} - -static cgltf_float cgltf_json_to_float(jsmntok_t const* tok, const uint8_t* json_chunk) -{ - CGLTF_CHECK_TOKTYPE(*tok, JSMN_PRIMITIVE); - char tmp[128]; - int size = (cgltf_size)(tok->end - tok->start) < sizeof(tmp) ? tok->end - tok->start : (int)(sizeof(tmp) - 1); - strncpy(tmp, (const char*)json_chunk + tok->start, size); - tmp[size] = 0; - return (cgltf_float)CGLTF_ATOF(tmp); -} - -static cgltf_bool cgltf_json_to_bool(jsmntok_t const* tok, const uint8_t* json_chunk) -{ - int size = tok->end - tok->start; - return size == 4 && memcmp(json_chunk + tok->start, "true", 4) == 0; -} - -static int cgltf_skip_json(jsmntok_t const* tokens, int i) -{ - int end = i + 1; - - while (i < end) - { - switch (tokens[i].type) - { - case JSMN_OBJECT: - end += tokens[i].size * 2; - break; - - case JSMN_ARRAY: - end += tokens[i].size; - break; - - case JSMN_PRIMITIVE: - case JSMN_STRING: - break; - - default: - return -1; - } - - i++; - } - - return i; -} - -static void cgltf_fill_float_array(float* out_array, int size, float value) -{ - for (int j = 0; j < size; ++j) - { - out_array[j] = value; - } -} - -static int cgltf_parse_json_float_array(jsmntok_t const* tokens, int i, const uint8_t* json_chunk, float* out_array, int size) -{ - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_ARRAY); - if (tokens[i].size != size) - { - return CGLTF_ERROR_JSON; - } - ++i; - for (int j = 0; j < size; ++j) - { - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE); - out_array[j] = cgltf_json_to_float(tokens + i, json_chunk); - ++i; - } - return i; -} - -static int cgltf_parse_json_string(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, char** out_string) -{ - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_STRING); - if (*out_string) - { - return CGLTF_ERROR_JSON; - } - int size = tokens[i].end - tokens[i].start; - char* result = (char*)options->memory.alloc(options->memory.user_data, size + 1); - if (!result) - { - return CGLTF_ERROR_NOMEM; - } - strncpy(result, (const char*)json_chunk + tokens[i].start, size); - result[size] = 0; - *out_string = result; - return i + 1; -} - -static int cgltf_parse_json_array(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, size_t element_size, void** out_array, cgltf_size* out_size) -{ - (void)json_chunk; - if (tokens[i].type != JSMN_ARRAY) - { - return tokens[i].type == JSMN_OBJECT ? CGLTF_ERROR_LEGACY : CGLTF_ERROR_JSON; - } - if (*out_array) - { - return CGLTF_ERROR_JSON; - } - int size = tokens[i].size; - void* result = cgltf_calloc(options, element_size, size); - if (!result) - { - return CGLTF_ERROR_NOMEM; - } - *out_array = result; - *out_size = size; - return i + 1; -} - -static int cgltf_parse_json_string_array(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, char*** out_array, cgltf_size* out_size) -{ - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_ARRAY); - i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(char*), (void**)out_array, out_size); - if (i < 0) - { - return i; - } - - for (cgltf_size j = 0; j < *out_size; ++j) - { - i = cgltf_parse_json_string(options, tokens, i, json_chunk, j + (*out_array)); - if (i < 0) - { - return i; - } - } - return i; -} - -static void cgltf_parse_attribute_type(const char* name, cgltf_attribute_type* out_type, int* out_index) -{ - const char* us = strchr(name, '_'); - size_t len = us ? (size_t)(us - name) : strlen(name); - - if (len == 8 && strncmp(name, "POSITION", 8) == 0) - { - *out_type = cgltf_attribute_type_position; - } - else if (len == 6 && strncmp(name, "NORMAL", 6) == 0) - { - *out_type = cgltf_attribute_type_normal; - } - else if (len == 7 && strncmp(name, "TANGENT", 7) == 0) - { - *out_type = cgltf_attribute_type_tangent; - } - else if (len == 8 && strncmp(name, "TEXCOORD", 8) == 0) - { - *out_type = cgltf_attribute_type_texcoord; - } - else if (len == 5 && strncmp(name, "COLOR", 5) == 0) - { - *out_type = cgltf_attribute_type_color; - } - else if (len == 6 && strncmp(name, "JOINTS", 6) == 0) - { - *out_type = cgltf_attribute_type_joints; - } - else if (len == 7 && strncmp(name, "WEIGHTS", 7) == 0) - { - *out_type = cgltf_attribute_type_weights; - } - else - { - *out_type = cgltf_attribute_type_invalid; - } - - if (us && *out_type != cgltf_attribute_type_invalid) - { - *out_index = CGLTF_ATOI(us + 1); - } -} - -static int cgltf_parse_json_attribute_list(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_attribute** out_attributes, cgltf_size* out_attributes_count) -{ - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - if (*out_attributes) - { - return CGLTF_ERROR_JSON; - } - - *out_attributes_count = tokens[i].size; - *out_attributes = (cgltf_attribute*)cgltf_calloc(options, sizeof(cgltf_attribute), *out_attributes_count); - ++i; - - if (!*out_attributes) - { - return CGLTF_ERROR_NOMEM; - } - - for (cgltf_size j = 0; j < *out_attributes_count; ++j) - { - CGLTF_CHECK_KEY(tokens[i]); - - i = cgltf_parse_json_string(options, tokens, i, json_chunk, &(*out_attributes)[j].name); - if (i < 0) - { - return CGLTF_ERROR_JSON; - } - - cgltf_parse_attribute_type((*out_attributes)[j].name, &(*out_attributes)[j].type, &(*out_attributes)[j].index); - - (*out_attributes)[j].data = CGLTF_PTRINDEX(cgltf_accessor, cgltf_json_to_int(tokens + i, json_chunk)); - ++i; - } - - return i; -} - -static int cgltf_parse_json_extras(jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_extras* out_extras) -{ - (void)json_chunk; - out_extras->start_offset = tokens[i].start; - out_extras->end_offset = tokens[i].end; - i = cgltf_skip_json(tokens, i); - return i; -} - -static int cgltf_parse_json_unprocessed_extension(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_extension* out_extension) -{ - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_STRING); - CGLTF_CHECK_TOKTYPE(tokens[i+1], JSMN_OBJECT); - if (out_extension->name) - { - return CGLTF_ERROR_JSON; - } - - cgltf_size name_length = tokens[i].end - tokens[i].start; - out_extension->name = (char*)options->memory.alloc(options->memory.user_data, name_length + 1); - if (!out_extension->name) - { - return CGLTF_ERROR_NOMEM; - } - strncpy(out_extension->name, (const char*)json_chunk + tokens[i].start, name_length); - out_extension->name[name_length] = 0; - i++; - - size_t start = tokens[i].start; - size_t size = tokens[i].end - start; - out_extension->data = (char*)options->memory.alloc(options->memory.user_data, size + 1); - if (!out_extension->data) - { - return CGLTF_ERROR_NOMEM; - } - strncpy(out_extension->data, (const char*)json_chunk + start, size); - out_extension->data[size] = '\0'; - - i = cgltf_skip_json(tokens, i); - - return i; -} - -static int cgltf_parse_json_unprocessed_extensions(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_size* out_extensions_count, cgltf_extension** out_extensions) -{ - ++i; - - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - if(*out_extensions) - { - return CGLTF_ERROR_JSON; - } - - int extensions_size = tokens[i].size; - *out_extensions_count = 0; - *out_extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size); - - if (!*out_extensions) - { - return CGLTF_ERROR_NOMEM; - } - - ++i; - - for (int j = 0; j < extensions_size; ++j) - { - CGLTF_CHECK_KEY(tokens[i]); - - cgltf_size extension_index = (*out_extensions_count)++; - cgltf_extension* extension = &((*out_extensions)[extension_index]); - i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, extension); - - if (i < 0) - { - return i; - } - } - return i; -} - -static int cgltf_parse_json_draco_mesh_compression(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_draco_mesh_compression* out_draco_mesh_compression) -{ - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - int size = tokens[i].size; - ++i; - - for (int j = 0; j < size; ++j) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens + i, json_chunk, "attributes") == 0) - { - i = cgltf_parse_json_attribute_list(options, tokens, i + 1, json_chunk, &out_draco_mesh_compression->attributes, &out_draco_mesh_compression->attributes_count); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "bufferView") == 0) - { - ++i; - out_draco_mesh_compression->buffer_view = CGLTF_PTRINDEX(cgltf_buffer_view, cgltf_json_to_int(tokens + i, json_chunk)); - ++i; - } - } - - return i; -} - -static int cgltf_parse_json_primitive(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_primitive* out_prim) -{ - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - out_prim->type = cgltf_primitive_type_triangles; - - int size = tokens[i].size; - ++i; - - for (int j = 0; j < size; ++j) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "mode") == 0) - { - ++i; - out_prim->type - = (cgltf_primitive_type) - cgltf_json_to_int(tokens+i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "indices") == 0) - { - ++i; - out_prim->indices = CGLTF_PTRINDEX(cgltf_accessor, cgltf_json_to_int(tokens + i, json_chunk)); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "material") == 0) - { - ++i; - out_prim->material = CGLTF_PTRINDEX(cgltf_material, cgltf_json_to_int(tokens + i, json_chunk)); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "attributes") == 0) - { - i = cgltf_parse_json_attribute_list(options, tokens, i + 1, json_chunk, &out_prim->attributes, &out_prim->attributes_count); - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "targets") == 0) - { - i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_morph_target), (void**)&out_prim->targets, &out_prim->targets_count); - if (i < 0) - { - return i; - } - - for (cgltf_size k = 0; k < out_prim->targets_count; ++k) - { - i = cgltf_parse_json_attribute_list(options, tokens, i, json_chunk, &out_prim->targets[k].attributes, &out_prim->targets[k].attributes_count); - if (i < 0) - { - return i; - } - } - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) - { - i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_prim->extras); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) - { - ++i; - - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - if(out_prim->extensions) - { - return CGLTF_ERROR_JSON; - } - - int extensions_size = tokens[i].size; - out_prim->extensions_count = 0; - out_prim->extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size); - - if (!out_prim->extensions) - { - return CGLTF_ERROR_NOMEM; - } - - ++i; - for (int k = 0; k < extensions_size; ++k) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_draco_mesh_compression") == 0) - { - out_prim->has_draco_mesh_compression = 1; - i = cgltf_parse_json_draco_mesh_compression(options, tokens, i + 1, json_chunk, &out_prim->draco_mesh_compression); - } - else - { - i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, &(out_prim->extensions[out_prim->extensions_count++])); - } - - if (i < 0) - { - return i; - } - } - } - else - { - i = cgltf_skip_json(tokens, i+1); - } - - if (i < 0) - { - return i; - } - } - - return i; -} - -static int cgltf_parse_json_mesh(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_mesh* out_mesh) -{ - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - int size = tokens[i].size; - ++i; - - for (int j = 0; j < size; ++j) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0) - { - i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_mesh->name); - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "primitives") == 0) - { - i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_primitive), (void**)&out_mesh->primitives, &out_mesh->primitives_count); - if (i < 0) - { - return i; - } - - for (cgltf_size prim_index = 0; prim_index < out_mesh->primitives_count; ++prim_index) - { - i = cgltf_parse_json_primitive(options, tokens, i, json_chunk, &out_mesh->primitives[prim_index]); - if (i < 0) - { - return i; - } - } - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "weights") == 0) - { - i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_float), (void**)&out_mesh->weights, &out_mesh->weights_count); - if (i < 0) - { - return i; - } - - i = cgltf_parse_json_float_array(tokens, i - 1, json_chunk, out_mesh->weights, (int)out_mesh->weights_count); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) - { - ++i; - - out_mesh->extras.start_offset = tokens[i].start; - out_mesh->extras.end_offset = tokens[i].end; - - if (tokens[i].type == JSMN_OBJECT) - { - int extras_size = tokens[i].size; - ++i; - - for (int k = 0; k < extras_size; ++k) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "targetNames") == 0) - { - i = cgltf_parse_json_string_array(options, tokens, i + 1, json_chunk, &out_mesh->target_names, &out_mesh->target_names_count); - } - else - { - i = cgltf_skip_json(tokens, i+1); - } - - if (i < 0) - { - return i; - } - } - } - else - { - i = cgltf_skip_json(tokens, i); - } - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) - { - i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_mesh->extensions_count, &out_mesh->extensions); - } - else - { - i = cgltf_skip_json(tokens, i+1); - } - - if (i < 0) - { - return i; - } - } - - return i; -} - -static int cgltf_parse_json_meshes(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) -{ - i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_mesh), (void**)&out_data->meshes, &out_data->meshes_count); - if (i < 0) - { - return i; - } - - for (cgltf_size j = 0; j < out_data->meshes_count; ++j) - { - i = cgltf_parse_json_mesh(options, tokens, i, json_chunk, &out_data->meshes[j]); - if (i < 0) - { - return i; - } - } - return i; -} - -static cgltf_component_type cgltf_json_to_component_type(jsmntok_t const* tok, const uint8_t* json_chunk) -{ - int type = cgltf_json_to_int(tok, json_chunk); - - switch (type) - { - case 5120: - return cgltf_component_type_r_8; - case 5121: - return cgltf_component_type_r_8u; - case 5122: - return cgltf_component_type_r_16; - case 5123: - return cgltf_component_type_r_16u; - case 5125: - return cgltf_component_type_r_32u; - case 5126: - return cgltf_component_type_r_32f; - default: - return cgltf_component_type_invalid; - } -} - -static int cgltf_parse_json_accessor_sparse(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_accessor_sparse* out_sparse) -{ - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - int size = tokens[i].size; - ++i; - - for (int j = 0; j < size; ++j) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "count") == 0) - { - ++i; - out_sparse->count = cgltf_json_to_int(tokens + i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "indices") == 0) - { - ++i; - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - int indices_size = tokens[i].size; - ++i; - - for (int k = 0; k < indices_size; ++k) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "bufferView") == 0) - { - ++i; - out_sparse->indices_buffer_view = CGLTF_PTRINDEX(cgltf_buffer_view, cgltf_json_to_int(tokens + i, json_chunk)); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteOffset") == 0) - { - ++i; - out_sparse->indices_byte_offset = cgltf_json_to_int(tokens + i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "componentType") == 0) - { - ++i; - out_sparse->indices_component_type = cgltf_json_to_component_type(tokens + i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) - { - i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_sparse->indices_extras); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) - { - i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_sparse->indices_extensions_count, &out_sparse->indices_extensions); - } - else - { - i = cgltf_skip_json(tokens, i+1); - } - - if (i < 0) - { - return i; - } - } - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "values") == 0) - { - ++i; - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - int values_size = tokens[i].size; - ++i; - - for (int k = 0; k < values_size; ++k) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "bufferView") == 0) - { - ++i; - out_sparse->values_buffer_view = CGLTF_PTRINDEX(cgltf_buffer_view, cgltf_json_to_int(tokens + i, json_chunk)); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteOffset") == 0) - { - ++i; - out_sparse->values_byte_offset = cgltf_json_to_int(tokens + i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) - { - i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_sparse->values_extras); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) - { - i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_sparse->values_extensions_count, &out_sparse->values_extensions); - } - else - { - i = cgltf_skip_json(tokens, i+1); - } - - if (i < 0) - { - return i; - } - } - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) - { - i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_sparse->extras); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) - { - i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_sparse->extensions_count, &out_sparse->extensions); - } - else - { - i = cgltf_skip_json(tokens, i+1); - } - - if (i < 0) - { - return i; - } - } - - return i; -} - -static int cgltf_parse_json_accessor(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_accessor* out_accessor) -{ - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - int size = tokens[i].size; - ++i; - - for (int j = 0; j < size; ++j) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "bufferView") == 0) - { - ++i; - out_accessor->buffer_view = CGLTF_PTRINDEX(cgltf_buffer_view, cgltf_json_to_int(tokens + i, json_chunk)); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteOffset") == 0) - { - ++i; - out_accessor->offset = - cgltf_json_to_int(tokens+i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "componentType") == 0) - { - ++i; - out_accessor->component_type = cgltf_json_to_component_type(tokens + i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "normalized") == 0) - { - ++i; - out_accessor->normalized = cgltf_json_to_bool(tokens+i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "count") == 0) - { - ++i; - out_accessor->count = - cgltf_json_to_int(tokens+i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "type") == 0) - { - ++i; - if (cgltf_json_strcmp(tokens+i, json_chunk, "SCALAR") == 0) - { - out_accessor->type = cgltf_type_scalar; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "VEC2") == 0) - { - out_accessor->type = cgltf_type_vec2; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "VEC3") == 0) - { - out_accessor->type = cgltf_type_vec3; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "VEC4") == 0) - { - out_accessor->type = cgltf_type_vec4; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "MAT2") == 0) - { - out_accessor->type = cgltf_type_mat2; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "MAT3") == 0) - { - out_accessor->type = cgltf_type_mat3; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "MAT4") == 0) - { - out_accessor->type = cgltf_type_mat4; - } - ++i; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "min") == 0) - { - ++i; - out_accessor->has_min = 1; - // note: we can't parse the precise number of elements since type may not have been computed yet - int min_size = tokens[i].size > 16 ? 16 : tokens[i].size; - i = cgltf_parse_json_float_array(tokens, i, json_chunk, out_accessor->min, min_size); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "max") == 0) - { - ++i; - out_accessor->has_max = 1; - // note: we can't parse the precise number of elements since type may not have been computed yet - int max_size = tokens[i].size > 16 ? 16 : tokens[i].size; - i = cgltf_parse_json_float_array(tokens, i, json_chunk, out_accessor->max, max_size); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "sparse") == 0) - { - out_accessor->is_sparse = 1; - i = cgltf_parse_json_accessor_sparse(options, tokens, i + 1, json_chunk, &out_accessor->sparse); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) - { - i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_accessor->extras); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) - { - i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_accessor->extensions_count, &out_accessor->extensions); - } - else - { - i = cgltf_skip_json(tokens, i+1); - } - - if (i < 0) - { - return i; - } - } - - return i; -} - -static int cgltf_parse_json_texture_transform(jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_texture_transform* out_texture_transform) -{ - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - int size = tokens[i].size; - ++i; - - for (int j = 0; j < size; ++j) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens + i, json_chunk, "offset") == 0) - { - i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_texture_transform->offset, 2); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "rotation") == 0) - { - ++i; - out_texture_transform->rotation = cgltf_json_to_float(tokens + i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "scale") == 0) - { - i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_texture_transform->scale, 2); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "texCoord") == 0) - { - ++i; - out_texture_transform->texcoord = cgltf_json_to_int(tokens + i, json_chunk); - ++i; - } - else - { - i = cgltf_skip_json(tokens, i + 1); - } - - if (i < 0) - { - return i; - } - } - - return i; -} - -static int cgltf_parse_json_texture_view(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_texture_view* out_texture_view) -{ - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - out_texture_view->scale = 1.0f; - cgltf_fill_float_array(out_texture_view->transform.scale, 2, 1.0f); - - int size = tokens[i].size; - ++i; - - for (int j = 0; j < size; ++j) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens + i, json_chunk, "index") == 0) - { - ++i; - out_texture_view->texture = CGLTF_PTRINDEX(cgltf_texture, cgltf_json_to_int(tokens + i, json_chunk)); - ++i; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "texCoord") == 0) - { - ++i; - out_texture_view->texcoord = cgltf_json_to_int(tokens + i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "scale") == 0) - { - ++i; - out_texture_view->scale = cgltf_json_to_float(tokens + i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "strength") == 0) - { - ++i; - out_texture_view->scale = cgltf_json_to_float(tokens + i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) - { - i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_texture_view->extras); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) - { - ++i; - - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - if(out_texture_view->extensions) - { - return CGLTF_ERROR_JSON; - } - - int extensions_size = tokens[i].size; - out_texture_view->extensions_count = 0; - out_texture_view->extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size); - - if (!out_texture_view->extensions) - { - return CGLTF_ERROR_NOMEM; - } - - ++i; - - for (int k = 0; k < extensions_size; ++k) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_texture_transform") == 0) - { - out_texture_view->has_transform = 1; - i = cgltf_parse_json_texture_transform(tokens, i + 1, json_chunk, &out_texture_view->transform); - } - else - { - i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, &(out_texture_view->extensions[out_texture_view->extensions_count++])); - } - - if (i < 0) - { - return i; - } - } - } - else - { - i = cgltf_skip_json(tokens, i + 1); - } - - if (i < 0) - { - return i; - } - } - - return i; -} - -static int cgltf_parse_json_pbr_metallic_roughness(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_pbr_metallic_roughness* out_pbr) -{ - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - int size = tokens[i].size; - ++i; - - for (int j = 0; j < size; ++j) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "metallicFactor") == 0) - { - ++i; - out_pbr->metallic_factor = - cgltf_json_to_float(tokens + i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "roughnessFactor") == 0) - { - ++i; - out_pbr->roughness_factor = - cgltf_json_to_float(tokens+i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "baseColorFactor") == 0) - { - i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_pbr->base_color_factor, 4); - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "baseColorTexture") == 0) - { - i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, - &out_pbr->base_color_texture); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "metallicRoughnessTexture") == 0) - { - i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, - &out_pbr->metallic_roughness_texture); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) - { - i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_pbr->extras); - } - else - { - i = cgltf_skip_json(tokens, i+1); - } - - if (i < 0) - { - return i; - } - } - - return i; -} - -static int cgltf_parse_json_pbr_specular_glossiness(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_pbr_specular_glossiness* out_pbr) -{ - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - int size = tokens[i].size; - ++i; - - for (int j = 0; j < size; ++j) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "diffuseFactor") == 0) - { - i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_pbr->diffuse_factor, 4); - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "specularFactor") == 0) - { - i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_pbr->specular_factor, 3); - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "glossinessFactor") == 0) - { - ++i; - out_pbr->glossiness_factor = cgltf_json_to_float(tokens + i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "diffuseTexture") == 0) - { - i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_pbr->diffuse_texture); - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "specularGlossinessTexture") == 0) - { - i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_pbr->specular_glossiness_texture); - } - else - { - i = cgltf_skip_json(tokens, i+1); - } - - if (i < 0) - { - return i; - } - } - - return i; -} - -static int cgltf_parse_json_clearcoat(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_clearcoat* out_clearcoat) -{ - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - int size = tokens[i].size; - ++i; - - for (int j = 0; j < size; ++j) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "clearcoatFactor") == 0) - { - ++i; - out_clearcoat->clearcoat_factor = cgltf_json_to_float(tokens + i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "clearcoatRoughnessFactor") == 0) - { - ++i; - out_clearcoat->clearcoat_roughness_factor = cgltf_json_to_float(tokens + i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "clearcoatTexture") == 0) - { - i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_clearcoat->clearcoat_texture); - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "clearcoatRoughnessTexture") == 0) - { - i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_clearcoat->clearcoat_roughness_texture); - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "clearcoatNormalTexture") == 0) - { - i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_clearcoat->clearcoat_normal_texture); - } - else - { - i = cgltf_skip_json(tokens, i+1); - } - - if (i < 0) - { - return i; - } - } - - return i; -} - -static int cgltf_parse_json_ior(jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_ior* out_ior) -{ - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - int size = tokens[i].size; - ++i; - - // Default values - out_ior->ior = 1.5f; - - for (int j = 0; j < size; ++j) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "ior") == 0) - { - ++i; - out_ior->ior = cgltf_json_to_float(tokens + i, json_chunk); - ++i; - } - else - { - i = cgltf_skip_json(tokens, i+1); - } - - if (i < 0) - { - return i; - } - } - - return i; -} - -static int cgltf_parse_json_specular(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_specular* out_specular) -{ - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - int size = tokens[i].size; - ++i; - - // Default values - out_specular->specular_factor = 1.0f; - cgltf_fill_float_array(out_specular->specular_color_factor, 3, 1.0f); - - for (int j = 0; j < size; ++j) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "specularFactor") == 0) - { - ++i; - out_specular->specular_factor = cgltf_json_to_float(tokens + i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "specularColorFactor") == 0) - { - i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_specular->specular_color_factor, 3); - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "specularTexture") == 0) - { - i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_specular->specular_texture); - } - else - { - i = cgltf_skip_json(tokens, i+1); - } - - if (i < 0) - { - return i; - } - } - - return i; -} - -static int cgltf_parse_json_transmission(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_transmission* out_transmission) -{ - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - int size = tokens[i].size; - ++i; - - for (int j = 0; j < size; ++j) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "transmissionFactor") == 0) - { - ++i; - out_transmission->transmission_factor = cgltf_json_to_float(tokens + i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "transmissionTexture") == 0) - { - i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, &out_transmission->transmission_texture); - } - else - { - i = cgltf_skip_json(tokens, i+1); - } - - if (i < 0) - { - return i; - } - } - - return i; -} - -static int cgltf_parse_json_image(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_image* out_image) -{ - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - int size = tokens[i].size; - ++i; - - for (int j = 0; j < size; ++j) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens + i, json_chunk, "uri") == 0) - { - i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_image->uri); - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "bufferView") == 0) - { - ++i; - out_image->buffer_view = CGLTF_PTRINDEX(cgltf_buffer_view, cgltf_json_to_int(tokens + i, json_chunk)); - ++i; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "mimeType") == 0) - { - i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_image->mime_type); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "name") == 0) - { - i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_image->name); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) - { - i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_image->extras); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) - { - i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_image->extensions_count, &out_image->extensions); - } - else - { - i = cgltf_skip_json(tokens, i + 1); - } - - if (i < 0) - { - return i; - } - } - - return i; -} - -static int cgltf_parse_json_sampler(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_sampler* out_sampler) -{ - (void)options; - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - out_sampler->wrap_s = 10497; - out_sampler->wrap_t = 10497; - - int size = tokens[i].size; - ++i; - - for (int j = 0; j < size; ++j) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens + i, json_chunk, "magFilter") == 0) - { - ++i; - out_sampler->mag_filter - = cgltf_json_to_int(tokens + i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "minFilter") == 0) - { - ++i; - out_sampler->min_filter - = cgltf_json_to_int(tokens + i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "wrapS") == 0) - { - ++i; - out_sampler->wrap_s - = cgltf_json_to_int(tokens + i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "wrapT") == 0) - { - ++i; - out_sampler->wrap_t - = cgltf_json_to_int(tokens + i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) - { - i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_sampler->extras); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) - { - i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_sampler->extensions_count, &out_sampler->extensions); - } - else - { - i = cgltf_skip_json(tokens, i + 1); - } - - if (i < 0) - { - return i; - } - } - - return i; -} - -static int cgltf_parse_json_texture(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_texture* out_texture) -{ - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - int size = tokens[i].size; - ++i; - - for (int j = 0; j < size; ++j) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0) - { - i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_texture->name); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "sampler") == 0) - { - ++i; - out_texture->sampler = CGLTF_PTRINDEX(cgltf_sampler, cgltf_json_to_int(tokens + i, json_chunk)); - ++i; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "source") == 0) - { - ++i; - out_texture->image = CGLTF_PTRINDEX(cgltf_image, cgltf_json_to_int(tokens + i, json_chunk)); - ++i; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) - { - i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_texture->extras); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) - { - i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_texture->extensions_count, &out_texture->extensions); - } - else - { - i = cgltf_skip_json(tokens, i + 1); - } - - if (i < 0) - { - return i; - } - } - - return i; -} - -static int cgltf_parse_json_material(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_material* out_material) -{ - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - cgltf_fill_float_array(out_material->pbr_metallic_roughness.base_color_factor, 4, 1.0f); - out_material->pbr_metallic_roughness.metallic_factor = 1.0f; - out_material->pbr_metallic_roughness.roughness_factor = 1.0f; - - cgltf_fill_float_array(out_material->pbr_specular_glossiness.diffuse_factor, 4, 1.0f); - cgltf_fill_float_array(out_material->pbr_specular_glossiness.specular_factor, 3, 1.0f); - out_material->pbr_specular_glossiness.glossiness_factor = 1.0f; - - out_material->alpha_cutoff = 0.5f; - - int size = tokens[i].size; - ++i; - - for (int j = 0; j < size; ++j) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0) - { - i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_material->name); - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "pbrMetallicRoughness") == 0) - { - out_material->has_pbr_metallic_roughness = 1; - i = cgltf_parse_json_pbr_metallic_roughness(options, tokens, i + 1, json_chunk, &out_material->pbr_metallic_roughness); - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "emissiveFactor") == 0) - { - i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_material->emissive_factor, 3); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "normalTexture") == 0) - { - i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, - &out_material->normal_texture); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "occlusionTexture") == 0) - { - i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, - &out_material->occlusion_texture); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "emissiveTexture") == 0) - { - i = cgltf_parse_json_texture_view(options, tokens, i + 1, json_chunk, - &out_material->emissive_texture); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "alphaMode") == 0) - { - ++i; - if (cgltf_json_strcmp(tokens + i, json_chunk, "OPAQUE") == 0) - { - out_material->alpha_mode = cgltf_alpha_mode_opaque; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "MASK") == 0) - { - out_material->alpha_mode = cgltf_alpha_mode_mask; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "BLEND") == 0) - { - out_material->alpha_mode = cgltf_alpha_mode_blend; - } - ++i; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "alphaCutoff") == 0) - { - ++i; - out_material->alpha_cutoff = cgltf_json_to_float(tokens + i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "doubleSided") == 0) - { - ++i; - out_material->double_sided = - cgltf_json_to_bool(tokens + i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) - { - i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_material->extras); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) - { - ++i; - - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - if(out_material->extensions) - { - return CGLTF_ERROR_JSON; - } - - int extensions_size = tokens[i].size; - ++i; - out_material->extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size); - out_material->extensions_count= 0; - - if (!out_material->extensions) - { - return CGLTF_ERROR_NOMEM; - } - - for (int k = 0; k < extensions_size; ++k) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_pbrSpecularGlossiness") == 0) - { - out_material->has_pbr_specular_glossiness = 1; - i = cgltf_parse_json_pbr_specular_glossiness(options, tokens, i + 1, json_chunk, &out_material->pbr_specular_glossiness); - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_unlit") == 0) - { - out_material->unlit = 1; - i = cgltf_skip_json(tokens, i+1); - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_clearcoat") == 0) - { - out_material->has_clearcoat = 1; - i = cgltf_parse_json_clearcoat(options, tokens, i + 1, json_chunk, &out_material->clearcoat); - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_ior") == 0) - { - out_material->has_ior = 1; - i = cgltf_parse_json_ior(tokens, i + 1, json_chunk, &out_material->ior); - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_specular") == 0) - { - out_material->has_specular = 1; - i = cgltf_parse_json_specular(options, tokens, i + 1, json_chunk, &out_material->specular); - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_materials_transmission") == 0) - { - out_material->has_transmission = 1; - i = cgltf_parse_json_transmission(options, tokens, i + 1, json_chunk, &out_material->transmission); - } - else - { - i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, &(out_material->extensions[out_material->extensions_count++])); - } - - if (i < 0) - { - return i; - } - } - } - else - { - i = cgltf_skip_json(tokens, i+1); - } - - if (i < 0) - { - return i; - } - } - - return i; -} - -static int cgltf_parse_json_accessors(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) -{ - i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_accessor), (void**)&out_data->accessors, &out_data->accessors_count); - if (i < 0) - { - return i; - } - - for (cgltf_size j = 0; j < out_data->accessors_count; ++j) - { - i = cgltf_parse_json_accessor(options, tokens, i, json_chunk, &out_data->accessors[j]); - if (i < 0) - { - return i; - } - } - return i; -} - -static int cgltf_parse_json_materials(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) -{ - i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_material), (void**)&out_data->materials, &out_data->materials_count); - if (i < 0) - { - return i; - } - - for (cgltf_size j = 0; j < out_data->materials_count; ++j) - { - i = cgltf_parse_json_material(options, tokens, i, json_chunk, &out_data->materials[j]); - if (i < 0) - { - return i; - } - } - return i; -} - -static int cgltf_parse_json_images(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) -{ - i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_image), (void**)&out_data->images, &out_data->images_count); - if (i < 0) - { - return i; - } - - for (cgltf_size j = 0; j < out_data->images_count; ++j) - { - i = cgltf_parse_json_image(options, tokens, i, json_chunk, &out_data->images[j]); - if (i < 0) - { - return i; - } - } - return i; -} - -static int cgltf_parse_json_textures(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) -{ - i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_texture), (void**)&out_data->textures, &out_data->textures_count); - if (i < 0) - { - return i; - } - - for (cgltf_size j = 0; j < out_data->textures_count; ++j) - { - i = cgltf_parse_json_texture(options, tokens, i, json_chunk, &out_data->textures[j]); - if (i < 0) - { - return i; - } - } - return i; -} - -static int cgltf_parse_json_samplers(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) -{ - i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_sampler), (void**)&out_data->samplers, &out_data->samplers_count); - if (i < 0) - { - return i; - } - - for (cgltf_size j = 0; j < out_data->samplers_count; ++j) - { - i = cgltf_parse_json_sampler(options, tokens, i, json_chunk, &out_data->samplers[j]); - if (i < 0) - { - return i; - } - } - return i; -} - -static int cgltf_parse_json_buffer_view(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_buffer_view* out_buffer_view) -{ - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - int size = tokens[i].size; - ++i; - - for (int j = 0; j < size; ++j) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "buffer") == 0) - { - ++i; - out_buffer_view->buffer = CGLTF_PTRINDEX(cgltf_buffer, cgltf_json_to_int(tokens + i, json_chunk)); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteOffset") == 0) - { - ++i; - out_buffer_view->offset = - cgltf_json_to_int(tokens+i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteLength") == 0) - { - ++i; - out_buffer_view->size = - cgltf_json_to_int(tokens+i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "byteStride") == 0) - { - ++i; - out_buffer_view->stride = - cgltf_json_to_int(tokens+i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "target") == 0) - { - ++i; - int type = cgltf_json_to_int(tokens+i, json_chunk); - switch (type) - { - case 34962: - type = cgltf_buffer_view_type_vertices; - break; - case 34963: - type = cgltf_buffer_view_type_indices; - break; - default: - type = cgltf_buffer_view_type_invalid; - break; - } - out_buffer_view->type = (cgltf_buffer_view_type)type; - ++i; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) - { - i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_buffer_view->extras); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) - { - i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_buffer_view->extensions_count, &out_buffer_view->extensions); - } - else - { - i = cgltf_skip_json(tokens, i+1); - } - - if (i < 0) - { - return i; - } - } - - return i; -} - -static int cgltf_parse_json_buffer_views(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) -{ - i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_buffer_view), (void**)&out_data->buffer_views, &out_data->buffer_views_count); - if (i < 0) - { - return i; - } - - for (cgltf_size j = 0; j < out_data->buffer_views_count; ++j) - { - i = cgltf_parse_json_buffer_view(options, tokens, i, json_chunk, &out_data->buffer_views[j]); - if (i < 0) - { - return i; - } - } - return i; -} - -static int cgltf_parse_json_buffer(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_buffer* out_buffer) -{ - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - int size = tokens[i].size; - ++i; - - for (int j = 0; j < size; ++j) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "byteLength") == 0) - { - ++i; - out_buffer->size = - cgltf_json_to_int(tokens+i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "uri") == 0) - { - i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_buffer->uri); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) - { - i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_buffer->extras); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) - { - i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_buffer->extensions_count, &out_buffer->extensions); - } - else - { - i = cgltf_skip_json(tokens, i+1); - } - - if (i < 0) - { - return i; - } - } - - return i; -} - -static int cgltf_parse_json_buffers(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) -{ - i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_buffer), (void**)&out_data->buffers, &out_data->buffers_count); - if (i < 0) - { - return i; - } - - for (cgltf_size j = 0; j < out_data->buffers_count; ++j) - { - i = cgltf_parse_json_buffer(options, tokens, i, json_chunk, &out_data->buffers[j]); - if (i < 0) - { - return i; - } - } - return i; -} - -static int cgltf_parse_json_skin(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_skin* out_skin) -{ - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - int size = tokens[i].size; - ++i; - - for (int j = 0; j < size; ++j) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0) - { - i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_skin->name); - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "joints") == 0) - { - i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_node*), (void**)&out_skin->joints, &out_skin->joints_count); - if (i < 0) - { - return i; - } - - for (cgltf_size k = 0; k < out_skin->joints_count; ++k) - { - out_skin->joints[k] = CGLTF_PTRINDEX(cgltf_node, cgltf_json_to_int(tokens + i, json_chunk)); - ++i; - } - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "skeleton") == 0) - { - ++i; - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE); - out_skin->skeleton = CGLTF_PTRINDEX(cgltf_node, cgltf_json_to_int(tokens + i, json_chunk)); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "inverseBindMatrices") == 0) - { - ++i; - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE); - out_skin->inverse_bind_matrices = CGLTF_PTRINDEX(cgltf_accessor, cgltf_json_to_int(tokens + i, json_chunk)); - ++i; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) - { - i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_skin->extras); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) - { - i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_skin->extensions_count, &out_skin->extensions); - } - else - { - i = cgltf_skip_json(tokens, i+1); - } - - if (i < 0) - { - return i; - } - } - - return i; -} - -static int cgltf_parse_json_skins(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) -{ - i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_skin), (void**)&out_data->skins, &out_data->skins_count); - if (i < 0) - { - return i; - } - - for (cgltf_size j = 0; j < out_data->skins_count; ++j) - { - i = cgltf_parse_json_skin(options, tokens, i, json_chunk, &out_data->skins[j]); - if (i < 0) - { - return i; - } - } - return i; -} - -static int cgltf_parse_json_camera(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_camera* out_camera) -{ - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - int size = tokens[i].size; - ++i; - - for (int j = 0; j < size; ++j) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0) - { - i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_camera->name); - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "type") == 0) - { - ++i; - if (cgltf_json_strcmp(tokens + i, json_chunk, "perspective") == 0) - { - out_camera->type = cgltf_camera_type_perspective; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "orthographic") == 0) - { - out_camera->type = cgltf_camera_type_orthographic; - } - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "perspective") == 0) - { - ++i; - - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - int data_size = tokens[i].size; - ++i; - - out_camera->type = cgltf_camera_type_perspective; - - for (int k = 0; k < data_size; ++k) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "aspectRatio") == 0) - { - ++i; - out_camera->data.perspective.aspect_ratio = cgltf_json_to_float(tokens + i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "yfov") == 0) - { - ++i; - out_camera->data.perspective.yfov = cgltf_json_to_float(tokens + i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "zfar") == 0) - { - ++i; - out_camera->data.perspective.zfar = cgltf_json_to_float(tokens + i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "znear") == 0) - { - ++i; - out_camera->data.perspective.znear = cgltf_json_to_float(tokens + i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) - { - i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_camera->data.perspective.extras); - } - else - { - i = cgltf_skip_json(tokens, i+1); - } - - if (i < 0) - { - return i; - } - } - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "orthographic") == 0) - { - ++i; - - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - int data_size = tokens[i].size; - ++i; - - out_camera->type = cgltf_camera_type_orthographic; - - for (int k = 0; k < data_size; ++k) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "xmag") == 0) - { - ++i; - out_camera->data.orthographic.xmag = cgltf_json_to_float(tokens + i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "ymag") == 0) - { - ++i; - out_camera->data.orthographic.ymag = cgltf_json_to_float(tokens + i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "zfar") == 0) - { - ++i; - out_camera->data.orthographic.zfar = cgltf_json_to_float(tokens + i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "znear") == 0) - { - ++i; - out_camera->data.orthographic.znear = cgltf_json_to_float(tokens + i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) - { - i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_camera->data.orthographic.extras); - } - else - { - i = cgltf_skip_json(tokens, i+1); - } - - if (i < 0) - { - return i; - } - } - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) - { - i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_camera->extras); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) - { - i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_camera->extensions_count, &out_camera->extensions); - } - else - { - i = cgltf_skip_json(tokens, i+1); - } - - if (i < 0) - { - return i; - } - } - - return i; -} - -static int cgltf_parse_json_cameras(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) -{ - i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_camera), (void**)&out_data->cameras, &out_data->cameras_count); - if (i < 0) - { - return i; - } - - for (cgltf_size j = 0; j < out_data->cameras_count; ++j) - { - i = cgltf_parse_json_camera(options, tokens, i, json_chunk, &out_data->cameras[j]); - if (i < 0) - { - return i; - } - } - return i; -} - -static int cgltf_parse_json_light(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_light* out_light) -{ - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - int size = tokens[i].size; - ++i; - - for (int j = 0; j < size; ++j) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0) - { - i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_light->name); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "color") == 0) - { - i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_light->color, 3); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "intensity") == 0) - { - ++i; - out_light->intensity = cgltf_json_to_float(tokens + i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "type") == 0) - { - ++i; - if (cgltf_json_strcmp(tokens + i, json_chunk, "directional") == 0) - { - out_light->type = cgltf_light_type_directional; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "point") == 0) - { - out_light->type = cgltf_light_type_point; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "spot") == 0) - { - out_light->type = cgltf_light_type_spot; - } - ++i; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "range") == 0) - { - ++i; - out_light->range = cgltf_json_to_float(tokens + i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "spot") == 0) - { - ++i; - - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - int data_size = tokens[i].size; - ++i; - - for (int k = 0; k < data_size; ++k) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "innerConeAngle") == 0) - { - ++i; - out_light->spot_inner_cone_angle = cgltf_json_to_float(tokens + i, json_chunk); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "outerConeAngle") == 0) - { - ++i; - out_light->spot_outer_cone_angle = cgltf_json_to_float(tokens + i, json_chunk); - ++i; - } - else - { - i = cgltf_skip_json(tokens, i+1); - } - - if (i < 0) - { - return i; - } - } - } - else - { - i = cgltf_skip_json(tokens, i+1); - } - - if (i < 0) - { - return i; - } - } - - return i; -} - -static int cgltf_parse_json_lights(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) -{ - i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_light), (void**)&out_data->lights, &out_data->lights_count); - if (i < 0) - { - return i; - } - - for (cgltf_size j = 0; j < out_data->lights_count; ++j) - { - i = cgltf_parse_json_light(options, tokens, i, json_chunk, &out_data->lights[j]); - if (i < 0) - { - return i; - } - } - return i; -} - -static int cgltf_parse_json_node(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_node* out_node) -{ - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - out_node->rotation[3] = 1.0f; - out_node->scale[0] = 1.0f; - out_node->scale[1] = 1.0f; - out_node->scale[2] = 1.0f; - out_node->matrix[0] = 1.0f; - out_node->matrix[5] = 1.0f; - out_node->matrix[10] = 1.0f; - out_node->matrix[15] = 1.0f; - - int size = tokens[i].size; - ++i; - - for (int j = 0; j < size; ++j) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0) - { - i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_node->name); - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "children") == 0) - { - i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_node*), (void**)&out_node->children, &out_node->children_count); - if (i < 0) - { - return i; - } - - for (cgltf_size k = 0; k < out_node->children_count; ++k) - { - out_node->children[k] = CGLTF_PTRINDEX(cgltf_node, cgltf_json_to_int(tokens + i, json_chunk)); - ++i; - } - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "mesh") == 0) - { - ++i; - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE); - out_node->mesh = CGLTF_PTRINDEX(cgltf_mesh, cgltf_json_to_int(tokens + i, json_chunk)); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "skin") == 0) - { - ++i; - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE); - out_node->skin = CGLTF_PTRINDEX(cgltf_skin, cgltf_json_to_int(tokens + i, json_chunk)); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "camera") == 0) - { - ++i; - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE); - out_node->camera = CGLTF_PTRINDEX(cgltf_camera, cgltf_json_to_int(tokens + i, json_chunk)); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "translation") == 0) - { - out_node->has_translation = 1; - i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_node->translation, 3); - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "rotation") == 0) - { - out_node->has_rotation = 1; - i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_node->rotation, 4); - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "scale") == 0) - { - out_node->has_scale = 1; - i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_node->scale, 3); - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "matrix") == 0) - { - out_node->has_matrix = 1; - i = cgltf_parse_json_float_array(tokens, i + 1, json_chunk, out_node->matrix, 16); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "weights") == 0) - { - i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_float), (void**)&out_node->weights, &out_node->weights_count); - if (i < 0) - { - return i; - } - - i = cgltf_parse_json_float_array(tokens, i - 1, json_chunk, out_node->weights, (int)out_node->weights_count); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) - { - i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_node->extras); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) - { - ++i; - - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - if(out_node->extensions) - { - return CGLTF_ERROR_JSON; - } - - int extensions_size = tokens[i].size; - out_node->extensions_count= 0; - out_node->extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size); - - if (!out_node->extensions) - { - return CGLTF_ERROR_NOMEM; - } - - ++i; - - for (int k = 0; k < extensions_size; ++k) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_lights_punctual") == 0) - { - ++i; - - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - int data_size = tokens[i].size; - ++i; - - for (int m = 0; m < data_size; ++m) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens + i, json_chunk, "light") == 0) - { - ++i; - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_PRIMITIVE); - out_node->light = CGLTF_PTRINDEX(cgltf_light, cgltf_json_to_int(tokens + i, json_chunk)); - ++i; - } - else - { - i = cgltf_skip_json(tokens, i + 1); - } - - if (i < 0) - { - return i; - } - } - } - else - { - i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, &(out_node->extensions[out_node->extensions_count++])); - } - - if (i < 0) - { - return i; - } - } - } - else - { - i = cgltf_skip_json(tokens, i+1); - } - - if (i < 0) - { - return i; - } - } - - return i; -} - -static int cgltf_parse_json_nodes(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) -{ - i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_node), (void**)&out_data->nodes, &out_data->nodes_count); - if (i < 0) - { - return i; - } - - for (cgltf_size j = 0; j < out_data->nodes_count; ++j) - { - i = cgltf_parse_json_node(options, tokens, i, json_chunk, &out_data->nodes[j]); - if (i < 0) - { - return i; - } - } - return i; -} - -static int cgltf_parse_json_scene(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_scene* out_scene) -{ - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - int size = tokens[i].size; - ++i; - - for (int j = 0; j < size; ++j) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0) - { - i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_scene->name); - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "nodes") == 0) - { - i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_node*), (void**)&out_scene->nodes, &out_scene->nodes_count); - if (i < 0) - { - return i; - } - - for (cgltf_size k = 0; k < out_scene->nodes_count; ++k) - { - out_scene->nodes[k] = CGLTF_PTRINDEX(cgltf_node, cgltf_json_to_int(tokens + i, json_chunk)); - ++i; - } - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) - { - i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_scene->extras); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) - { - i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_scene->extensions_count, &out_scene->extensions); - } - else - { - i = cgltf_skip_json(tokens, i+1); - } - - if (i < 0) - { - return i; - } - } - - return i; -} - -static int cgltf_parse_json_scenes(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) -{ - i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_scene), (void**)&out_data->scenes, &out_data->scenes_count); - if (i < 0) - { - return i; - } - - for (cgltf_size j = 0; j < out_data->scenes_count; ++j) - { - i = cgltf_parse_json_scene(options, tokens, i, json_chunk, &out_data->scenes[j]); - if (i < 0) - { - return i; - } - } - return i; -} - -static int cgltf_parse_json_animation_sampler(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_animation_sampler* out_sampler) -{ - (void)options; - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - int size = tokens[i].size; - ++i; - - for (int j = 0; j < size; ++j) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "input") == 0) - { - ++i; - out_sampler->input = CGLTF_PTRINDEX(cgltf_accessor, cgltf_json_to_int(tokens + i, json_chunk)); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "output") == 0) - { - ++i; - out_sampler->output = CGLTF_PTRINDEX(cgltf_accessor, cgltf_json_to_int(tokens + i, json_chunk)); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "interpolation") == 0) - { - ++i; - if (cgltf_json_strcmp(tokens + i, json_chunk, "LINEAR") == 0) - { - out_sampler->interpolation = cgltf_interpolation_type_linear; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "STEP") == 0) - { - out_sampler->interpolation = cgltf_interpolation_type_step; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "CUBICSPLINE") == 0) - { - out_sampler->interpolation = cgltf_interpolation_type_cubic_spline; - } - ++i; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) - { - i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_sampler->extras); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) - { - i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_sampler->extensions_count, &out_sampler->extensions); - } - else - { - i = cgltf_skip_json(tokens, i+1); - } - - if (i < 0) - { - return i; - } - } - - return i; -} - -static int cgltf_parse_json_animation_channel(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_animation_channel* out_channel) -{ - (void)options; - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - int size = tokens[i].size; - ++i; - - for (int j = 0; j < size; ++j) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "sampler") == 0) - { - ++i; - out_channel->sampler = CGLTF_PTRINDEX(cgltf_animation_sampler, cgltf_json_to_int(tokens + i, json_chunk)); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "target") == 0) - { - ++i; - - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - int target_size = tokens[i].size; - ++i; - - for (int k = 0; k < target_size; ++k) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "node") == 0) - { - ++i; - out_channel->target_node = CGLTF_PTRINDEX(cgltf_node, cgltf_json_to_int(tokens + i, json_chunk)); - ++i; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "path") == 0) - { - ++i; - if (cgltf_json_strcmp(tokens+i, json_chunk, "translation") == 0) - { - out_channel->target_path = cgltf_animation_path_type_translation; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "rotation") == 0) - { - out_channel->target_path = cgltf_animation_path_type_rotation; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "scale") == 0) - { - out_channel->target_path = cgltf_animation_path_type_scale; - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "weights") == 0) - { - out_channel->target_path = cgltf_animation_path_type_weights; - } - ++i; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) - { - i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_channel->extras); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) - { - i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_channel->extensions_count, &out_channel->extensions); - } - else - { - i = cgltf_skip_json(tokens, i+1); - } - - if (i < 0) - { - return i; - } - } - } - else - { - i = cgltf_skip_json(tokens, i+1); - } - - if (i < 0) - { - return i; - } - } - - return i; -} - -static int cgltf_parse_json_animation(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_animation* out_animation) -{ - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - int size = tokens[i].size; - ++i; - - for (int j = 0; j < size; ++j) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "name") == 0) - { - i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_animation->name); - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "samplers") == 0) - { - i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_animation_sampler), (void**)&out_animation->samplers, &out_animation->samplers_count); - if (i < 0) - { - return i; - } - - for (cgltf_size k = 0; k < out_animation->samplers_count; ++k) - { - i = cgltf_parse_json_animation_sampler(options, tokens, i, json_chunk, &out_animation->samplers[k]); - if (i < 0) - { - return i; - } - } - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "channels") == 0) - { - i = cgltf_parse_json_array(options, tokens, i + 1, json_chunk, sizeof(cgltf_animation_channel), (void**)&out_animation->channels, &out_animation->channels_count); - if (i < 0) - { - return i; - } - - for (cgltf_size k = 0; k < out_animation->channels_count; ++k) - { - i = cgltf_parse_json_animation_channel(options, tokens, i, json_chunk, &out_animation->channels[k]); - if (i < 0) - { - return i; - } - } - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) - { - i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_animation->extras); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) - { - i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_animation->extensions_count, &out_animation->extensions); - } - else - { - i = cgltf_skip_json(tokens, i+1); - } - - if (i < 0) - { - return i; - } - } - - return i; -} - -static int cgltf_parse_json_animations(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) -{ - i = cgltf_parse_json_array(options, tokens, i, json_chunk, sizeof(cgltf_animation), (void**)&out_data->animations, &out_data->animations_count); - if (i < 0) - { - return i; - } - - for (cgltf_size j = 0; j < out_data->animations_count; ++j) - { - i = cgltf_parse_json_animation(options, tokens, i, json_chunk, &out_data->animations[j]); - if (i < 0) - { - return i; - } - } - return i; -} - -static int cgltf_parse_json_asset(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_asset* out_asset) -{ - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - int size = tokens[i].size; - ++i; - - for (int j = 0; j < size; ++j) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "copyright") == 0) - { - i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_asset->copyright); - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "generator") == 0) - { - i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_asset->generator); - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "version") == 0) - { - i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_asset->version); - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "minVersion") == 0) - { - i = cgltf_parse_json_string(options, tokens, i + 1, json_chunk, &out_asset->min_version); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extras") == 0) - { - i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_asset->extras); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) - { - i = cgltf_parse_json_unprocessed_extensions(options, tokens, i, json_chunk, &out_asset->extensions_count, &out_asset->extensions); - } - else - { - i = cgltf_skip_json(tokens, i+1); - } - - if (i < 0) - { - return i; - } - } - - if (out_asset->version && CGLTF_ATOF(out_asset->version) < 2) - { - return CGLTF_ERROR_LEGACY; - } - - return i; -} - -cgltf_size cgltf_num_components(cgltf_type type) { - switch (type) - { - case cgltf_type_vec2: - return 2; - case cgltf_type_vec3: - return 3; - case cgltf_type_vec4: - return 4; - case cgltf_type_mat2: - return 4; - case cgltf_type_mat3: - return 9; - case cgltf_type_mat4: - return 16; - case cgltf_type_invalid: - case cgltf_type_scalar: - default: - return 1; - } -} - -static cgltf_size cgltf_component_size(cgltf_component_type component_type) { - switch (component_type) - { - case cgltf_component_type_r_8: - case cgltf_component_type_r_8u: - return 1; - case cgltf_component_type_r_16: - case cgltf_component_type_r_16u: - return 2; - case cgltf_component_type_r_32u: - case cgltf_component_type_r_32f: - return 4; - case cgltf_component_type_invalid: - default: - return 0; - } -} - -static cgltf_size cgltf_calc_size(cgltf_type type, cgltf_component_type component_type) -{ - cgltf_size component_size = cgltf_component_size(component_type); - if (type == cgltf_type_mat2 && component_size == 1) - { - return 8 * component_size; - } - else if (type == cgltf_type_mat3 && (component_size == 1 || component_size == 2)) - { - return 12 * component_size; - } - return component_size * cgltf_num_components(type); -} - -static int cgltf_fixup_pointers(cgltf_data* out_data); - -static int cgltf_parse_json_root(cgltf_options* options, jsmntok_t const* tokens, int i, const uint8_t* json_chunk, cgltf_data* out_data) -{ - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - int size = tokens[i].size; - ++i; - - for (int j = 0; j < size; ++j) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens + i, json_chunk, "asset") == 0) - { - i = cgltf_parse_json_asset(options, tokens, i + 1, json_chunk, &out_data->asset); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "meshes") == 0) - { - i = cgltf_parse_json_meshes(options, tokens, i + 1, json_chunk, out_data); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "accessors") == 0) - { - i = cgltf_parse_json_accessors(options, tokens, i + 1, json_chunk, out_data); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "bufferViews") == 0) - { - i = cgltf_parse_json_buffer_views(options, tokens, i + 1, json_chunk, out_data); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "buffers") == 0) - { - i = cgltf_parse_json_buffers(options, tokens, i + 1, json_chunk, out_data); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "materials") == 0) - { - i = cgltf_parse_json_materials(options, tokens, i + 1, json_chunk, out_data); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "images") == 0) - { - i = cgltf_parse_json_images(options, tokens, i + 1, json_chunk, out_data); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "textures") == 0) - { - i = cgltf_parse_json_textures(options, tokens, i + 1, json_chunk, out_data); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "samplers") == 0) - { - i = cgltf_parse_json_samplers(options, tokens, i + 1, json_chunk, out_data); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "skins") == 0) - { - i = cgltf_parse_json_skins(options, tokens, i + 1, json_chunk, out_data); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "cameras") == 0) - { - i = cgltf_parse_json_cameras(options, tokens, i + 1, json_chunk, out_data); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "nodes") == 0) - { - i = cgltf_parse_json_nodes(options, tokens, i + 1, json_chunk, out_data); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "scenes") == 0) - { - i = cgltf_parse_json_scenes(options, tokens, i + 1, json_chunk, out_data); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "scene") == 0) - { - ++i; - out_data->scene = CGLTF_PTRINDEX(cgltf_scene, cgltf_json_to_int(tokens + i, json_chunk)); - ++i; - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "animations") == 0) - { - i = cgltf_parse_json_animations(options, tokens, i + 1, json_chunk, out_data); - } - else if (cgltf_json_strcmp(tokens+i, json_chunk, "extras") == 0) - { - i = cgltf_parse_json_extras(tokens, i + 1, json_chunk, &out_data->extras); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensions") == 0) - { - ++i; - - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - if(out_data->data_extensions) - { - return CGLTF_ERROR_JSON; - } - - int extensions_size = tokens[i].size; - out_data->data_extensions_count = 0; - out_data->data_extensions = (cgltf_extension*)cgltf_calloc(options, sizeof(cgltf_extension), extensions_size); - - if (!out_data->data_extensions) - { - return CGLTF_ERROR_NOMEM; - } - - ++i; - - for (int k = 0; k < extensions_size; ++k) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens+i, json_chunk, "KHR_lights_punctual") == 0) - { - ++i; - - CGLTF_CHECK_TOKTYPE(tokens[i], JSMN_OBJECT); - - int data_size = tokens[i].size; - ++i; - - for (int m = 0; m < data_size; ++m) - { - CGLTF_CHECK_KEY(tokens[i]); - - if (cgltf_json_strcmp(tokens + i, json_chunk, "lights") == 0) - { - i = cgltf_parse_json_lights(options, tokens, i + 1, json_chunk, out_data); - } - else - { - i = cgltf_skip_json(tokens, i + 1); - } - - if (i < 0) - { - return i; - } - } - } - else - { - i = cgltf_parse_json_unprocessed_extension(options, tokens, i, json_chunk, &(out_data->data_extensions[out_data->data_extensions_count++])); - } - - if (i < 0) - { - return i; - } - } - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensionsUsed") == 0) - { - i = cgltf_parse_json_string_array(options, tokens, i + 1, json_chunk, &out_data->extensions_used, &out_data->extensions_used_count); - } - else if (cgltf_json_strcmp(tokens + i, json_chunk, "extensionsRequired") == 0) - { - i = cgltf_parse_json_string_array(options, tokens, i + 1, json_chunk, &out_data->extensions_required, &out_data->extensions_required_count); - } - else - { - i = cgltf_skip_json(tokens, i + 1); - } - - if (i < 0) - { - return i; - } - } - - return i; -} - -cgltf_result cgltf_parse_json(cgltf_options* options, const uint8_t* json_chunk, cgltf_size size, cgltf_data** out_data) -{ - jsmn_parser parser = { 0, 0, 0 }; - - if (options->json_token_count == 0) - { - int token_count = jsmn_parse(&parser, (const char*)json_chunk, size, NULL, 0); - - if (token_count <= 0) - { - return cgltf_result_invalid_json; - } - - options->json_token_count = token_count; - } - - jsmntok_t* tokens = (jsmntok_t*)options->memory.alloc(options->memory.user_data, sizeof(jsmntok_t) * (options->json_token_count + 1)); - - if (!tokens) - { - return cgltf_result_out_of_memory; - } - - jsmn_init(&parser); - - int token_count = jsmn_parse(&parser, (const char*)json_chunk, size, tokens, options->json_token_count); - - if (token_count <= 0) - { - options->memory.free(options->memory.user_data, tokens); - return cgltf_result_invalid_json; - } - - // this makes sure that we always have an UNDEFINED token at the end of the stream - // for invalid JSON inputs this makes sure we don't perform out of bound reads of token data - tokens[token_count].type = JSMN_UNDEFINED; - - cgltf_data* data = (cgltf_data*)options->memory.alloc(options->memory.user_data, sizeof(cgltf_data)); - - if (!data) - { - options->memory.free(options->memory.user_data, tokens); - return cgltf_result_out_of_memory; - } - - memset(data, 0, sizeof(cgltf_data)); - data->memory = options->memory; - data->file = options->file; - - int i = cgltf_parse_json_root(options, tokens, 0, json_chunk, data); - - options->memory.free(options->memory.user_data, tokens); - - if (i < 0) - { - cgltf_free(data); - - switch (i) - { - case CGLTF_ERROR_NOMEM: return cgltf_result_out_of_memory; - case CGLTF_ERROR_LEGACY: return cgltf_result_legacy_gltf; - default: return cgltf_result_invalid_gltf; - } - } - - if (cgltf_fixup_pointers(data) < 0) - { - cgltf_free(data); - return cgltf_result_invalid_gltf; - } - - data->json = (const char*)json_chunk; - data->json_size = size; - - *out_data = data; - - return cgltf_result_success; -} - -static int cgltf_fixup_pointers(cgltf_data* data) -{ - for (cgltf_size i = 0; i < data->meshes_count; ++i) - { - for (cgltf_size j = 0; j < data->meshes[i].primitives_count; ++j) - { - CGLTF_PTRFIXUP(data->meshes[i].primitives[j].indices, data->accessors, data->accessors_count); - CGLTF_PTRFIXUP(data->meshes[i].primitives[j].material, data->materials, data->materials_count); - - for (cgltf_size k = 0; k < data->meshes[i].primitives[j].attributes_count; ++k) - { - CGLTF_PTRFIXUP_REQ(data->meshes[i].primitives[j].attributes[k].data, data->accessors, data->accessors_count); - } - - for (cgltf_size k = 0; k < data->meshes[i].primitives[j].targets_count; ++k) - { - for (cgltf_size m = 0; m < data->meshes[i].primitives[j].targets[k].attributes_count; ++m) - { - CGLTF_PTRFIXUP_REQ(data->meshes[i].primitives[j].targets[k].attributes[m].data, data->accessors, data->accessors_count); - } - } - - if (data->meshes[i].primitives[j].has_draco_mesh_compression) - { - CGLTF_PTRFIXUP_REQ(data->meshes[i].primitives[j].draco_mesh_compression.buffer_view, data->buffer_views, data->buffer_views_count); - for (cgltf_size m = 0; m < data->meshes[i].primitives[j].draco_mesh_compression.attributes_count; ++m) - { - CGLTF_PTRFIXUP_REQ(data->meshes[i].primitives[j].draco_mesh_compression.attributes[m].data, data->accessors, data->accessors_count); - } - } - } - } - - for (cgltf_size i = 0; i < data->accessors_count; ++i) - { - CGLTF_PTRFIXUP(data->accessors[i].buffer_view, data->buffer_views, data->buffer_views_count); - - if (data->accessors[i].is_sparse) - { - CGLTF_PTRFIXUP_REQ(data->accessors[i].sparse.indices_buffer_view, data->buffer_views, data->buffer_views_count); - CGLTF_PTRFIXUP_REQ(data->accessors[i].sparse.values_buffer_view, data->buffer_views, data->buffer_views_count); - } - - if (data->accessors[i].buffer_view) - { - data->accessors[i].stride = data->accessors[i].buffer_view->stride; - } - - if (data->accessors[i].stride == 0) - { - data->accessors[i].stride = cgltf_calc_size(data->accessors[i].type, data->accessors[i].component_type); - } - } - - for (cgltf_size i = 0; i < data->textures_count; ++i) - { - CGLTF_PTRFIXUP(data->textures[i].image, data->images, data->images_count); - CGLTF_PTRFIXUP(data->textures[i].sampler, data->samplers, data->samplers_count); - } - - for (cgltf_size i = 0; i < data->images_count; ++i) - { - CGLTF_PTRFIXUP(data->images[i].buffer_view, data->buffer_views, data->buffer_views_count); - } - - for (cgltf_size i = 0; i < data->materials_count; ++i) - { - CGLTF_PTRFIXUP(data->materials[i].normal_texture.texture, data->textures, data->textures_count); - CGLTF_PTRFIXUP(data->materials[i].emissive_texture.texture, data->textures, data->textures_count); - CGLTF_PTRFIXUP(data->materials[i].occlusion_texture.texture, data->textures, data->textures_count); - - CGLTF_PTRFIXUP(data->materials[i].pbr_metallic_roughness.base_color_texture.texture, data->textures, data->textures_count); - CGLTF_PTRFIXUP(data->materials[i].pbr_metallic_roughness.metallic_roughness_texture.texture, data->textures, data->textures_count); - - CGLTF_PTRFIXUP(data->materials[i].pbr_specular_glossiness.diffuse_texture.texture, data->textures, data->textures_count); - CGLTF_PTRFIXUP(data->materials[i].pbr_specular_glossiness.specular_glossiness_texture.texture, data->textures, data->textures_count); - - CGLTF_PTRFIXUP(data->materials[i].clearcoat.clearcoat_texture.texture, data->textures, data->textures_count); - CGLTF_PTRFIXUP(data->materials[i].clearcoat.clearcoat_roughness_texture.texture, data->textures, data->textures_count); - CGLTF_PTRFIXUP(data->materials[i].clearcoat.clearcoat_normal_texture.texture, data->textures, data->textures_count); - - CGLTF_PTRFIXUP(data->materials[i].specular.specular_texture.texture, data->textures, data->textures_count); - - CGLTF_PTRFIXUP(data->materials[i].transmission.transmission_texture.texture, data->textures, data->textures_count); - } - - for (cgltf_size i = 0; i < data->buffer_views_count; ++i) - { - CGLTF_PTRFIXUP_REQ(data->buffer_views[i].buffer, data->buffers, data->buffers_count); - } - - for (cgltf_size i = 0; i < data->skins_count; ++i) - { - for (cgltf_size j = 0; j < data->skins[i].joints_count; ++j) - { - CGLTF_PTRFIXUP_REQ(data->skins[i].joints[j], data->nodes, data->nodes_count); - } - - CGLTF_PTRFIXUP(data->skins[i].skeleton, data->nodes, data->nodes_count); - CGLTF_PTRFIXUP(data->skins[i].inverse_bind_matrices, data->accessors, data->accessors_count); - } - - for (cgltf_size i = 0; i < data->nodes_count; ++i) - { - for (cgltf_size j = 0; j < data->nodes[i].children_count; ++j) - { - CGLTF_PTRFIXUP_REQ(data->nodes[i].children[j], data->nodes, data->nodes_count); - - if (data->nodes[i].children[j]->parent) - { - return CGLTF_ERROR_JSON; - } - - data->nodes[i].children[j]->parent = &data->nodes[i]; - } - - CGLTF_PTRFIXUP(data->nodes[i].mesh, data->meshes, data->meshes_count); - CGLTF_PTRFIXUP(data->nodes[i].skin, data->skins, data->skins_count); - CGLTF_PTRFIXUP(data->nodes[i].camera, data->cameras, data->cameras_count); - CGLTF_PTRFIXUP(data->nodes[i].light, data->lights, data->lights_count); - } - - for (cgltf_size i = 0; i < data->scenes_count; ++i) - { - for (cgltf_size j = 0; j < data->scenes[i].nodes_count; ++j) - { - CGLTF_PTRFIXUP_REQ(data->scenes[i].nodes[j], data->nodes, data->nodes_count); - - if (data->scenes[i].nodes[j]->parent) - { - return CGLTF_ERROR_JSON; - } - } - } - - CGLTF_PTRFIXUP(data->scene, data->scenes, data->scenes_count); - - for (cgltf_size i = 0; i < data->animations_count; ++i) - { - for (cgltf_size j = 0; j < data->animations[i].samplers_count; ++j) - { - CGLTF_PTRFIXUP_REQ(data->animations[i].samplers[j].input, data->accessors, data->accessors_count); - CGLTF_PTRFIXUP_REQ(data->animations[i].samplers[j].output, data->accessors, data->accessors_count); - } - - for (cgltf_size j = 0; j < data->animations[i].channels_count; ++j) - { - CGLTF_PTRFIXUP_REQ(data->animations[i].channels[j].sampler, data->animations[i].samplers, data->animations[i].samplers_count); - CGLTF_PTRFIXUP(data->animations[i].channels[j].target_node, data->nodes, data->nodes_count); - } - } - - return 0; -} - -/* - * -- jsmn.c start -- - * Source: https://github.com/zserge/jsmn - * License: MIT - * - * Copyright (c) 2010 Serge A. Zaitsev - - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -/** - * Allocates a fresh unused token from the token pull. - */ -static jsmntok_t *jsmn_alloc_token(jsmn_parser *parser, - jsmntok_t *tokens, size_t num_tokens) { - jsmntok_t *tok; - if (parser->toknext >= num_tokens) { - return NULL; - } - tok = &tokens[parser->toknext++]; - tok->start = tok->end = -1; - tok->size = 0; -#ifdef JSMN_PARENT_LINKS - tok->parent = -1; -#endif - return tok; -} - -/** - * Fills token type and boundaries. - */ -static void jsmn_fill_token(jsmntok_t *token, jsmntype_t type, - int start, int end) { - token->type = type; - token->start = start; - token->end = end; - token->size = 0; -} - -/** - * Fills next available token with JSON primitive. - */ -static int jsmn_parse_primitive(jsmn_parser *parser, const char *js, - size_t len, jsmntok_t *tokens, size_t num_tokens) { - jsmntok_t *token; - int start; - - start = parser->pos; - - for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { - switch (js[parser->pos]) { -#ifndef JSMN_STRICT - /* In strict mode primitive must be followed by "," or "}" or "]" */ - case ':': -#endif - case '\t' : case '\r' : case '\n' : case ' ' : - case ',' : case ']' : case '}' : - goto found; - } - if (js[parser->pos] < 32 || js[parser->pos] >= 127) { - parser->pos = start; - return JSMN_ERROR_INVAL; - } - } -#ifdef JSMN_STRICT - /* In strict mode primitive must be followed by a comma/object/array */ - parser->pos = start; - return JSMN_ERROR_PART; -#endif - -found: - if (tokens == NULL) { - parser->pos--; - return 0; - } - token = jsmn_alloc_token(parser, tokens, num_tokens); - if (token == NULL) { - parser->pos = start; - return JSMN_ERROR_NOMEM; - } - jsmn_fill_token(token, JSMN_PRIMITIVE, start, parser->pos); -#ifdef JSMN_PARENT_LINKS - token->parent = parser->toksuper; -#endif - parser->pos--; - return 0; -} - -/** - * Fills next token with JSON string. - */ -static int jsmn_parse_string(jsmn_parser *parser, const char *js, - size_t len, jsmntok_t *tokens, size_t num_tokens) { - jsmntok_t *token; - - int start = parser->pos; - - parser->pos++; - - /* Skip starting quote */ - for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { - char c = js[parser->pos]; - - /* Quote: end of string */ - if (c == '\"') { - if (tokens == NULL) { - return 0; - } - token = jsmn_alloc_token(parser, tokens, num_tokens); - if (token == NULL) { - parser->pos = start; - return JSMN_ERROR_NOMEM; - } - jsmn_fill_token(token, JSMN_STRING, start+1, parser->pos); -#ifdef JSMN_PARENT_LINKS - token->parent = parser->toksuper; -#endif - return 0; - } - - /* Backslash: Quoted symbol expected */ - if (c == '\\' && parser->pos + 1 < len) { - int i; - parser->pos++; - switch (js[parser->pos]) { - /* Allowed escaped symbols */ - case '\"': case '/' : case '\\' : case 'b' : - case 'f' : case 'r' : case 'n' : case 't' : - break; - /* Allows escaped symbol \uXXXX */ - case 'u': - parser->pos++; - for(i = 0; i < 4 && parser->pos < len && js[parser->pos] != '\0'; i++) { - /* If it isn't a hex character we have an error */ - if(!((js[parser->pos] >= 48 && js[parser->pos] <= 57) || /* 0-9 */ - (js[parser->pos] >= 65 && js[parser->pos] <= 70) || /* A-F */ - (js[parser->pos] >= 97 && js[parser->pos] <= 102))) { /* a-f */ - parser->pos = start; - return JSMN_ERROR_INVAL; - } - parser->pos++; - } - parser->pos--; - break; - /* Unexpected symbol */ - default: - parser->pos = start; - return JSMN_ERROR_INVAL; - } - } - } - parser->pos = start; - return JSMN_ERROR_PART; -} - -/** - * Parse JSON string and fill tokens. - */ -static int jsmn_parse(jsmn_parser *parser, const char *js, size_t len, - jsmntok_t *tokens, size_t num_tokens) { - int r; - int i; - jsmntok_t *token; - int count = parser->toknext; - - for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { - char c; - jsmntype_t type; - - c = js[parser->pos]; - switch (c) { - case '{': case '[': - count++; - if (tokens == NULL) { - break; - } - token = jsmn_alloc_token(parser, tokens, num_tokens); - if (token == NULL) - return JSMN_ERROR_NOMEM; - if (parser->toksuper != -1) { - tokens[parser->toksuper].size++; -#ifdef JSMN_PARENT_LINKS - token->parent = parser->toksuper; -#endif - } - token->type = (c == '{' ? JSMN_OBJECT : JSMN_ARRAY); - token->start = parser->pos; - parser->toksuper = parser->toknext - 1; - break; - case '}': case ']': - if (tokens == NULL) - break; - type = (c == '}' ? JSMN_OBJECT : JSMN_ARRAY); -#ifdef JSMN_PARENT_LINKS - if (parser->toknext < 1) { - return JSMN_ERROR_INVAL; - } - token = &tokens[parser->toknext - 1]; - for (;;) { - if (token->start != -1 && token->end == -1) { - if (token->type != type) { - return JSMN_ERROR_INVAL; - } - token->end = parser->pos + 1; - parser->toksuper = token->parent; - break; - } - if (token->parent == -1) { - if(token->type != type || parser->toksuper == -1) { - return JSMN_ERROR_INVAL; - } - break; - } - token = &tokens[token->parent]; - } -#else - for (i = parser->toknext - 1; i >= 0; i--) { - token = &tokens[i]; - if (token->start != -1 && token->end == -1) { - if (token->type != type) { - return JSMN_ERROR_INVAL; - } - parser->toksuper = -1; - token->end = parser->pos + 1; - break; - } - } - /* Error if unmatched closing bracket */ - if (i == -1) return JSMN_ERROR_INVAL; - for (; i >= 0; i--) { - token = &tokens[i]; - if (token->start != -1 && token->end == -1) { - parser->toksuper = i; - break; - } - } -#endif - break; - case '\"': - r = jsmn_parse_string(parser, js, len, tokens, num_tokens); - if (r < 0) return r; - count++; - if (parser->toksuper != -1 && tokens != NULL) - tokens[parser->toksuper].size++; - break; - case '\t' : case '\r' : case '\n' : case ' ': - break; - case ':': - parser->toksuper = parser->toknext - 1; - break; - case ',': - if (tokens != NULL && parser->toksuper != -1 && - tokens[parser->toksuper].type != JSMN_ARRAY && - tokens[parser->toksuper].type != JSMN_OBJECT) { -#ifdef JSMN_PARENT_LINKS - parser->toksuper = tokens[parser->toksuper].parent; -#else - for (i = parser->toknext - 1; i >= 0; i--) { - if (tokens[i].type == JSMN_ARRAY || tokens[i].type == JSMN_OBJECT) { - if (tokens[i].start != -1 && tokens[i].end == -1) { - parser->toksuper = i; - break; - } - } - } -#endif - } - break; -#ifdef JSMN_STRICT - /* In strict mode primitives are: numbers and booleans */ - case '-': case '0': case '1' : case '2': case '3' : case '4': - case '5': case '6': case '7' : case '8': case '9': - case 't': case 'f': case 'n' : - /* And they must not be keys of the object */ - if (tokens != NULL && parser->toksuper != -1) { - jsmntok_t *t = &tokens[parser->toksuper]; - if (t->type == JSMN_OBJECT || - (t->type == JSMN_STRING && t->size != 0)) { - return JSMN_ERROR_INVAL; - } - } -#else - /* In non-strict mode every unquoted value is a primitive */ - default: -#endif - r = jsmn_parse_primitive(parser, js, len, tokens, num_tokens); - if (r < 0) return r; - count++; - if (parser->toksuper != -1 && tokens != NULL) - tokens[parser->toksuper].size++; - break; - -#ifdef JSMN_STRICT - /* Unexpected char in strict mode */ - default: - return JSMN_ERROR_INVAL; -#endif - } - } - - if (tokens != NULL) { - for (i = parser->toknext - 1; i >= 0; i--) { - /* Unmatched opened object or array */ - if (tokens[i].start != -1 && tokens[i].end == -1) { - return JSMN_ERROR_PART; - } - } - } - - return count; -} - -/** - * Creates a new parser based over a given buffer with an array of tokens - * available. - */ -static void jsmn_init(jsmn_parser *parser) { - parser->pos = 0; - parser->toknext = 0; - parser->toksuper = -1; -} -/* - * -- jsmn.c end -- - */ - -#endif /* #ifdef CGLTF_IMPLEMENTATION */ - -/* cgltf is distributed under MIT license: - * - * Copyright (c) 2018 Johannes Kuhlmann - - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ diff --git a/gfx/contrib/cgltf/cgltf_write.h b/gfx/contrib/cgltf/cgltf_write.h deleted file mode 100644 index 2096a5b..0000000 --- a/gfx/contrib/cgltf/cgltf_write.h +++ /dev/null @@ -1,1173 +0,0 @@ -/** - * cgltf_write - a single-file glTF 2.0 writer written in C99. - * - * Version: 1.7 - * - * Website: https://github.com/jkuhlmann/cgltf - * - * Distributed under the MIT License, see notice at the end of this file. - * - * Building: - * Include this file where you need the struct and function - * declarations. Have exactly one source file where you define - * `CGLTF_WRITE_IMPLEMENTATION` before including this file to get the - * function definitions. - * - * Reference: - * `cgltf_result cgltf_write_file(const cgltf_options* options, const char* - * path, const cgltf_data* data)` writes JSON to the given file path. Buffer - * files and external images are not written out. `data` is not deallocated. - * - * `cgltf_size cgltf_write(const cgltf_options* options, char* buffer, - * cgltf_size size, const cgltf_data* data)` writes JSON into the given memory - * buffer. Returns the number of bytes written to `buffer`, including a null - * terminator. If buffer is null, returns the number of bytes that would have - * been written. `data` is not deallocated. - * - * To write custom JSON into the `extras` field, aggregate all the custom JSON - * into a single buffer, then set `file_data` to this buffer. By supplying - * start_offset and end_offset values for various objects, you can select a - * range of characters within the aggregated buffer. - */ -#ifndef CGLTF_WRITE_H_INCLUDED__ -#define CGLTF_WRITE_H_INCLUDED__ - -#include "cgltf.h" - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -cgltf_result cgltf_write_file(const cgltf_options* options, const char* path, const cgltf_data* data); -cgltf_size cgltf_write(const cgltf_options* options, char* buffer, cgltf_size size, const cgltf_data* data); - -#ifdef __cplusplus -} -#endif - -#endif /* #ifndef CGLTF_WRITE_H_INCLUDED__ */ - -/* - * - * Stop now, if you are only interested in the API. - * Below, you find the implementation. - * - */ - -#if defined(__INTELLISENSE__) || defined(__JETBRAINS_IDE__) -/* This makes MSVC/CLion intellisense work. */ -#define CGLTF_IMPLEMENTATION -#endif - -#ifdef CGLTF_WRITE_IMPLEMENTATION - -#include -#include -#include -#include - -#define CGLTF_EXTENSION_FLAG_TEXTURE_TRANSFORM (1 << 0) -#define CGLTF_EXTENSION_FLAG_MATERIALS_UNLIT (1 << 1) -#define CGLTF_EXTENSION_FLAG_SPECULAR_GLOSSINESS (1 << 2) -#define CGLTF_EXTENSION_FLAG_LIGHTS_PUNCTUAL (1 << 3) -#define CGLTF_EXTENSION_FLAG_DRACO_MESH_COMPRESSION (1 << 4) -#define CGLTF_EXTENSION_FLAG_MATERIALS_CLEARCOAT (1 << 5) -#define CGLTF_EXTENSION_FLAG_MATERIALS_IOR (1 << 6) -#define CGLTF_EXTENSION_FLAG_MATERIALS_SPECULAR (1 << 7) -#define CGLTF_EXTENSION_FLAG_MATERIALS_TRANSMISSION (1 << 8) - -typedef struct { - char* buffer; - cgltf_size buffer_size; - cgltf_size remaining; - char* cursor; - cgltf_size tmp; - cgltf_size chars_written; - const cgltf_data* data; - int depth; - const char* indent; - int needs_comma; - uint32_t extension_flags; - uint32_t required_extension_flags; -} cgltf_write_context; - -#define CGLTF_MIN(a, b) (a < b ? a : b) - -#define CGLTF_SPRINTF(...) { \ - context->tmp = snprintf ( context->cursor, context->remaining, __VA_ARGS__ ); \ - context->chars_written += context->tmp; \ - if (context->cursor) { \ - context->cursor += context->tmp; \ - context->remaining -= context->tmp; \ - } } - -#define CGLTF_SNPRINTF(length, ...) { \ - context->tmp = snprintf ( context->cursor, CGLTF_MIN(length + 1, context->remaining), __VA_ARGS__ ); \ - context->chars_written += length; \ - if (context->cursor) { \ - context->cursor += length; \ - context->remaining -= length; \ - } } - -#define CGLTF_WRITE_IDXPROP(label, val, start) if (val) { \ - cgltf_write_indent(context); \ - CGLTF_SPRINTF("\"%s\": %d", label, (int) (val - start)); \ - context->needs_comma = 1; } - -#define CGLTF_WRITE_IDXARRPROP(label, dim, vals, start) if (vals) { \ - cgltf_write_indent(context); \ - CGLTF_SPRINTF("\"%s\": [", label); \ - for (int i = 0; i < (int)(dim); ++i) { \ - int idx = (int) (vals[i] - start); \ - if (i != 0) CGLTF_SPRINTF(","); \ - CGLTF_SPRINTF(" %d", idx); \ - } \ - CGLTF_SPRINTF(" ]"); \ - context->needs_comma = 1; } - -#define CGLTF_WRITE_TEXTURE_INFO(label, info) if (info.texture) { \ - cgltf_write_line(context, "\"" label "\": {"); \ - CGLTF_WRITE_IDXPROP("index", info.texture, context->data->textures); \ - cgltf_write_intprop(context, "texCoord", info.texcoord, 0); \ - cgltf_write_floatprop(context, "scale", info.scale, 1.0f); \ - if (info.has_transform) { \ - context->extension_flags |= CGLTF_EXTENSION_FLAG_TEXTURE_TRANSFORM; \ - cgltf_write_texture_transform(context, &info.transform); \ - } \ - cgltf_write_extras(context, &info.extras); \ - cgltf_write_line(context, "}"); } - -static void cgltf_write_indent(cgltf_write_context* context) -{ - if (context->needs_comma) - { - CGLTF_SPRINTF(",\n"); - context->needs_comma = 0; - } - else - { - CGLTF_SPRINTF("\n"); - } - for (int i = 0; i < context->depth; ++i) - { - CGLTF_SPRINTF("%s", context->indent); - } -} - -static void cgltf_write_line(cgltf_write_context* context, const char* line) -{ - if (line[0] == ']' || line[0] == '}') - { - --context->depth; - context->needs_comma = 0; - } - cgltf_write_indent(context); - CGLTF_SPRINTF("%s", line); - cgltf_size last = (cgltf_size)(strlen(line) - 1); - if (line[0] == ']' || line[0] == '}') - { - context->needs_comma = 1; - } - if (line[last] == '[' || line[last] == '{') - { - ++context->depth; - context->needs_comma = 0; - } -} - -static void cgltf_write_strprop(cgltf_write_context* context, const char* label, const char* val) -{ - if (val) - { - cgltf_write_indent(context); - CGLTF_SPRINTF("\"%s\": \"%s\"", label, val); - context->needs_comma = 1; - } -} - -static void cgltf_write_extras(cgltf_write_context* context, const cgltf_extras* extras) -{ - cgltf_size length = extras->end_offset - extras->start_offset; - if (length > 0 && context->data->file_data) - { - char* json_string = ((char*) context->data->file_data) + extras->start_offset; - cgltf_write_indent(context); - CGLTF_SPRINTF("%s", "\"extras\": "); - CGLTF_SNPRINTF(length, "%s", json_string); - context->needs_comma = 1; - } -} - -static void cgltf_write_stritem(cgltf_write_context* context, const char* item) -{ - cgltf_write_indent(context); - CGLTF_SPRINTF("\"%s\"", item); - context->needs_comma = 1; -} - -static void cgltf_write_intprop(cgltf_write_context* context, const char* label, int val, int def) -{ - if (val != def) - { - cgltf_write_indent(context); - CGLTF_SPRINTF("\"%s\": %d", label, val); - context->needs_comma = 1; - } -} - -static void cgltf_write_floatprop(cgltf_write_context* context, const char* label, float val, float def) -{ - if (val != def) - { - cgltf_write_indent(context); - CGLTF_SPRINTF("\"%s\": ", label); - CGLTF_SPRINTF("%g", val); - context->needs_comma = 1; - - if (context->cursor) - { - char *decimal_comma = strchr(context->cursor - context->tmp, ','); - if (decimal_comma) - { - *decimal_comma = '.'; - } - } - } -} - -static void cgltf_write_boolprop_optional(cgltf_write_context* context, const char* label, bool val, bool def) -{ - if (val != def) - { - cgltf_write_indent(context); - CGLTF_SPRINTF("\"%s\": %s", label, val ? "true" : "false"); - context->needs_comma = 1; - } -} - -static void cgltf_write_floatarrayprop(cgltf_write_context* context, const char* label, const cgltf_float* vals, cgltf_size dim) -{ - cgltf_write_indent(context); - CGLTF_SPRINTF("\"%s\": [", label); - for (cgltf_size i = 0; i < dim; ++i) - { - if (i != 0) - { - CGLTF_SPRINTF(", %g", vals[i]); - } - else - { - CGLTF_SPRINTF("%g", vals[i]); - } - } - CGLTF_SPRINTF("]"); - context->needs_comma = 1; -} - -static bool cgltf_check_floatarray(const float* vals, int dim, float val) { - while (dim--) - { - if (vals[dim] != val) - { - return true; - } - } - return false; -} - -static int cgltf_int_from_component_type(cgltf_component_type ctype) -{ - switch (ctype) - { - case cgltf_component_type_r_8: return 5120; - case cgltf_component_type_r_8u: return 5121; - case cgltf_component_type_r_16: return 5122; - case cgltf_component_type_r_16u: return 5123; - case cgltf_component_type_r_32u: return 5125; - case cgltf_component_type_r_32f: return 5126; - default: return 0; - } -} - -static const char* cgltf_str_from_alpha_mode(cgltf_alpha_mode alpha_mode) -{ - switch (alpha_mode) - { - case cgltf_alpha_mode_mask: return "MASK"; - case cgltf_alpha_mode_blend: return "BLEND"; - default: return NULL; - } -} - -static const char* cgltf_str_from_type(cgltf_type type) -{ - switch (type) - { - case cgltf_type_scalar: return "SCALAR"; - case cgltf_type_vec2: return "VEC2"; - case cgltf_type_vec3: return "VEC3"; - case cgltf_type_vec4: return "VEC4"; - case cgltf_type_mat2: return "MAT2"; - case cgltf_type_mat3: return "MAT3"; - case cgltf_type_mat4: return "MAT4"; - default: return NULL; - } -} - -static cgltf_size cgltf_dim_from_type(cgltf_type type) -{ - switch (type) - { - case cgltf_type_scalar: return 1; - case cgltf_type_vec2: return 2; - case cgltf_type_vec3: return 3; - case cgltf_type_vec4: return 4; - case cgltf_type_mat2: return 4; - case cgltf_type_mat3: return 9; - case cgltf_type_mat4: return 16; - default: return 0; - } -} - -static const char* cgltf_str_from_camera_type(cgltf_camera_type camera_type) -{ - switch (camera_type) - { - case cgltf_camera_type_perspective: return "perspective"; - case cgltf_camera_type_orthographic: return "orthographic"; - default: return NULL; - } -} - -static const char* cgltf_str_from_light_type(cgltf_light_type light_type) -{ - switch (light_type) - { - case cgltf_light_type_directional: return "directional"; - case cgltf_light_type_point: return "point"; - case cgltf_light_type_spot: return "spot"; - default: return NULL; - } -} - -static void cgltf_write_texture_transform(cgltf_write_context* context, const cgltf_texture_transform* transform) -{ - cgltf_write_line(context, "\"extensions\": {"); - cgltf_write_line(context, "\"KHR_texture_transform\": {"); - if (cgltf_check_floatarray(transform->offset, 2, 0.0f)) - { - cgltf_write_floatarrayprop(context, "offset", transform->offset, 2); - } - cgltf_write_floatprop(context, "rotation", transform->rotation, 0.0f); - if (cgltf_check_floatarray(transform->scale, 2, 1.0f)) - { - cgltf_write_floatarrayprop(context, "scale", transform->scale, 2); - } - cgltf_write_intprop(context, "texCoord", transform->texcoord, 0); - cgltf_write_line(context, "}"); - cgltf_write_line(context, "}"); -} - -static void cgltf_write_asset(cgltf_write_context* context, const cgltf_asset* asset) -{ - cgltf_write_line(context, "\"asset\": {"); - cgltf_write_strprop(context, "copyright", asset->copyright); - cgltf_write_strprop(context, "generator", asset->generator); - cgltf_write_strprop(context, "version", asset->version); - cgltf_write_strprop(context, "min_version", asset->min_version); - cgltf_write_extras(context, &asset->extras); - cgltf_write_line(context, "}"); -} - -static void cgltf_write_primitive(cgltf_write_context* context, const cgltf_primitive* prim) -{ - cgltf_write_intprop(context, "mode", (int) prim->type, 4); - CGLTF_WRITE_IDXPROP("indices", prim->indices, context->data->accessors); - CGLTF_WRITE_IDXPROP("material", prim->material, context->data->materials); - cgltf_write_line(context, "\"attributes\": {"); - for (cgltf_size i = 0; i < prim->attributes_count; ++i) - { - const cgltf_attribute* attr = prim->attributes + i; - CGLTF_WRITE_IDXPROP(attr->name, attr->data, context->data->accessors); - } - cgltf_write_line(context, "}"); - - if (prim->targets_count) - { - cgltf_write_line(context, "\"targets\": ["); - for (cgltf_size i = 0; i < prim->targets_count; ++i) - { - cgltf_write_line(context, "{"); - for (cgltf_size j = 0; j < prim->targets[i].attributes_count; ++j) - { - const cgltf_attribute* attr = prim->targets[i].attributes + j; - CGLTF_WRITE_IDXPROP(attr->name, attr->data, context->data->accessors); - } - cgltf_write_line(context, "}"); - } - cgltf_write_line(context, "]"); - } - cgltf_write_extras(context, &prim->extras); - - cgltf_bool has_extensions = prim->has_draco_mesh_compression; - if (has_extensions) { - cgltf_write_line(context, "\"extensions\": {"); - - if (prim->has_draco_mesh_compression) { - context->extension_flags |= CGLTF_EXTENSION_FLAG_DRACO_MESH_COMPRESSION; - if (prim->attributes_count == 0 || prim->indices == 0) { - context->required_extension_flags |= CGLTF_EXTENSION_FLAG_DRACO_MESH_COMPRESSION; - } - - cgltf_write_line(context, "\"KHR_draco_mesh_compression\": {"); - CGLTF_WRITE_IDXPROP("bufferView", prim->draco_mesh_compression.buffer_view, context->data->buffer_views); - cgltf_write_line(context, "\"attributes\": {"); - for (cgltf_size i = 0; i < prim->draco_mesh_compression.attributes_count; ++i) - { - const cgltf_attribute* attr = prim->draco_mesh_compression.attributes + i; - CGLTF_WRITE_IDXPROP(attr->name, attr->data, context->data->accessors); - } - cgltf_write_line(context, "}"); - cgltf_write_line(context, "}"); - } - - cgltf_write_line(context, "}"); - } -} - -static void cgltf_write_mesh(cgltf_write_context* context, const cgltf_mesh* mesh) -{ - cgltf_write_line(context, "{"); - cgltf_write_strprop(context, "name", mesh->name); - - cgltf_write_line(context, "\"primitives\": ["); - for (cgltf_size i = 0; i < mesh->primitives_count; ++i) - { - cgltf_write_line(context, "{"); - cgltf_write_primitive(context, mesh->primitives + i); - cgltf_write_line(context, "}"); - } - cgltf_write_line(context, "]"); - - if (mesh->weights_count > 0) - { - cgltf_write_floatarrayprop(context, "weights", mesh->weights, mesh->weights_count); - } - cgltf_write_extras(context, &mesh->extras); - cgltf_write_line(context, "}"); -} - -static void cgltf_write_buffer_view(cgltf_write_context* context, const cgltf_buffer_view* view) -{ - cgltf_write_line(context, "{"); - CGLTF_WRITE_IDXPROP("buffer", view->buffer, context->data->buffers); - cgltf_write_intprop(context, "byteLength", (int)view->size, -1); - cgltf_write_intprop(context, "byteOffset", (int)view->offset, 0); - cgltf_write_intprop(context, "byteStride", (int)view->stride, 0); - // NOTE: We skip writing "target" because the spec says its usage can be inferred. - cgltf_write_extras(context, &view->extras); - cgltf_write_line(context, "}"); -} - - -static void cgltf_write_buffer(cgltf_write_context* context, const cgltf_buffer* buffer) -{ - cgltf_write_line(context, "{"); - cgltf_write_strprop(context, "uri", buffer->uri); - cgltf_write_intprop(context, "byteLength", (int)buffer->size, -1); - cgltf_write_extras(context, &buffer->extras); - cgltf_write_line(context, "}"); -} - -static void cgltf_write_material(cgltf_write_context* context, const cgltf_material* material) -{ - cgltf_write_line(context, "{"); - cgltf_write_strprop(context, "name", material->name); - cgltf_write_floatprop(context, "alphaCutoff", material->alpha_cutoff, 0.5f); - cgltf_write_boolprop_optional(context, "doubleSided", material->double_sided, false); - // cgltf_write_boolprop_optional(context, "unlit", material->unlit, false); - - if (material->unlit) - { - context->extension_flags |= CGLTF_EXTENSION_FLAG_MATERIALS_UNLIT; - } - - if (material->has_pbr_specular_glossiness) - { - context->extension_flags |= CGLTF_EXTENSION_FLAG_SPECULAR_GLOSSINESS; - } - - if (material->has_clearcoat) - { - context->extension_flags |= CGLTF_EXTENSION_FLAG_MATERIALS_CLEARCOAT; - } - - if (material->has_transmission) - { - context->extension_flags |= CGLTF_EXTENSION_FLAG_MATERIALS_TRANSMISSION; - } - - if (material->has_ior) - { - context->extension_flags |= CGLTF_EXTENSION_FLAG_MATERIALS_IOR; - } - - if (material->has_specular) - { - context->extension_flags |= CGLTF_EXTENSION_FLAG_MATERIALS_SPECULAR; - } - - if (material->has_pbr_metallic_roughness) - { - const cgltf_pbr_metallic_roughness* params = &material->pbr_metallic_roughness; - cgltf_write_line(context, "\"pbrMetallicRoughness\": {"); - CGLTF_WRITE_TEXTURE_INFO("baseColorTexture", params->base_color_texture); - CGLTF_WRITE_TEXTURE_INFO("metallicRoughnessTexture", params->metallic_roughness_texture); - cgltf_write_floatprop(context, "metallicFactor", params->metallic_factor, 1.0f); - cgltf_write_floatprop(context, "roughnessFactor", params->roughness_factor, 1.0f); - if (cgltf_check_floatarray(params->base_color_factor, 4, 1.0f)) - { - cgltf_write_floatarrayprop(context, "baseColorFactor", params->base_color_factor, 4); - } - cgltf_write_extras(context, ¶ms->extras); - cgltf_write_line(context, "}"); - } - - if (material->unlit || material->has_pbr_specular_glossiness || material->has_clearcoat || material->has_ior || material->has_specular || material->has_transmission) - { - cgltf_write_line(context, "\"extensions\": {"); - if (material->has_clearcoat) - { - const cgltf_clearcoat* params = &material->clearcoat; - cgltf_write_line(context, "\"KHR_materials_clearcoat\": {"); - CGLTF_WRITE_TEXTURE_INFO("clearcoatTexture", params->clearcoat_texture); - CGLTF_WRITE_TEXTURE_INFO("clearcoatRoughnessTexture", params->clearcoat_roughness_texture); - CGLTF_WRITE_TEXTURE_INFO("clearcoatNormalTexture", params->clearcoat_normal_texture); - cgltf_write_floatprop(context, "clearcoatFactor", params->clearcoat_factor, 0.0f); - cgltf_write_floatprop(context, "clearcoatRoughnessFactor", params->clearcoat_roughness_factor, 0.0f); - cgltf_write_line(context, "}"); - } - if (material->has_ior) - { - const cgltf_ior* params = &material->ior; - cgltf_write_line(context, "\"KHR_materials_ior\": {"); - cgltf_write_floatprop(context, "ior", params->ior, 1.5f); - cgltf_write_line(context, "}"); - } - if (material->has_specular) - { - const cgltf_specular* params = &material->specular; - cgltf_write_line(context, "\"KHR_materials_specular\": {"); - CGLTF_WRITE_TEXTURE_INFO("specularTexture", params->specular_texture); - cgltf_write_floatprop(context, "specularFactor", params->specular_factor, 1.0f); - if (cgltf_check_floatarray(params->specular_color_factor, 3, 1.0f)) - { - cgltf_write_floatarrayprop(context, "specularColorFactor", params->specular_color_factor, 3); - } - cgltf_write_line(context, "}"); - } - if (material->has_transmission) - { - const cgltf_transmission* params = &material->transmission; - cgltf_write_line(context, "\"KHR_materials_transmission\": {"); - CGLTF_WRITE_TEXTURE_INFO("transmissionTexture", params->transmission_texture); - cgltf_write_floatprop(context, "transmissionFactor", params->transmission_factor, 0.0f); - cgltf_write_line(context, "}"); - } - if (material->has_pbr_specular_glossiness) - { - const cgltf_pbr_specular_glossiness* params = &material->pbr_specular_glossiness; - cgltf_write_line(context, "\"KHR_materials_pbrSpecularGlossiness\": {"); - CGLTF_WRITE_TEXTURE_INFO("diffuseTexture", params->diffuse_texture); - CGLTF_WRITE_TEXTURE_INFO("specularGlossinessTexture", params->specular_glossiness_texture); - if (cgltf_check_floatarray(params->diffuse_factor, 4, 1.0f)) - { - cgltf_write_floatarrayprop(context, "dffuseFactor", params->diffuse_factor, 4); - } - if (cgltf_check_floatarray(params->specular_factor, 3, 1.0f)) - { - cgltf_write_floatarrayprop(context, "specularFactor", params->specular_factor, 3); - } - cgltf_write_floatprop(context, "glossinessFactor", params->glossiness_factor, 1.0f); - cgltf_write_line(context, "}"); - } - if (material->unlit) - { - cgltf_write_line(context, "\"KHR_materials_unlit\": {}"); - } - cgltf_write_line(context, "}"); - } - - CGLTF_WRITE_TEXTURE_INFO("normalTexture", material->normal_texture); - CGLTF_WRITE_TEXTURE_INFO("occlusionTexture", material->occlusion_texture); - CGLTF_WRITE_TEXTURE_INFO("emissiveTexture", material->emissive_texture); - if (cgltf_check_floatarray(material->emissive_factor, 3, 0.0f)) - { - cgltf_write_floatarrayprop(context, "emissiveFactor", material->emissive_factor, 3); - } - cgltf_write_strprop(context, "alphaMode", cgltf_str_from_alpha_mode(material->alpha_mode)); - cgltf_write_extras(context, &material->extras); - cgltf_write_line(context, "}"); -} - -static void cgltf_write_image(cgltf_write_context* context, const cgltf_image* image) -{ - cgltf_write_line(context, "{"); - cgltf_write_strprop(context, "name", image->name); - cgltf_write_strprop(context, "uri", image->uri); - CGLTF_WRITE_IDXPROP("bufferView", image->buffer_view, context->data->buffer_views); - cgltf_write_strprop(context, "mimeType", image->mime_type); - cgltf_write_extras(context, &image->extras); - cgltf_write_line(context, "}"); -} - -static void cgltf_write_texture(cgltf_write_context* context, const cgltf_texture* texture) -{ - cgltf_write_line(context, "{"); - cgltf_write_strprop(context, "name", texture->name); - CGLTF_WRITE_IDXPROP("source", texture->image, context->data->images); - CGLTF_WRITE_IDXPROP("sampler", texture->sampler, context->data->samplers); - cgltf_write_extras(context, &texture->extras); - cgltf_write_line(context, "}"); -} - -static void cgltf_write_skin(cgltf_write_context* context, const cgltf_skin* skin) -{ - cgltf_write_line(context, "{"); - CGLTF_WRITE_IDXPROP("skeleton", skin->skeleton, context->data->nodes); - CGLTF_WRITE_IDXPROP("inverseBindMatrices", skin->inverse_bind_matrices, context->data->accessors); - CGLTF_WRITE_IDXARRPROP("joints", skin->joints_count, skin->joints, context->data->nodes); - cgltf_write_strprop(context, "name", skin->name); - cgltf_write_extras(context, &skin->extras); - cgltf_write_line(context, "}"); -} - -static const char* cgltf_write_str_path_type(cgltf_animation_path_type path_type) -{ - switch (path_type) - { - case cgltf_animation_path_type_translation: - return "translation"; - case cgltf_animation_path_type_rotation: - return "rotation"; - case cgltf_animation_path_type_scale: - return "scale"; - case cgltf_animation_path_type_weights: - return "weights"; - case cgltf_animation_path_type_invalid: - break; - } - return "invalid"; -} - -static const char* cgltf_write_str_interpolation_type(cgltf_interpolation_type interpolation_type) -{ - switch (interpolation_type) - { - case cgltf_interpolation_type_linear: - return "LINEAR"; - case cgltf_interpolation_type_step: - return "STEP"; - case cgltf_interpolation_type_cubic_spline: - return "CUBICSPLINE"; - } - return "invalid"; -} - -static void cgltf_write_path_type(cgltf_write_context* context, const char *label, cgltf_animation_path_type path_type) -{ - cgltf_write_strprop(context, label, cgltf_write_str_path_type(path_type)); -} - -static void cgltf_write_interpolation_type(cgltf_write_context* context, const char *label, cgltf_interpolation_type interpolation_type) -{ - cgltf_write_strprop(context, label, cgltf_write_str_interpolation_type(interpolation_type)); -} - -static void cgltf_write_animation_sampler(cgltf_write_context* context, const cgltf_animation_sampler* animation_sampler) -{ - cgltf_write_line(context, "{"); - cgltf_write_interpolation_type(context, "interpolation", animation_sampler->interpolation); - CGLTF_WRITE_IDXPROP("input", animation_sampler->input, context->data->accessors); - CGLTF_WRITE_IDXPROP("output", animation_sampler->output, context->data->accessors); - cgltf_write_extras(context, &animation_sampler->extras); - cgltf_write_line(context, "}"); -} - -static void cgltf_write_animation_channel(cgltf_write_context* context, const cgltf_animation* animation, const cgltf_animation_channel* animation_channel) -{ - cgltf_write_line(context, "{"); - CGLTF_WRITE_IDXPROP("sampler", animation_channel->sampler, animation->samplers); - cgltf_write_line(context, "\"target\": {"); - CGLTF_WRITE_IDXPROP("node", animation_channel->target_node, context->data->nodes); - cgltf_write_path_type(context, "path", animation_channel->target_path); - cgltf_write_line(context, "}"); - cgltf_write_extras(context, &animation_channel->extras); - cgltf_write_line(context, "}"); -} - -static void cgltf_write_animation(cgltf_write_context* context, const cgltf_animation* animation) -{ - cgltf_write_line(context, "{"); - cgltf_write_strprop(context, "name", animation->name); - - if (animation->samplers_count > 0) - { - cgltf_write_line(context, "\"samplers\": ["); - for (cgltf_size i = 0; i < animation->samplers_count; ++i) - { - cgltf_write_animation_sampler(context, animation->samplers + i); - } - cgltf_write_line(context, "]"); - } - if (animation->channels_count > 0) - { - cgltf_write_line(context, "\"channels\": ["); - for (cgltf_size i = 0; i < animation->channels_count; ++i) - { - cgltf_write_animation_channel(context, animation, animation->channels + i); - } - cgltf_write_line(context, "]"); - } - cgltf_write_extras(context, &animation->extras); - cgltf_write_line(context, "}"); -} - -static void cgltf_write_sampler(cgltf_write_context* context, const cgltf_sampler* sampler) -{ - cgltf_write_line(context, "{"); - cgltf_write_intprop(context, "magFilter", sampler->mag_filter, 0); - cgltf_write_intprop(context, "minFilter", sampler->min_filter, 0); - cgltf_write_intprop(context, "wrapS", sampler->wrap_s, 10497); - cgltf_write_intprop(context, "wrapT", sampler->wrap_t, 10497); - cgltf_write_extras(context, &sampler->extras); - cgltf_write_line(context, "}"); -} - -static void cgltf_write_node(cgltf_write_context* context, const cgltf_node* node) -{ - cgltf_write_line(context, "{"); - CGLTF_WRITE_IDXARRPROP("children", node->children_count, node->children, context->data->nodes); - CGLTF_WRITE_IDXPROP("mesh", node->mesh, context->data->meshes); - cgltf_write_strprop(context, "name", node->name); - if (node->has_matrix) - { - cgltf_write_floatarrayprop(context, "matrix", node->matrix, 16); - } - if (node->has_translation) - { - cgltf_write_floatarrayprop(context, "translation", node->translation, 3); - } - if (node->has_rotation) - { - cgltf_write_floatarrayprop(context, "rotation", node->rotation, 4); - } - if (node->has_scale) - { - cgltf_write_floatarrayprop(context, "scale", node->scale, 3); - } - if (node->skin) - { - CGLTF_WRITE_IDXPROP("skin", node->skin, context->data->skins); - } - - if (node->light) - { - context->extension_flags |= CGLTF_EXTENSION_FLAG_LIGHTS_PUNCTUAL; - cgltf_write_line(context, "\"extensions\": {"); - cgltf_write_line(context, "\"KHR_lights_punctual\": {"); - CGLTF_WRITE_IDXPROP("light", node->light, context->data->lights); - cgltf_write_line(context, "}"); - cgltf_write_line(context, "}"); - } - - if (node->weights_count > 0) - { - cgltf_write_floatarrayprop(context, "weights", node->weights, node->weights_count); - } - - if (node->camera) - { - CGLTF_WRITE_IDXPROP("camera", node->camera, context->data->cameras); - } - - cgltf_write_extras(context, &node->extras); - cgltf_write_line(context, "}"); -} - -static void cgltf_write_scene(cgltf_write_context* context, const cgltf_scene* scene) -{ - cgltf_write_line(context, "{"); - cgltf_write_strprop(context, "name", scene->name); - CGLTF_WRITE_IDXARRPROP("nodes", scene->nodes_count, scene->nodes, context->data->nodes); - cgltf_write_extras(context, &scene->extras); - cgltf_write_line(context, "}"); -} - -static void cgltf_write_accessor(cgltf_write_context* context, const cgltf_accessor* accessor) -{ - cgltf_write_line(context, "{"); - CGLTF_WRITE_IDXPROP("bufferView", accessor->buffer_view, context->data->buffer_views); - cgltf_write_intprop(context, "componentType", cgltf_int_from_component_type(accessor->component_type), 0); - cgltf_write_strprop(context, "type", cgltf_str_from_type(accessor->type)); - cgltf_size dim = cgltf_dim_from_type(accessor->type); - cgltf_write_boolprop_optional(context, "normalized", accessor->normalized, false); - cgltf_write_intprop(context, "byteOffset", (int)accessor->offset, 0); - cgltf_write_intprop(context, "count", (int)accessor->count, -1); - if (accessor->has_min) - { - cgltf_write_floatarrayprop(context, "min", accessor->min, dim); - } - if (accessor->has_max) - { - cgltf_write_floatarrayprop(context, "max", accessor->max, dim); - } - if (accessor->is_sparse) - { - cgltf_write_line(context, "\"sparse\": {"); - cgltf_write_intprop(context, "count", (int)accessor->sparse.count, 0); - cgltf_write_line(context, "\"indices\": {"); - cgltf_write_intprop(context, "byteOffset", (int)accessor->sparse.indices_byte_offset, 0); - CGLTF_WRITE_IDXPROP("bufferView", accessor->sparse.indices_buffer_view, context->data->buffer_views); - cgltf_write_intprop(context, "componentType", cgltf_int_from_component_type(accessor->sparse.indices_component_type), 0); - cgltf_write_extras(context, &accessor->sparse.indices_extras); - cgltf_write_line(context, "}"); - cgltf_write_line(context, "\"values\": {"); - cgltf_write_intprop(context, "byteOffset", (int)accessor->sparse.values_byte_offset, 0); - CGLTF_WRITE_IDXPROP("bufferView", accessor->sparse.values_buffer_view, context->data->buffer_views); - cgltf_write_extras(context, &accessor->sparse.values_extras); - cgltf_write_line(context, "}"); - cgltf_write_extras(context, &accessor->sparse.extras); - cgltf_write_line(context, "}"); - } - cgltf_write_extras(context, &accessor->extras); - cgltf_write_line(context, "}"); -} - -static void cgltf_write_camera(cgltf_write_context* context, const cgltf_camera* camera) -{ - cgltf_write_line(context, "{"); - cgltf_write_strprop(context, "type", cgltf_str_from_camera_type(camera->type)); - if (camera->name) - { - cgltf_write_strprop(context, "name", camera->name); - } - - if (camera->type == cgltf_camera_type_orthographic) - { - cgltf_write_line(context, "\"orthographic\": {"); - cgltf_write_floatprop(context, "xmag", camera->data.orthographic.xmag, -1.0f); - cgltf_write_floatprop(context, "ymag", camera->data.orthographic.ymag, -1.0f); - cgltf_write_floatprop(context, "zfar", camera->data.orthographic.zfar, -1.0f); - cgltf_write_floatprop(context, "znear", camera->data.orthographic.znear, -1.0f); - cgltf_write_extras(context, &camera->data.orthographic.extras); - cgltf_write_line(context, "}"); - } - else if (camera->type == cgltf_camera_type_perspective) - { - cgltf_write_line(context, "\"perspective\": {"); - cgltf_write_floatprop(context, "aspectRatio", camera->data.perspective.aspect_ratio, -1.0f); - cgltf_write_floatprop(context, "yfov", camera->data.perspective.yfov, -1.0f); - cgltf_write_floatprop(context, "zfar", camera->data.perspective.zfar, -1.0f); - cgltf_write_floatprop(context, "znear", camera->data.perspective.znear, -1.0f); - cgltf_write_extras(context, &camera->data.perspective.extras); - cgltf_write_line(context, "}"); - } - cgltf_write_extras(context, &camera->extras); - cgltf_write_line(context, "}"); -} - -static void cgltf_write_light(cgltf_write_context* context, const cgltf_light* light) -{ - cgltf_write_line(context, "{"); - cgltf_write_strprop(context, "type", cgltf_str_from_light_type(light->type)); - if (light->name) - { - cgltf_write_strprop(context, "name", light->name); - } - if (cgltf_check_floatarray(light->color, 3, 1.0f)) - { - cgltf_write_floatarrayprop(context, "color", light->color, 3); - } - cgltf_write_floatprop(context, "intensity", light->intensity, 1.0f); - cgltf_write_floatprop(context, "range", light->range, 0.0f); - - if (light->type == cgltf_light_type_spot) - { - cgltf_write_line(context, "\"spot\": {"); - cgltf_write_floatprop(context, "innerConeAngle", light->spot_inner_cone_angle, 0.0f); - cgltf_write_floatprop(context, "outerConeAngle", light->spot_outer_cone_angle, 3.14159265358979323846f/4.0f); - cgltf_write_line(context, "}"); - } - cgltf_write_line(context, "}"); -} - -cgltf_result cgltf_write_file(const cgltf_options* options, const char* path, const cgltf_data* data) -{ - cgltf_size expected = cgltf_write(options, NULL, 0, data); - char* buffer = (char*) malloc(expected); - cgltf_size actual = cgltf_write(options, buffer, expected, data); - if (expected != actual) { - fprintf(stderr, "Error: expected %zu bytes but wrote %zu bytes.\n", expected, actual); - } - FILE* file = fopen(path, "wt"); - if (!file) - { - return cgltf_result_file_not_found; - } - // Note that cgltf_write() includes a null terminator, which we omit from the file content. - fwrite(buffer, actual - 1, 1, file); - fclose(file); - free(buffer); - return cgltf_result_success; -} - -static void cgltf_write_extensions(cgltf_write_context* context, uint32_t extension_flags) -{ - if (extension_flags & CGLTF_EXTENSION_FLAG_TEXTURE_TRANSFORM) { - cgltf_write_stritem(context, "KHR_texture_transform"); - } - if (extension_flags & CGLTF_EXTENSION_FLAG_MATERIALS_UNLIT) { - cgltf_write_stritem(context, "KHR_materials_unlit"); - } - if (extension_flags & CGLTF_EXTENSION_FLAG_SPECULAR_GLOSSINESS) { - cgltf_write_stritem(context, "KHR_materials_pbrSpecularGlossiness"); - } - if (extension_flags & CGLTF_EXTENSION_FLAG_LIGHTS_PUNCTUAL) { - cgltf_write_stritem(context, "KHR_lights_punctual"); - } - if (extension_flags & CGLTF_EXTENSION_FLAG_DRACO_MESH_COMPRESSION) { - cgltf_write_stritem(context, "KHR_draco_mesh_compression"); - } - if (extension_flags & CGLTF_EXTENSION_FLAG_MATERIALS_CLEARCOAT) { - cgltf_write_stritem(context, "KHR_materials_clearcoat"); - } - if (extension_flags & CGLTF_EXTENSION_FLAG_MATERIALS_IOR) { - cgltf_write_stritem(context, "KHR_materials_ior"); - } - if (extension_flags & CGLTF_EXTENSION_FLAG_MATERIALS_SPECULAR) { - cgltf_write_stritem(context, "KHR_materials_specular"); - } - if (extension_flags & CGLTF_EXTENSION_FLAG_MATERIALS_TRANSMISSION) { - cgltf_write_stritem(context, "KHR_materials_transmission"); - } -} - -cgltf_size cgltf_write(const cgltf_options* options, char* buffer, cgltf_size size, const cgltf_data* data) -{ - (void)options; - cgltf_write_context ctx; - ctx.buffer = buffer; - ctx.buffer_size = size; - ctx.remaining = size; - ctx.cursor = buffer; - ctx.chars_written = 0; - ctx.data = data; - ctx.depth = 1; - ctx.indent = " "; - ctx.needs_comma = 0; - ctx.extension_flags = 0; - ctx.required_extension_flags = 0; - - cgltf_write_context* context = &ctx; - - CGLTF_SPRINTF("{"); - - if (data->accessors_count > 0) - { - cgltf_write_line(context, "\"accessors\": ["); - for (cgltf_size i = 0; i < data->accessors_count; ++i) - { - cgltf_write_accessor(context, data->accessors + i); - } - cgltf_write_line(context, "]"); - } - - cgltf_write_asset(context, &data->asset); - - if (data->buffer_views_count > 0) - { - cgltf_write_line(context, "\"bufferViews\": ["); - for (cgltf_size i = 0; i < data->buffer_views_count; ++i) - { - cgltf_write_buffer_view(context, data->buffer_views + i); - } - cgltf_write_line(context, "]"); - } - - if (data->buffers_count > 0) - { - cgltf_write_line(context, "\"buffers\": ["); - for (cgltf_size i = 0; i < data->buffers_count; ++i) - { - cgltf_write_buffer(context, data->buffers + i); - } - cgltf_write_line(context, "]"); - } - - if (data->images_count > 0) - { - cgltf_write_line(context, "\"images\": ["); - for (cgltf_size i = 0; i < data->images_count; ++i) - { - cgltf_write_image(context, data->images + i); - } - cgltf_write_line(context, "]"); - } - - if (data->meshes_count > 0) - { - cgltf_write_line(context, "\"meshes\": ["); - for (cgltf_size i = 0; i < data->meshes_count; ++i) - { - cgltf_write_mesh(context, data->meshes + i); - } - cgltf_write_line(context, "]"); - } - - if (data->materials_count > 0) - { - cgltf_write_line(context, "\"materials\": ["); - for (cgltf_size i = 0; i < data->materials_count; ++i) - { - cgltf_write_material(context, data->materials + i); - } - cgltf_write_line(context, "]"); - } - - if (data->nodes_count > 0) - { - cgltf_write_line(context, "\"nodes\": ["); - for (cgltf_size i = 0; i < data->nodes_count; ++i) - { - cgltf_write_node(context, data->nodes + i); - } - cgltf_write_line(context, "]"); - } - - if (data->samplers_count > 0) - { - cgltf_write_line(context, "\"samplers\": ["); - for (cgltf_size i = 0; i < data->samplers_count; ++i) - { - cgltf_write_sampler(context, data->samplers + i); - } - cgltf_write_line(context, "]"); - } - - CGLTF_WRITE_IDXPROP("scene", data->scene, data->scenes); - - if (data->scenes_count > 0) - { - cgltf_write_line(context, "\"scenes\": ["); - for (cgltf_size i = 0; i < data->scenes_count; ++i) - { - cgltf_write_scene(context, data->scenes + i); - } - cgltf_write_line(context, "]"); - } - - if (data->textures_count > 0) - { - cgltf_write_line(context, "\"textures\": ["); - for (cgltf_size i = 0; i < data->textures_count; ++i) - { - cgltf_write_texture(context, data->textures + i); - } - cgltf_write_line(context, "]"); - } - - if (data->skins_count > 0) - { - cgltf_write_line(context, "\"skins\": ["); - for (cgltf_size i = 0; i < data->skins_count; ++i) - { - cgltf_write_skin(context, data->skins + i); - } - cgltf_write_line(context, "]"); - } - - if (data->animations_count > 0) - { - cgltf_write_line(context, "\"animations\": ["); - for (cgltf_size i = 0; i < data->animations_count; ++i) - { - cgltf_write_animation(context, data->animations + i); - } - cgltf_write_line(context, "]"); - } - - if (data->cameras_count > 0) - { - cgltf_write_line(context, "\"cameras\": ["); - for (cgltf_size i = 0; i < data->cameras_count; ++i) - { - cgltf_write_camera(context, data->cameras + i); - } - cgltf_write_line(context, "]"); - } - - if (data->lights_count > 0) - { - cgltf_write_line(context, "\"extensions\": {"); - - cgltf_write_line(context, "\"KHR_lights_punctual\": {"); - cgltf_write_line(context, "\"lights\": ["); - for (cgltf_size i = 0; i < data->lights_count; ++i) - { - cgltf_write_light(context, data->lights + i); - } - cgltf_write_line(context, "]"); - cgltf_write_line(context, "}"); - - cgltf_write_line(context, "}"); - } - - if (context->extension_flags != 0) { - cgltf_write_line(context, "\"extensionsUsed\": ["); - cgltf_write_extensions(context, context->extension_flags); - cgltf_write_line(context, "]"); - } - - if (context->required_extension_flags != 0) { - cgltf_write_line(context, "\"extensionsRequired\": ["); - cgltf_write_extensions(context, context->required_extension_flags); - cgltf_write_line(context, "]"); - } - - cgltf_write_extras(context, &data->extras); - - CGLTF_SPRINTF("\n}\n"); - - // snprintf does not include the null terminator in its return value, so be sure to include it - // in the returned byte count. - return 1 + ctx.chars_written; -} - -#endif /* #ifdef CGLTF_WRITE_IMPLEMENTATION */ - -/* cgltf is distributed under MIT license: - * - * Copyright (c) 2019 Philip Rideout - - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ diff --git a/gfx/contrib/stb/CMakeLists.txt b/gfx/contrib/stb/CMakeLists.txt deleted file mode 100644 index 8cee003..0000000 --- a/gfx/contrib/stb/CMakeLists.txt +++ /dev/null @@ -1,8 +0,0 @@ -cmake_minimum_required(VERSION 3.16) - -project(stb) - -add_library(stb INTERFACE) - -target_include_directories(stb INTERFACE - ${CMAKE_CURRENT_SOURCE_DIR}) diff --git a/gfx/contrib/stb/stb_image.h b/gfx/contrib/stb/stb_image.h deleted file mode 100644 index 97038e6..0000000 --- a/gfx/contrib/stb/stb_image.h +++ /dev/null @@ -1,7762 +0,0 @@ -/* stb_image - v2.26 - public domain image loader - http://nothings.org/stb - no warranty implied; use at your own risk - - Do this: - #define STB_IMAGE_IMPLEMENTATION - before you include this file in *one* C or C++ file to create the implementation. - - // i.e. it should look like this: - #include ... - #include ... - #include ... - #define STB_IMAGE_IMPLEMENTATION - #include "stb_image.h" - - You can #define STBI_ASSERT(x) before the #include to avoid using assert.h. - And #define STBI_MALLOC, STBI_REALLOC, and STBI_FREE to avoid using malloc,realloc,free - - - QUICK NOTES: - Primarily of interest to game developers and other people who can - avoid problematic images and only need the trivial interface - - JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib) - PNG 1/2/4/8/16-bit-per-channel - - TGA (not sure what subset, if a subset) - BMP non-1bpp, non-RLE - PSD (composited view only, no extra channels, 8/16 bit-per-channel) - - GIF (*comp always reports as 4-channel) - HDR (radiance rgbE format) - PIC (Softimage PIC) - PNM (PPM and PGM binary only) - - Animated GIF still needs a proper API, but here's one way to do it: - http://gist.github.com/urraka/685d9a6340b26b830d49 - - - decode from memory or through FILE (define STBI_NO_STDIO to remove code) - - decode from arbitrary I/O callbacks - - SIMD acceleration on x86/x64 (SSE2) and ARM (NEON) - - Full documentation under "DOCUMENTATION" below. - - -LICENSE - - See end of file for license information. - -RECENT REVISION HISTORY: - - 2.26 (2020-07-13) many minor fixes - 2.25 (2020-02-02) fix warnings - 2.24 (2020-02-02) fix warnings; thread-local failure_reason and flip_vertically - 2.23 (2019-08-11) fix clang static analysis warning - 2.22 (2019-03-04) gif fixes, fix warnings - 2.21 (2019-02-25) fix typo in comment - 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs - 2.19 (2018-02-11) fix warning - 2.18 (2018-01-30) fix warnings - 2.17 (2018-01-29) bugfix, 1-bit BMP, 16-bitness query, fix warnings - 2.16 (2017-07-23) all functions have 16-bit variants; optimizations; bugfixes - 2.15 (2017-03-18) fix png-1,2,4; all Imagenet JPGs; no runtime SSE detection on GCC - 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs - 2.13 (2016-12-04) experimental 16-bit API, only for PNG so far; fixes - 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes - 2.11 (2016-04-02) 16-bit PNGS; enable SSE2 in non-gcc x64 - RGB-format JPEG; remove white matting in PSD; - allocate large structures on the stack; - correct channel count for PNG & BMP - 2.10 (2016-01-22) avoid warning introduced in 2.09 - 2.09 (2016-01-16) 16-bit TGA; comments in PNM files; STBI_REALLOC_SIZED - - See end of file for full revision history. - - - ============================ Contributors ========================= - - Image formats Extensions, features - Sean Barrett (jpeg, png, bmp) Jetro Lauha (stbi_info) - Nicolas Schulz (hdr, psd) Martin "SpartanJ" Golini (stbi_info) - Jonathan Dummer (tga) James "moose2000" Brown (iPhone PNG) - Jean-Marc Lienher (gif) Ben "Disch" Wenger (io callbacks) - Tom Seddon (pic) Omar Cornut (1/2/4-bit PNG) - Thatcher Ulrich (psd) Nicolas Guillemot (vertical flip) - Ken Miller (pgm, ppm) Richard Mitton (16-bit PSD) - github:urraka (animated gif) Junggon Kim (PNM comments) - Christopher Forseth (animated gif) Daniel Gibson (16-bit TGA) - socks-the-fox (16-bit PNG) - Jeremy Sawicki (handle all ImageNet JPGs) - Optimizations & bugfixes Mikhail Morozov (1-bit BMP) - Fabian "ryg" Giesen Anael Seghezzi (is-16-bit query) - Arseny Kapoulkine - John-Mark Allen - Carmelo J Fdez-Aguera - - Bug & warning fixes - Marc LeBlanc David Woo Guillaume George Martins Mozeiko - Christpher Lloyd Jerry Jansson Joseph Thomson Blazej Dariusz Roszkowski - Phil Jordan Dave Moore Roy Eltham - Hayaki Saito Nathan Reed Won Chun - Luke Graham Johan Duparc Nick Verigakis the Horde3D community - Thomas Ruf Ronny Chevalier github:rlyeh - Janez Zemva John Bartholomew Michal Cichon github:romigrou - Jonathan Blow Ken Hamada Tero Hanninen github:svdijk - Laurent Gomila Cort Stratton github:snagar - Aruelien Pocheville Sergio Gonzalez Thibault Reuille github:Zelex - Cass Everitt Ryamond Barbiero github:grim210 - Paul Du Bois Engin Manap Aldo Culquicondor github:sammyhw - Philipp Wiesemann Dale Weiler Oriol Ferrer Mesia github:phprus - Josh Tobin Matthew Gregan github:poppolopoppo - Julian Raschke Gregory Mullen Christian Floisand github:darealshinji - Baldur Karlsson Kevin Schmidt JR Smith github:Michaelangel007 - Brad Weinberger Matvey Cherevko [reserved] - Luca Sas Alexander Veselov Zack Middleton [reserved] - Ryan C. Gordon [reserved] [reserved] - DO NOT ADD YOUR NAME HERE - - To add your name to the credits, pick a random blank space in the middle and fill it. - 80% of merge conflicts on stb PRs are due to people adding their name at the end - of the credits. -*/ - -#ifndef STBI_INCLUDE_STB_IMAGE_H -#define STBI_INCLUDE_STB_IMAGE_H - -// DOCUMENTATION -// -// Limitations: -// - no 12-bit-per-channel JPEG -// - no JPEGs with arithmetic coding -// - GIF always returns *comp=4 -// -// Basic usage (see HDR discussion below for HDR usage): -// int x,y,n; -// unsigned char *data = stbi_load(filename, &x, &y, &n, 0); -// // ... process data if not NULL ... -// // ... x = width, y = height, n = # 8-bit components per pixel ... -// // ... replace '0' with '1'..'4' to force that many components per pixel -// // ... but 'n' will always be the number that it would have been if you said 0 -// stbi_image_free(data) -// -// Standard parameters: -// int *x -- outputs image width in pixels -// int *y -- outputs image height in pixels -// int *channels_in_file -- outputs # of image components in image file -// int desired_channels -- if non-zero, # of image components requested in result -// -// The return value from an image loader is an 'unsigned char *' which points -// to the pixel data, or NULL on an allocation failure or if the image is -// corrupt or invalid. The pixel data consists of *y scanlines of *x pixels, -// with each pixel consisting of N interleaved 8-bit components; the first -// pixel pointed to is top-left-most in the image. There is no padding between -// image scanlines or between pixels, regardless of format. The number of -// components N is 'desired_channels' if desired_channels is non-zero, or -// *channels_in_file otherwise. If desired_channels is non-zero, -// *channels_in_file has the number of components that _would_ have been -// output otherwise. E.g. if you set desired_channels to 4, you will always -// get RGBA output, but you can check *channels_in_file to see if it's trivially -// opaque because e.g. there were only 3 channels in the source image. -// -// An output image with N components has the following components interleaved -// in this order in each pixel: -// -// N=#comp components -// 1 grey -// 2 grey, alpha -// 3 red, green, blue -// 4 red, green, blue, alpha -// -// If image loading fails for any reason, the return value will be NULL, -// and *x, *y, *channels_in_file will be unchanged. The function -// stbi_failure_reason() can be queried for an extremely brief, end-user -// unfriendly explanation of why the load failed. Define STBI_NO_FAILURE_STRINGS -// to avoid compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly -// more user-friendly ones. -// -// Paletted PNG, BMP, GIF, and PIC images are automatically depalettized. -// -// =========================================================================== -// -// UNICODE: -// -// If compiling for Windows and you wish to use Unicode filenames, compile -// with -// #define STBI_WINDOWS_UTF8 -// and pass utf8-encoded filenames. Call stbi_convert_wchar_to_utf8 to convert -// Windows wchar_t filenames to utf8. -// -// =========================================================================== -// -// Philosophy -// -// stb libraries are designed with the following priorities: -// -// 1. easy to use -// 2. easy to maintain -// 3. good performance -// -// Sometimes I let "good performance" creep up in priority over "easy to maintain", -// and for best performance I may provide less-easy-to-use APIs that give higher -// performance, in addition to the easy-to-use ones. Nevertheless, it's important -// to keep in mind that from the standpoint of you, a client of this library, -// all you care about is #1 and #3, and stb libraries DO NOT emphasize #3 above all. -// -// Some secondary priorities arise directly from the first two, some of which -// provide more explicit reasons why performance can't be emphasized. -// -// - Portable ("ease of use") -// - Small source code footprint ("easy to maintain") -// - No dependencies ("ease of use") -// -// =========================================================================== -// -// I/O callbacks -// -// I/O callbacks allow you to read from arbitrary sources, like packaged -// files or some other source. Data read from callbacks are processed -// through a small internal buffer (currently 128 bytes) to try to reduce -// overhead. -// -// The three functions you must define are "read" (reads some bytes of data), -// "skip" (skips some bytes of data), "eof" (reports if the stream is at the end). -// -// =========================================================================== -// -// SIMD support -// -// The JPEG decoder will try to automatically use SIMD kernels on x86 when -// supported by the compiler. For ARM Neon support, you must explicitly -// request it. -// -// (The old do-it-yourself SIMD API is no longer supported in the current -// code.) -// -// On x86, SSE2 will automatically be used when available based on a run-time -// test; if not, the generic C versions are used as a fall-back. On ARM targets, -// the typical path is to have separate builds for NEON and non-NEON devices -// (at least this is true for iOS and Android). Therefore, the NEON support is -// toggled by a build flag: define STBI_NEON to get NEON loops. -// -// If for some reason you do not want to use any of SIMD code, or if -// you have issues compiling it, you can disable it entirely by -// defining STBI_NO_SIMD. -// -// =========================================================================== -// -// HDR image support (disable by defining STBI_NO_HDR) -// -// stb_image supports loading HDR images in general, and currently the Radiance -// .HDR file format specifically. You can still load any file through the existing -// interface; if you attempt to load an HDR file, it will be automatically remapped -// to LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1; -// both of these constants can be reconfigured through this interface: -// -// stbi_hdr_to_ldr_gamma(2.2f); -// stbi_hdr_to_ldr_scale(1.0f); -// -// (note, do not use _inverse_ constants; stbi_image will invert them -// appropriately). -// -// Additionally, there is a new, parallel interface for loading files as -// (linear) floats to preserve the full dynamic range: -// -// float *data = stbi_loadf(filename, &x, &y, &n, 0); -// -// If you load LDR images through this interface, those images will -// be promoted to floating point values, run through the inverse of -// constants corresponding to the above: -// -// stbi_ldr_to_hdr_scale(1.0f); -// stbi_ldr_to_hdr_gamma(2.2f); -// -// Finally, given a filename (or an open file or memory block--see header -// file for details) containing image data, you can query for the "most -// appropriate" interface to use (that is, whether the image is HDR or -// not), using: -// -// stbi_is_hdr(char *filename); -// -// =========================================================================== -// -// iPhone PNG support: -// -// By default we convert iphone-formatted PNGs back to RGB, even though -// they are internally encoded differently. You can disable this conversion -// by calling stbi_convert_iphone_png_to_rgb(0), in which case -// you will always just get the native iphone "format" through (which -// is BGR stored in RGB). -// -// Call stbi_set_unpremultiply_on_load(1) as well to force a divide per -// pixel to remove any premultiplied alpha *only* if the image file explicitly -// says there's premultiplied data (currently only happens in iPhone images, -// and only if iPhone convert-to-rgb processing is on). -// -// =========================================================================== -// -// ADDITIONAL CONFIGURATION -// -// - You can suppress implementation of any of the decoders to reduce -// your code footprint by #defining one or more of the following -// symbols before creating the implementation. -// -// STBI_NO_JPEG -// STBI_NO_PNG -// STBI_NO_BMP -// STBI_NO_PSD -// STBI_NO_TGA -// STBI_NO_GIF -// STBI_NO_HDR -// STBI_NO_PIC -// STBI_NO_PNM (.ppm and .pgm) -// -// - You can request *only* certain decoders and suppress all other ones -// (this will be more forward-compatible, as addition of new decoders -// doesn't require you to disable them explicitly): -// -// STBI_ONLY_JPEG -// STBI_ONLY_PNG -// STBI_ONLY_BMP -// STBI_ONLY_PSD -// STBI_ONLY_TGA -// STBI_ONLY_GIF -// STBI_ONLY_HDR -// STBI_ONLY_PIC -// STBI_ONLY_PNM (.ppm and .pgm) -// -// - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still -// want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB -// -// - If you define STBI_MAX_DIMENSIONS, stb_image will reject images greater -// than that size (in either width or height) without further processing. -// This is to let programs in the wild set an upper bound to prevent -// denial-of-service attacks on untrusted data, as one could generate a -// valid image of gigantic dimensions and force stb_image to allocate a -// huge block of memory and spend disproportionate time decoding it. By -// default this is set to (1 << 24), which is 16777216, but that's still -// very big. - -#ifndef STBI_NO_STDIO -#include -#endif // STBI_NO_STDIO - -#define STBI_VERSION 1 - -enum -{ - STBI_default = 0, // only used for desired_channels - - STBI_grey = 1, - STBI_grey_alpha = 2, - STBI_rgb = 3, - STBI_rgb_alpha = 4 -}; - -#include -typedef unsigned char stbi_uc; -typedef unsigned short stbi_us; - -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef STBIDEF -#ifdef STB_IMAGE_STATIC -#define STBIDEF static -#else -#define STBIDEF extern -#endif -#endif - -////////////////////////////////////////////////////////////////////////////// -// -// PRIMARY API - works on images of any type -// - -// -// load image by filename, open file, or memory buffer -// - -typedef struct -{ - int (*read) (void *user,char *data,int size); // fill 'data' with 'size' bytes. return number of bytes actually read - void (*skip) (void *user,int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative - int (*eof) (void *user); // returns nonzero if we are at end of file/data -} stbi_io_callbacks; - -//////////////////////////////////// -// -// 8-bits-per-channel interface -// - -STBIDEF stbi_uc *stbi_load_from_memory (stbi_uc const *buffer, int len , int *x, int *y, int *channels_in_file, int desired_channels); -STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk , void *user, int *x, int *y, int *channels_in_file, int desired_channels); - -#ifndef STBI_NO_STDIO -STBIDEF stbi_uc *stbi_load (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); -STBIDEF stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); -// for stbi_load_from_file, file pointer is left pointing immediately after image -#endif - -#ifndef STBI_NO_GIF -STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp); -#endif - -#ifdef STBI_WINDOWS_UTF8 -STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input); -#endif - -//////////////////////////////////// -// -// 16-bits-per-channel interface -// - -STBIDEF stbi_us *stbi_load_16_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); -STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); - -#ifndef STBI_NO_STDIO -STBIDEF stbi_us *stbi_load_16 (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); -STBIDEF stbi_us *stbi_load_from_file_16(FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); -#endif - -//////////////////////////////////// -// -// float-per-channel interface -// -#ifndef STBI_NO_LINEAR - STBIDEF float *stbi_loadf_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); - STBIDEF float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); - - #ifndef STBI_NO_STDIO - STBIDEF float *stbi_loadf (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); - STBIDEF float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); - #endif -#endif - -#ifndef STBI_NO_HDR - STBIDEF void stbi_hdr_to_ldr_gamma(float gamma); - STBIDEF void stbi_hdr_to_ldr_scale(float scale); -#endif // STBI_NO_HDR - -#ifndef STBI_NO_LINEAR - STBIDEF void stbi_ldr_to_hdr_gamma(float gamma); - STBIDEF void stbi_ldr_to_hdr_scale(float scale); -#endif // STBI_NO_LINEAR - -// stbi_is_hdr is always defined, but always returns false if STBI_NO_HDR -STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user); -STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len); -#ifndef STBI_NO_STDIO -STBIDEF int stbi_is_hdr (char const *filename); -STBIDEF int stbi_is_hdr_from_file(FILE *f); -#endif // STBI_NO_STDIO - - -// get a VERY brief reason for failure -// on most compilers (and ALL modern mainstream compilers) this is threadsafe -STBIDEF const char *stbi_failure_reason (void); - -// free the loaded image -- this is just free() -STBIDEF void stbi_image_free (void *retval_from_stbi_load); - -// get image dimensions & components without fully decoding -STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp); -STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp); -STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len); -STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *clbk, void *user); - -#ifndef STBI_NO_STDIO -STBIDEF int stbi_info (char const *filename, int *x, int *y, int *comp); -STBIDEF int stbi_info_from_file (FILE *f, int *x, int *y, int *comp); -STBIDEF int stbi_is_16_bit (char const *filename); -STBIDEF int stbi_is_16_bit_from_file(FILE *f); -#endif - - - -// for image formats that explicitly notate that they have premultiplied alpha, -// we just return the colors as stored in the file. set this flag to force -// unpremultiplication. results are undefined if the unpremultiply overflow. -STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply); - -// indicate whether we should process iphone images back to canonical format, -// or just pass them through "as-is" -STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert); - -// flip the image vertically, so the first pixel in the output array is the bottom left -STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip); - -// as above, but only applies to images loaded on the thread that calls the function -// this function is only available if your compiler supports thread-local variables; -// calling it will fail to link if your compiler doesn't -STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip); - -// ZLIB client - used by PNG, available for other purposes - -STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen); -STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header); -STBIDEF char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen); -STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); - -STBIDEF char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen); -STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); - - -#ifdef __cplusplus -} -#endif - -// -// -//// end header file ///////////////////////////////////////////////////// -#endif // STBI_INCLUDE_STB_IMAGE_H - -#ifdef STB_IMAGE_IMPLEMENTATION - -#if defined(STBI_ONLY_JPEG) || defined(STBI_ONLY_PNG) || defined(STBI_ONLY_BMP) \ - || defined(STBI_ONLY_TGA) || defined(STBI_ONLY_GIF) || defined(STBI_ONLY_PSD) \ - || defined(STBI_ONLY_HDR) || defined(STBI_ONLY_PIC) || defined(STBI_ONLY_PNM) \ - || defined(STBI_ONLY_ZLIB) - #ifndef STBI_ONLY_JPEG - #define STBI_NO_JPEG - #endif - #ifndef STBI_ONLY_PNG - #define STBI_NO_PNG - #endif - #ifndef STBI_ONLY_BMP - #define STBI_NO_BMP - #endif - #ifndef STBI_ONLY_PSD - #define STBI_NO_PSD - #endif - #ifndef STBI_ONLY_TGA - #define STBI_NO_TGA - #endif - #ifndef STBI_ONLY_GIF - #define STBI_NO_GIF - #endif - #ifndef STBI_ONLY_HDR - #define STBI_NO_HDR - #endif - #ifndef STBI_ONLY_PIC - #define STBI_NO_PIC - #endif - #ifndef STBI_ONLY_PNM - #define STBI_NO_PNM - #endif -#endif - -#if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) && !defined(STBI_NO_ZLIB) -#define STBI_NO_ZLIB -#endif - - -#include -#include // ptrdiff_t on osx -#include -#include -#include - -#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) -#include // ldexp, pow -#endif - -#ifndef STBI_NO_STDIO -#include -#endif - -#ifndef STBI_ASSERT -#include -#define STBI_ASSERT(x) assert(x) -#endif - -#ifdef __cplusplus -#define STBI_EXTERN extern "C" -#else -#define STBI_EXTERN extern -#endif - - -#ifndef _MSC_VER - #ifdef __cplusplus - #define stbi_inline inline - #else - #define stbi_inline - #endif -#else - #define stbi_inline __forceinline -#endif - -#ifndef STBI_NO_THREAD_LOCALS - #if defined(__cplusplus) && __cplusplus >= 201103L - #define STBI_THREAD_LOCAL thread_local - #elif defined(__GNUC__) && __GNUC__ < 5 - #define STBI_THREAD_LOCAL __thread - #elif defined(_MSC_VER) - #define STBI_THREAD_LOCAL __declspec(thread) - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__) - #define STBI_THREAD_LOCAL _Thread_local - #endif - - #ifndef STBI_THREAD_LOCAL - #if defined(__GNUC__) - #define STBI_THREAD_LOCAL __thread - #endif - #endif -#endif - -#ifdef _MSC_VER -typedef unsigned short stbi__uint16; -typedef signed short stbi__int16; -typedef unsigned int stbi__uint32; -typedef signed int stbi__int32; -#else -#include -typedef uint16_t stbi__uint16; -typedef int16_t stbi__int16; -typedef uint32_t stbi__uint32; -typedef int32_t stbi__int32; -#endif - -// should produce compiler error if size is wrong -typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1]; - -#ifdef _MSC_VER -#define STBI_NOTUSED(v) (void)(v) -#else -#define STBI_NOTUSED(v) (void)sizeof(v) -#endif - -#ifdef _MSC_VER -#define STBI_HAS_LROTL -#endif - -#ifdef STBI_HAS_LROTL - #define stbi_lrot(x,y) _lrotl(x,y) -#else - #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (32 - (y)))) -#endif - -#if defined(STBI_MALLOC) && defined(STBI_FREE) && (defined(STBI_REALLOC) || defined(STBI_REALLOC_SIZED)) -// ok -#elif !defined(STBI_MALLOC) && !defined(STBI_FREE) && !defined(STBI_REALLOC) && !defined(STBI_REALLOC_SIZED) -// ok -#else -#error "Must define all or none of STBI_MALLOC, STBI_FREE, and STBI_REALLOC (or STBI_REALLOC_SIZED)." -#endif - -#ifndef STBI_MALLOC -#define STBI_MALLOC(sz) malloc(sz) -#define STBI_REALLOC(p,newsz) realloc(p,newsz) -#define STBI_FREE(p) free(p) -#endif - -#ifndef STBI_REALLOC_SIZED -#define STBI_REALLOC_SIZED(p,oldsz,newsz) ((void)oldsz, STBI_REALLOC(p,newsz)) -#endif - -// x86/x64 detection -#if defined(__x86_64__) || defined(_M_X64) -#define STBI__X64_TARGET -#elif defined(__i386) || defined(_M_IX86) -#define STBI__X86_TARGET -#endif - -#if defined(__GNUC__) && defined(STBI__X86_TARGET) && !defined(__SSE2__) && !defined(STBI_NO_SIMD) -// gcc doesn't support sse2 intrinsics unless you compile with -msse2, -// which in turn means it gets to use SSE2 everywhere. This is unfortunate, -// but previous attempts to provide the SSE2 functions with runtime -// detection caused numerous issues. The way architecture extensions are -// exposed in GCC/Clang is, sadly, not really suited for one-file libs. -// New behavior: if compiled with -msse2, we use SSE2 without any -// detection; if not, we don't use it at all. -#define STBI_NO_SIMD -#endif - -#if defined(__MINGW32__) && defined(STBI__X86_TARGET) && !defined(STBI_MINGW_ENABLE_SSE2) && !defined(STBI_NO_SIMD) -// Note that __MINGW32__ doesn't actually mean 32-bit, so we have to avoid STBI__X64_TARGET -// -// 32-bit MinGW wants ESP to be 16-byte aligned, but this is not in the -// Windows ABI and VC++ as well as Windows DLLs don't maintain that invariant. -// As a result, enabling SSE2 on 32-bit MinGW is dangerous when not -// simultaneously enabling "-mstackrealign". -// -// See https://github.com/nothings/stb/issues/81 for more information. -// -// So default to no SSE2 on 32-bit MinGW. If you've read this far and added -// -mstackrealign to your build settings, feel free to #define STBI_MINGW_ENABLE_SSE2. -#define STBI_NO_SIMD -#endif - -#if !defined(STBI_NO_SIMD) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET)) -#define STBI_SSE2 -#include - -#ifdef _MSC_VER - -#if _MSC_VER >= 1400 // not VC6 -#include // __cpuid -static int stbi__cpuid3(void) -{ - int info[4]; - __cpuid(info,1); - return info[3]; -} -#else -static int stbi__cpuid3(void) -{ - int res; - __asm { - mov eax,1 - cpuid - mov res,edx - } - return res; -} -#endif - -#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name - -#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) -static int stbi__sse2_available(void) -{ - int info3 = stbi__cpuid3(); - return ((info3 >> 26) & 1) != 0; -} -#endif - -#else // assume GCC-style if not VC++ -#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) - -#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) -static int stbi__sse2_available(void) -{ - // If we're even attempting to compile this on GCC/Clang, that means - // -msse2 is on, which means the compiler is allowed to use SSE2 - // instructions at will, and so are we. - return 1; -} -#endif - -#endif -#endif - -// ARM NEON -#if defined(STBI_NO_SIMD) && defined(STBI_NEON) -#undef STBI_NEON -#endif - -#ifdef STBI_NEON -#include -// assume GCC or Clang on ARM targets -#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) -#endif - -#ifndef STBI_SIMD_ALIGN -#define STBI_SIMD_ALIGN(type, name) type name -#endif - -#ifndef STBI_MAX_DIMENSIONS -#define STBI_MAX_DIMENSIONS (1 << 24) -#endif - -/////////////////////////////////////////////// -// -// stbi__context struct and start_xxx functions - -// stbi__context structure is our basic context used by all images, so it -// contains all the IO context, plus some basic image information -typedef struct -{ - stbi__uint32 img_x, img_y; - int img_n, img_out_n; - - stbi_io_callbacks io; - void *io_user_data; - - int read_from_callbacks; - int buflen; - stbi_uc buffer_start[128]; - int callback_already_read; - - stbi_uc *img_buffer, *img_buffer_end; - stbi_uc *img_buffer_original, *img_buffer_original_end; -} stbi__context; - - -static void stbi__refill_buffer(stbi__context *s); - -// initialize a memory-decode context -static void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int len) -{ - s->io.read = NULL; - s->read_from_callbacks = 0; - s->callback_already_read = 0; - s->img_buffer = s->img_buffer_original = (stbi_uc *) buffer; - s->img_buffer_end = s->img_buffer_original_end = (stbi_uc *) buffer+len; -} - -// initialize a callback-based context -static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c, void *user) -{ - s->io = *c; - s->io_user_data = user; - s->buflen = sizeof(s->buffer_start); - s->read_from_callbacks = 1; - s->callback_already_read = 0; - s->img_buffer = s->img_buffer_original = s->buffer_start; - stbi__refill_buffer(s); - s->img_buffer_original_end = s->img_buffer_end; -} - -#ifndef STBI_NO_STDIO - -static int stbi__stdio_read(void *user, char *data, int size) -{ - return (int) fread(data,1,size,(FILE*) user); -} - -static void stbi__stdio_skip(void *user, int n) -{ - int ch; - fseek((FILE*) user, n, SEEK_CUR); - ch = fgetc((FILE*) user); /* have to read a byte to reset feof()'s flag */ - if (ch != EOF) { - ungetc(ch, (FILE *) user); /* push byte back onto stream if valid. */ - } -} - -static int stbi__stdio_eof(void *user) -{ - return feof((FILE*) user) || ferror((FILE *) user); -} - -static stbi_io_callbacks stbi__stdio_callbacks = -{ - stbi__stdio_read, - stbi__stdio_skip, - stbi__stdio_eof, -}; - -static void stbi__start_file(stbi__context *s, FILE *f) -{ - stbi__start_callbacks(s, &stbi__stdio_callbacks, (void *) f); -} - -//static void stop_file(stbi__context *s) { } - -#endif // !STBI_NO_STDIO - -static void stbi__rewind(stbi__context *s) -{ - // conceptually rewind SHOULD rewind to the beginning of the stream, - // but we just rewind to the beginning of the initial buffer, because - // we only use it after doing 'test', which only ever looks at at most 92 bytes - s->img_buffer = s->img_buffer_original; - s->img_buffer_end = s->img_buffer_original_end; -} - -enum -{ - STBI_ORDER_RGB, - STBI_ORDER_BGR -}; - -typedef struct -{ - int bits_per_channel; - int num_channels; - int channel_order; -} stbi__result_info; - -#ifndef STBI_NO_JPEG -static int stbi__jpeg_test(stbi__context *s); -static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); -static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp); -#endif - -#ifndef STBI_NO_PNG -static int stbi__png_test(stbi__context *s); -static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); -static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp); -static int stbi__png_is16(stbi__context *s); -#endif - -#ifndef STBI_NO_BMP -static int stbi__bmp_test(stbi__context *s); -static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); -static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp); -#endif - -#ifndef STBI_NO_TGA -static int stbi__tga_test(stbi__context *s); -static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); -static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp); -#endif - -#ifndef STBI_NO_PSD -static int stbi__psd_test(stbi__context *s); -static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc); -static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp); -static int stbi__psd_is16(stbi__context *s); -#endif - -#ifndef STBI_NO_HDR -static int stbi__hdr_test(stbi__context *s); -static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); -static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp); -#endif - -#ifndef STBI_NO_PIC -static int stbi__pic_test(stbi__context *s); -static void *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); -static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp); -#endif - -#ifndef STBI_NO_GIF -static int stbi__gif_test(stbi__context *s); -static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); -static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp); -static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp); -#endif - -#ifndef STBI_NO_PNM -static int stbi__pnm_test(stbi__context *s); -static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); -static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp); -#endif - -static -#ifdef STBI_THREAD_LOCAL -STBI_THREAD_LOCAL -#endif -const char *stbi__g_failure_reason; - -STBIDEF const char *stbi_failure_reason(void) -{ - return stbi__g_failure_reason; -} - -#ifndef STBI_NO_FAILURE_STRINGS -static int stbi__err(const char *str) -{ - stbi__g_failure_reason = str; - return 0; -} -#endif - -static void *stbi__malloc(size_t size) -{ - return STBI_MALLOC(size); -} - -// stb_image uses ints pervasively, including for offset calculations. -// therefore the largest decoded image size we can support with the -// current code, even on 64-bit targets, is INT_MAX. this is not a -// significant limitation for the intended use case. -// -// we do, however, need to make sure our size calculations don't -// overflow. hence a few helper functions for size calculations that -// multiply integers together, making sure that they're non-negative -// and no overflow occurs. - -// return 1 if the sum is valid, 0 on overflow. -// negative terms are considered invalid. -static int stbi__addsizes_valid(int a, int b) -{ - if (b < 0) return 0; - // now 0 <= b <= INT_MAX, hence also - // 0 <= INT_MAX - b <= INTMAX. - // And "a + b <= INT_MAX" (which might overflow) is the - // same as a <= INT_MAX - b (no overflow) - return a <= INT_MAX - b; -} - -// returns 1 if the product is valid, 0 on overflow. -// negative factors are considered invalid. -static int stbi__mul2sizes_valid(int a, int b) -{ - if (a < 0 || b < 0) return 0; - if (b == 0) return 1; // mul-by-0 is always safe - // portable way to check for no overflows in a*b - return a <= INT_MAX/b; -} - -#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) -// returns 1 if "a*b + add" has no negative terms/factors and doesn't overflow -static int stbi__mad2sizes_valid(int a, int b, int add) -{ - return stbi__mul2sizes_valid(a, b) && stbi__addsizes_valid(a*b, add); -} -#endif - -// returns 1 if "a*b*c + add" has no negative terms/factors and doesn't overflow -static int stbi__mad3sizes_valid(int a, int b, int c, int add) -{ - return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && - stbi__addsizes_valid(a*b*c, add); -} - -// returns 1 if "a*b*c*d + add" has no negative terms/factors and doesn't overflow -#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) -static int stbi__mad4sizes_valid(int a, int b, int c, int d, int add) -{ - return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && - stbi__mul2sizes_valid(a*b*c, d) && stbi__addsizes_valid(a*b*c*d, add); -} -#endif - -#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) -// mallocs with size overflow checking -static void *stbi__malloc_mad2(int a, int b, int add) -{ - if (!stbi__mad2sizes_valid(a, b, add)) return NULL; - return stbi__malloc(a*b + add); -} -#endif - -static void *stbi__malloc_mad3(int a, int b, int c, int add) -{ - if (!stbi__mad3sizes_valid(a, b, c, add)) return NULL; - return stbi__malloc(a*b*c + add); -} - -#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) -static void *stbi__malloc_mad4(int a, int b, int c, int d, int add) -{ - if (!stbi__mad4sizes_valid(a, b, c, d, add)) return NULL; - return stbi__malloc(a*b*c*d + add); -} -#endif - -// stbi__err - error -// stbi__errpf - error returning pointer to float -// stbi__errpuc - error returning pointer to unsigned char - -#ifdef STBI_NO_FAILURE_STRINGS - #define stbi__err(x,y) 0 -#elif defined(STBI_FAILURE_USERMSG) - #define stbi__err(x,y) stbi__err(y) -#else - #define stbi__err(x,y) stbi__err(x) -#endif - -#define stbi__errpf(x,y) ((float *)(size_t) (stbi__err(x,y)?NULL:NULL)) -#define stbi__errpuc(x,y) ((unsigned char *)(size_t) (stbi__err(x,y)?NULL:NULL)) - -STBIDEF void stbi_image_free(void *retval_from_stbi_load) -{ - STBI_FREE(retval_from_stbi_load); -} - -#ifndef STBI_NO_LINEAR -static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp); -#endif - -#ifndef STBI_NO_HDR -static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp); -#endif - -static int stbi__vertically_flip_on_load_global = 0; - -STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip) -{ - stbi__vertically_flip_on_load_global = flag_true_if_should_flip; -} - -#ifndef STBI_THREAD_LOCAL -#define stbi__vertically_flip_on_load stbi__vertically_flip_on_load_global -#else -static STBI_THREAD_LOCAL int stbi__vertically_flip_on_load_local, stbi__vertically_flip_on_load_set; - -STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip) -{ - stbi__vertically_flip_on_load_local = flag_true_if_should_flip; - stbi__vertically_flip_on_load_set = 1; -} - -#define stbi__vertically_flip_on_load (stbi__vertically_flip_on_load_set \ - ? stbi__vertically_flip_on_load_local \ - : stbi__vertically_flip_on_load_global) -#endif // STBI_THREAD_LOCAL - -static void *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) -{ - memset(ri, 0, sizeof(*ri)); // make sure it's initialized if we add new fields - ri->bits_per_channel = 8; // default is 8 so most paths don't have to be changed - ri->channel_order = STBI_ORDER_RGB; // all current input & output are this, but this is here so we can add BGR order - ri->num_channels = 0; - - #ifndef STBI_NO_JPEG - if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp, ri); - #endif - #ifndef STBI_NO_PNG - if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp, ri); - #endif - #ifndef STBI_NO_BMP - if (stbi__bmp_test(s)) return stbi__bmp_load(s,x,y,comp,req_comp, ri); - #endif - #ifndef STBI_NO_GIF - if (stbi__gif_test(s)) return stbi__gif_load(s,x,y,comp,req_comp, ri); - #endif - #ifndef STBI_NO_PSD - if (stbi__psd_test(s)) return stbi__psd_load(s,x,y,comp,req_comp, ri, bpc); - #else - STBI_NOTUSED(bpc); - #endif - #ifndef STBI_NO_PIC - if (stbi__pic_test(s)) return stbi__pic_load(s,x,y,comp,req_comp, ri); - #endif - #ifndef STBI_NO_PNM - if (stbi__pnm_test(s)) return stbi__pnm_load(s,x,y,comp,req_comp, ri); - #endif - - #ifndef STBI_NO_HDR - if (stbi__hdr_test(s)) { - float *hdr = stbi__hdr_load(s, x,y,comp,req_comp, ri); - return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp); - } - #endif - - #ifndef STBI_NO_TGA - // test tga last because it's a crappy test! - if (stbi__tga_test(s)) - return stbi__tga_load(s,x,y,comp,req_comp, ri); - #endif - - return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt"); -} - -static stbi_uc *stbi__convert_16_to_8(stbi__uint16 *orig, int w, int h, int channels) -{ - int i; - int img_len = w * h * channels; - stbi_uc *reduced; - - reduced = (stbi_uc *) stbi__malloc(img_len); - if (reduced == NULL) return stbi__errpuc("outofmem", "Out of memory"); - - for (i = 0; i < img_len; ++i) - reduced[i] = (stbi_uc)((orig[i] >> 8) & 0xFF); // top half of each byte is sufficient approx of 16->8 bit scaling - - STBI_FREE(orig); - return reduced; -} - -static stbi__uint16 *stbi__convert_8_to_16(stbi_uc *orig, int w, int h, int channels) -{ - int i; - int img_len = w * h * channels; - stbi__uint16 *enlarged; - - enlarged = (stbi__uint16 *) stbi__malloc(img_len*2); - if (enlarged == NULL) return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); - - for (i = 0; i < img_len; ++i) - enlarged[i] = (stbi__uint16)((orig[i] << 8) + orig[i]); // replicate to high and low byte, maps 0->0, 255->0xffff - - STBI_FREE(orig); - return enlarged; -} - -static void stbi__vertical_flip(void *image, int w, int h, int bytes_per_pixel) -{ - int row; - size_t bytes_per_row = (size_t)w * bytes_per_pixel; - stbi_uc temp[2048]; - stbi_uc *bytes = (stbi_uc *)image; - - for (row = 0; row < (h>>1); row++) { - stbi_uc *row0 = bytes + row*bytes_per_row; - stbi_uc *row1 = bytes + (h - row - 1)*bytes_per_row; - // swap row0 with row1 - size_t bytes_left = bytes_per_row; - while (bytes_left) { - size_t bytes_copy = (bytes_left < sizeof(temp)) ? bytes_left : sizeof(temp); - memcpy(temp, row0, bytes_copy); - memcpy(row0, row1, bytes_copy); - memcpy(row1, temp, bytes_copy); - row0 += bytes_copy; - row1 += bytes_copy; - bytes_left -= bytes_copy; - } - } -} - -#ifndef STBI_NO_GIF -static void stbi__vertical_flip_slices(void *image, int w, int h, int z, int bytes_per_pixel) -{ - int slice; - int slice_size = w * h * bytes_per_pixel; - - stbi_uc *bytes = (stbi_uc *)image; - for (slice = 0; slice < z; ++slice) { - stbi__vertical_flip(bytes, w, h, bytes_per_pixel); - bytes += slice_size; - } -} -#endif - -static unsigned char *stbi__load_and_postprocess_8bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) -{ - stbi__result_info ri; - void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 8); - - if (result == NULL) - return NULL; - - // it is the responsibility of the loaders to make sure we get either 8 or 16 bit. - STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); - - if (ri.bits_per_channel != 8) { - result = stbi__convert_16_to_8((stbi__uint16 *) result, *x, *y, req_comp == 0 ? *comp : req_comp); - ri.bits_per_channel = 8; - } - - // @TODO: move stbi__convert_format to here - - if (stbi__vertically_flip_on_load) { - int channels = req_comp ? req_comp : *comp; - stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi_uc)); - } - - return (unsigned char *) result; -} - -static stbi__uint16 *stbi__load_and_postprocess_16bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) -{ - stbi__result_info ri; - void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 16); - - if (result == NULL) - return NULL; - - // it is the responsibility of the loaders to make sure we get either 8 or 16 bit. - STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); - - if (ri.bits_per_channel != 16) { - result = stbi__convert_8_to_16((stbi_uc *) result, *x, *y, req_comp == 0 ? *comp : req_comp); - ri.bits_per_channel = 16; - } - - // @TODO: move stbi__convert_format16 to here - // @TODO: special case RGB-to-Y (and RGBA-to-YA) for 8-bit-to-16-bit case to keep more precision - - if (stbi__vertically_flip_on_load) { - int channels = req_comp ? req_comp : *comp; - stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi__uint16)); - } - - return (stbi__uint16 *) result; -} - -#if !defined(STBI_NO_HDR) && !defined(STBI_NO_LINEAR) -static void stbi__float_postprocess(float *result, int *x, int *y, int *comp, int req_comp) -{ - if (stbi__vertically_flip_on_load && result != NULL) { - int channels = req_comp ? req_comp : *comp; - stbi__vertical_flip(result, *x, *y, channels * sizeof(float)); - } -} -#endif - -#ifndef STBI_NO_STDIO - -#if defined(_MSC_VER) && defined(STBI_WINDOWS_UTF8) -STBI_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide); -STBI_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t *widestr, int cchwide, char *str, int cbmb, const char *defchar, int *used_default); -#endif - -#if defined(_MSC_VER) && defined(STBI_WINDOWS_UTF8) -STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input) -{ - return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, NULL); -} -#endif - -static FILE *stbi__fopen(char const *filename, char const *mode) -{ - FILE *f; -#if defined(_MSC_VER) && defined(STBI_WINDOWS_UTF8) - wchar_t wMode[64]; - wchar_t wFilename[1024]; - if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename))) - return 0; - - if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode))) - return 0; - -#if _MSC_VER >= 1400 - if (0 != _wfopen_s(&f, wFilename, wMode)) - f = 0; -#else - f = _wfopen(wFilename, wMode); -#endif - -#elif defined(_MSC_VER) && _MSC_VER >= 1400 - if (0 != fopen_s(&f, filename, mode)) - f=0; -#else - f = fopen(filename, mode); -#endif - return f; -} - - -STBIDEF stbi_uc *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp) -{ - FILE *f = stbi__fopen(filename, "rb"); - unsigned char *result; - if (!f) return stbi__errpuc("can't fopen", "Unable to open file"); - result = stbi_load_from_file(f,x,y,comp,req_comp); - fclose(f); - return result; -} - -STBIDEF stbi_uc *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) -{ - unsigned char *result; - stbi__context s; - stbi__start_file(&s,f); - result = stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); - if (result) { - // need to 'unget' all the characters in the IO buffer - fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); - } - return result; -} - -STBIDEF stbi__uint16 *stbi_load_from_file_16(FILE *f, int *x, int *y, int *comp, int req_comp) -{ - stbi__uint16 *result; - stbi__context s; - stbi__start_file(&s,f); - result = stbi__load_and_postprocess_16bit(&s,x,y,comp,req_comp); - if (result) { - // need to 'unget' all the characters in the IO buffer - fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); - } - return result; -} - -STBIDEF stbi_us *stbi_load_16(char const *filename, int *x, int *y, int *comp, int req_comp) -{ - FILE *f = stbi__fopen(filename, "rb"); - stbi__uint16 *result; - if (!f) return (stbi_us *) stbi__errpuc("can't fopen", "Unable to open file"); - result = stbi_load_from_file_16(f,x,y,comp,req_comp); - fclose(f); - return result; -} - - -#endif //!STBI_NO_STDIO - -STBIDEF stbi_us *stbi_load_16_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels) -{ - stbi__context s; - stbi__start_mem(&s,buffer,len); - return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels); -} - -STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels) -{ - stbi__context s; - stbi__start_callbacks(&s, (stbi_io_callbacks *)clbk, user); - return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels); -} - -STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) -{ - stbi__context s; - stbi__start_mem(&s,buffer,len); - return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); -} - -STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) -{ - stbi__context s; - stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); - return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); -} - -#ifndef STBI_NO_GIF -STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp) -{ - unsigned char *result; - stbi__context s; - stbi__start_mem(&s,buffer,len); - - result = (unsigned char*) stbi__load_gif_main(&s, delays, x, y, z, comp, req_comp); - if (stbi__vertically_flip_on_load) { - stbi__vertical_flip_slices( result, *x, *y, *z, *comp ); - } - - return result; -} -#endif - -#ifndef STBI_NO_LINEAR -static float *stbi__loadf_main(stbi__context *s, int *x, int *y, int *comp, int req_comp) -{ - unsigned char *data; - #ifndef STBI_NO_HDR - if (stbi__hdr_test(s)) { - stbi__result_info ri; - float *hdr_data = stbi__hdr_load(s,x,y,comp,req_comp, &ri); - if (hdr_data) - stbi__float_postprocess(hdr_data,x,y,comp,req_comp); - return hdr_data; - } - #endif - data = stbi__load_and_postprocess_8bit(s, x, y, comp, req_comp); - if (data) - return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp); - return stbi__errpf("unknown image type", "Image not of any known type, or corrupt"); -} - -STBIDEF float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) -{ - stbi__context s; - stbi__start_mem(&s,buffer,len); - return stbi__loadf_main(&s,x,y,comp,req_comp); -} - -STBIDEF float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) -{ - stbi__context s; - stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); - return stbi__loadf_main(&s,x,y,comp,req_comp); -} - -#ifndef STBI_NO_STDIO -STBIDEF float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp) -{ - float *result; - FILE *f = stbi__fopen(filename, "rb"); - if (!f) return stbi__errpf("can't fopen", "Unable to open file"); - result = stbi_loadf_from_file(f,x,y,comp,req_comp); - fclose(f); - return result; -} - -STBIDEF float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) -{ - stbi__context s; - stbi__start_file(&s,f); - return stbi__loadf_main(&s,x,y,comp,req_comp); -} -#endif // !STBI_NO_STDIO - -#endif // !STBI_NO_LINEAR - -// these is-hdr-or-not is defined independent of whether STBI_NO_LINEAR is -// defined, for API simplicity; if STBI_NO_LINEAR is defined, it always -// reports false! - -STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len) -{ - #ifndef STBI_NO_HDR - stbi__context s; - stbi__start_mem(&s,buffer,len); - return stbi__hdr_test(&s); - #else - STBI_NOTUSED(buffer); - STBI_NOTUSED(len); - return 0; - #endif -} - -#ifndef STBI_NO_STDIO -STBIDEF int stbi_is_hdr (char const *filename) -{ - FILE *f = stbi__fopen(filename, "rb"); - int result=0; - if (f) { - result = stbi_is_hdr_from_file(f); - fclose(f); - } - return result; -} - -STBIDEF int stbi_is_hdr_from_file(FILE *f) -{ - #ifndef STBI_NO_HDR - long pos = ftell(f); - int res; - stbi__context s; - stbi__start_file(&s,f); - res = stbi__hdr_test(&s); - fseek(f, pos, SEEK_SET); - return res; - #else - STBI_NOTUSED(f); - return 0; - #endif -} -#endif // !STBI_NO_STDIO - -STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user) -{ - #ifndef STBI_NO_HDR - stbi__context s; - stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); - return stbi__hdr_test(&s); - #else - STBI_NOTUSED(clbk); - STBI_NOTUSED(user); - return 0; - #endif -} - -#ifndef STBI_NO_LINEAR -static float stbi__l2h_gamma=2.2f, stbi__l2h_scale=1.0f; - -STBIDEF void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; } -STBIDEF void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; } -#endif - -static float stbi__h2l_gamma_i=1.0f/2.2f, stbi__h2l_scale_i=1.0f; - -STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1/gamma; } -STBIDEF void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1/scale; } - - -////////////////////////////////////////////////////////////////////////////// -// -// Common code used by all image loaders -// - -enum -{ - STBI__SCAN_load=0, - STBI__SCAN_type, - STBI__SCAN_header -}; - -static void stbi__refill_buffer(stbi__context *s) -{ - int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen); - s->callback_already_read += (int) (s->img_buffer - s->img_buffer_original); - if (n == 0) { - // at end of file, treat same as if from memory, but need to handle case - // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file - s->read_from_callbacks = 0; - s->img_buffer = s->buffer_start; - s->img_buffer_end = s->buffer_start+1; - *s->img_buffer = 0; - } else { - s->img_buffer = s->buffer_start; - s->img_buffer_end = s->buffer_start + n; - } -} - -stbi_inline static stbi_uc stbi__get8(stbi__context *s) -{ - if (s->img_buffer < s->img_buffer_end) - return *s->img_buffer++; - if (s->read_from_callbacks) { - stbi__refill_buffer(s); - return *s->img_buffer++; - } - return 0; -} - -#if defined(STBI_NO_JPEG) && defined(STBI_NO_HDR) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) -// nothing -#else -stbi_inline static int stbi__at_eof(stbi__context *s) -{ - if (s->io.read) { - if (!(s->io.eof)(s->io_user_data)) return 0; - // if feof() is true, check if buffer = end - // special case: we've only got the special 0 character at the end - if (s->read_from_callbacks == 0) return 1; - } - - return s->img_buffer >= s->img_buffer_end; -} -#endif - -#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) -// nothing -#else -static void stbi__skip(stbi__context *s, int n) -{ - if (n == 0) return; // already there! - if (n < 0) { - s->img_buffer = s->img_buffer_end; - return; - } - if (s->io.read) { - int blen = (int) (s->img_buffer_end - s->img_buffer); - if (blen < n) { - s->img_buffer = s->img_buffer_end; - (s->io.skip)(s->io_user_data, n - blen); - return; - } - } - s->img_buffer += n; -} -#endif - -#if defined(STBI_NO_PNG) && defined(STBI_NO_TGA) && defined(STBI_NO_HDR) && defined(STBI_NO_PNM) -// nothing -#else -static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n) -{ - if (s->io.read) { - int blen = (int) (s->img_buffer_end - s->img_buffer); - if (blen < n) { - int res, count; - - memcpy(buffer, s->img_buffer, blen); - - count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen); - res = (count == (n-blen)); - s->img_buffer = s->img_buffer_end; - return res; - } - } - - if (s->img_buffer+n <= s->img_buffer_end) { - memcpy(buffer, s->img_buffer, n); - s->img_buffer += n; - return 1; - } else - return 0; -} -#endif - -#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC) -// nothing -#else -static int stbi__get16be(stbi__context *s) -{ - int z = stbi__get8(s); - return (z << 8) + stbi__get8(s); -} -#endif - -#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC) -// nothing -#else -static stbi__uint32 stbi__get32be(stbi__context *s) -{ - stbi__uint32 z = stbi__get16be(s); - return (z << 16) + stbi__get16be(s); -} -#endif - -#if defined(STBI_NO_BMP) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) -// nothing -#else -static int stbi__get16le(stbi__context *s) -{ - int z = stbi__get8(s); - return z + (stbi__get8(s) << 8); -} -#endif - -#ifndef STBI_NO_BMP -static stbi__uint32 stbi__get32le(stbi__context *s) -{ - stbi__uint32 z = stbi__get16le(s); - return z + (stbi__get16le(s) << 16); -} -#endif - -#define STBI__BYTECAST(x) ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings - -#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) -// nothing -#else -////////////////////////////////////////////////////////////////////////////// -// -// generic converter from built-in img_n to req_comp -// individual types do this automatically as much as possible (e.g. jpeg -// does all cases internally since it needs to colorspace convert anyway, -// and it never has alpha, so very few cases ). png can automatically -// interleave an alpha=255 channel, but falls back to this for other cases -// -// assume data buffer is malloced, so malloc a new one and free that one -// only failure mode is malloc failing - -static stbi_uc stbi__compute_y(int r, int g, int b) -{ - return (stbi_uc) (((r*77) + (g*150) + (29*b)) >> 8); -} -#endif - -#if defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) -// nothing -#else -static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y) -{ - int i,j; - unsigned char *good; - - if (req_comp == img_n) return data; - STBI_ASSERT(req_comp >= 1 && req_comp <= 4); - - good = (unsigned char *) stbi__malloc_mad3(req_comp, x, y, 0); - if (good == NULL) { - STBI_FREE(data); - return stbi__errpuc("outofmem", "Out of memory"); - } - - for (j=0; j < (int) y; ++j) { - unsigned char *src = data + j * x * img_n ; - unsigned char *dest = good + j * x * req_comp; - - #define STBI__COMBO(a,b) ((a)*8+(b)) - #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) - // convert source image with img_n components to one with req_comp components; - // avoid switch per pixel, so use switch per scanline and massive macros - switch (STBI__COMBO(img_n, req_comp)) { - STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=255; } break; - STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; - STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=255; } break; - STBI__CASE(2,1) { dest[0]=src[0]; } break; - STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; - STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break; - STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=255; } break; - STBI__CASE(3,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break; - STBI__CASE(3,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = 255; } break; - STBI__CASE(4,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break; - STBI__CASE(4,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = src[3]; } break; - STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break; - default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return stbi__errpuc("unsupported", "Unsupported format conversion"); - } - #undef STBI__CASE - } - - STBI_FREE(data); - return good; -} -#endif - -#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) -// nothing -#else -static stbi__uint16 stbi__compute_y_16(int r, int g, int b) -{ - return (stbi__uint16) (((r*77) + (g*150) + (29*b)) >> 8); -} -#endif - -#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) -// nothing -#else -static stbi__uint16 *stbi__convert_format16(stbi__uint16 *data, int img_n, int req_comp, unsigned int x, unsigned int y) -{ - int i,j; - stbi__uint16 *good; - - if (req_comp == img_n) return data; - STBI_ASSERT(req_comp >= 1 && req_comp <= 4); - - good = (stbi__uint16 *) stbi__malloc(req_comp * x * y * 2); - if (good == NULL) { - STBI_FREE(data); - return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); - } - - for (j=0; j < (int) y; ++j) { - stbi__uint16 *src = data + j * x * img_n ; - stbi__uint16 *dest = good + j * x * req_comp; - - #define STBI__COMBO(a,b) ((a)*8+(b)) - #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) - // convert source image with img_n components to one with req_comp components; - // avoid switch per pixel, so use switch per scanline and massive macros - switch (STBI__COMBO(img_n, req_comp)) { - STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=0xffff; } break; - STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; - STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=0xffff; } break; - STBI__CASE(2,1) { dest[0]=src[0]; } break; - STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; - STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break; - STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=0xffff; } break; - STBI__CASE(3,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break; - STBI__CASE(3,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = 0xffff; } break; - STBI__CASE(4,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break; - STBI__CASE(4,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = src[3]; } break; - STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break; - default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return (stbi__uint16*) stbi__errpuc("unsupported", "Unsupported format conversion"); - } - #undef STBI__CASE - } - - STBI_FREE(data); - return good; -} -#endif - -#ifndef STBI_NO_LINEAR -static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp) -{ - int i,k,n; - float *output; - if (!data) return NULL; - output = (float *) stbi__malloc_mad4(x, y, comp, sizeof(float), 0); - if (output == NULL) { STBI_FREE(data); return stbi__errpf("outofmem", "Out of memory"); } - // compute number of non-alpha components - if (comp & 1) n = comp; else n = comp-1; - for (i=0; i < x*y; ++i) { - for (k=0; k < n; ++k) { - output[i*comp + k] = (float) (pow(data[i*comp+k]/255.0f, stbi__l2h_gamma) * stbi__l2h_scale); - } - } - if (n < comp) { - for (i=0; i < x*y; ++i) { - output[i*comp + n] = data[i*comp + n]/255.0f; - } - } - STBI_FREE(data); - return output; -} -#endif - -#ifndef STBI_NO_HDR -#define stbi__float2int(x) ((int) (x)) -static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp) -{ - int i,k,n; - stbi_uc *output; - if (!data) return NULL; - output = (stbi_uc *) stbi__malloc_mad3(x, y, comp, 0); - if (output == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); } - // compute number of non-alpha components - if (comp & 1) n = comp; else n = comp-1; - for (i=0; i < x*y; ++i) { - for (k=0; k < n; ++k) { - float z = (float) pow(data[i*comp+k]*stbi__h2l_scale_i, stbi__h2l_gamma_i) * 255 + 0.5f; - if (z < 0) z = 0; - if (z > 255) z = 255; - output[i*comp + k] = (stbi_uc) stbi__float2int(z); - } - if (k < comp) { - float z = data[i*comp+k] * 255 + 0.5f; - if (z < 0) z = 0; - if (z > 255) z = 255; - output[i*comp + k] = (stbi_uc) stbi__float2int(z); - } - } - STBI_FREE(data); - return output; -} -#endif - -////////////////////////////////////////////////////////////////////////////// -// -// "baseline" JPEG/JFIF decoder -// -// simple implementation -// - doesn't support delayed output of y-dimension -// - simple interface (only one output format: 8-bit interleaved RGB) -// - doesn't try to recover corrupt jpegs -// - doesn't allow partial loading, loading multiple at once -// - still fast on x86 (copying globals into locals doesn't help x86) -// - allocates lots of intermediate memory (full size of all components) -// - non-interleaved case requires this anyway -// - allows good upsampling (see next) -// high-quality -// - upsampled channels are bilinearly interpolated, even across blocks -// - quality integer IDCT derived from IJG's 'slow' -// performance -// - fast huffman; reasonable integer IDCT -// - some SIMD kernels for common paths on targets with SSE2/NEON -// - uses a lot of intermediate memory, could cache poorly - -#ifndef STBI_NO_JPEG - -// huffman decoding acceleration -#define FAST_BITS 9 // larger handles more cases; smaller stomps less cache - -typedef struct -{ - stbi_uc fast[1 << FAST_BITS]; - // weirdly, repacking this into AoS is a 10% speed loss, instead of a win - stbi__uint16 code[256]; - stbi_uc values[256]; - stbi_uc size[257]; - unsigned int maxcode[18]; - int delta[17]; // old 'firstsymbol' - old 'firstcode' -} stbi__huffman; - -typedef struct -{ - stbi__context *s; - stbi__huffman huff_dc[4]; - stbi__huffman huff_ac[4]; - stbi__uint16 dequant[4][64]; - stbi__int16 fast_ac[4][1 << FAST_BITS]; - -// sizes for components, interleaved MCUs - int img_h_max, img_v_max; - int img_mcu_x, img_mcu_y; - int img_mcu_w, img_mcu_h; - -// definition of jpeg image component - struct - { - int id; - int h,v; - int tq; - int hd,ha; - int dc_pred; - - int x,y,w2,h2; - stbi_uc *data; - void *raw_data, *raw_coeff; - stbi_uc *linebuf; - short *coeff; // progressive only - int coeff_w, coeff_h; // number of 8x8 coefficient blocks - } img_comp[4]; - - stbi__uint32 code_buffer; // jpeg entropy-coded buffer - int code_bits; // number of valid bits - unsigned char marker; // marker seen while filling entropy buffer - int nomore; // flag if we saw a marker so must stop - - int progressive; - int spec_start; - int spec_end; - int succ_high; - int succ_low; - int eob_run; - int jfif; - int app14_color_transform; // Adobe APP14 tag - int rgb; - - int scan_n, order[4]; - int restart_interval, todo; - -// kernels - void (*idct_block_kernel)(stbi_uc *out, int out_stride, short data[64]); - void (*YCbCr_to_RGB_kernel)(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step); - stbi_uc *(*resample_row_hv_2_kernel)(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs); -} stbi__jpeg; - -static int stbi__build_huffman(stbi__huffman *h, int *count) -{ - int i,j,k=0; - unsigned int code; - // build size list for each symbol (from JPEG spec) - for (i=0; i < 16; ++i) - for (j=0; j < count[i]; ++j) - h->size[k++] = (stbi_uc) (i+1); - h->size[k] = 0; - - // compute actual symbols (from jpeg spec) - code = 0; - k = 0; - for(j=1; j <= 16; ++j) { - // compute delta to add to code to compute symbol id - h->delta[j] = k - code; - if (h->size[k] == j) { - while (h->size[k] == j) - h->code[k++] = (stbi__uint16) (code++); - if (code-1 >= (1u << j)) return stbi__err("bad code lengths","Corrupt JPEG"); - } - // compute largest code + 1 for this size, preshifted as needed later - h->maxcode[j] = code << (16-j); - code <<= 1; - } - h->maxcode[j] = 0xffffffff; - - // build non-spec acceleration table; 255 is flag for not-accelerated - memset(h->fast, 255, 1 << FAST_BITS); - for (i=0; i < k; ++i) { - int s = h->size[i]; - if (s <= FAST_BITS) { - int c = h->code[i] << (FAST_BITS-s); - int m = 1 << (FAST_BITS-s); - for (j=0; j < m; ++j) { - h->fast[c+j] = (stbi_uc) i; - } - } - } - return 1; -} - -// build a table that decodes both magnitude and value of small ACs in -// one go. -static void stbi__build_fast_ac(stbi__int16 *fast_ac, stbi__huffman *h) -{ - int i; - for (i=0; i < (1 << FAST_BITS); ++i) { - stbi_uc fast = h->fast[i]; - fast_ac[i] = 0; - if (fast < 255) { - int rs = h->values[fast]; - int run = (rs >> 4) & 15; - int magbits = rs & 15; - int len = h->size[fast]; - - if (magbits && len + magbits <= FAST_BITS) { - // magnitude code followed by receive_extend code - int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> (FAST_BITS - magbits); - int m = 1 << (magbits - 1); - if (k < m) k += (~0U << magbits) + 1; - // if the result is small enough, we can fit it in fast_ac table - if (k >= -128 && k <= 127) - fast_ac[i] = (stbi__int16) ((k * 256) + (run * 16) + (len + magbits)); - } - } - } -} - -static void stbi__grow_buffer_unsafe(stbi__jpeg *j) -{ - do { - unsigned int b = j->nomore ? 0 : stbi__get8(j->s); - if (b == 0xff) { - int c = stbi__get8(j->s); - while (c == 0xff) c = stbi__get8(j->s); // consume fill bytes - if (c != 0) { - j->marker = (unsigned char) c; - j->nomore = 1; - return; - } - } - j->code_buffer |= b << (24 - j->code_bits); - j->code_bits += 8; - } while (j->code_bits <= 24); -} - -// (1 << n) - 1 -static const stbi__uint32 stbi__bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535}; - -// decode a jpeg huffman value from the bitstream -stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h) -{ - unsigned int temp; - int c,k; - - if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); - - // look at the top FAST_BITS and determine what symbol ID it is, - // if the code is <= FAST_BITS - c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); - k = h->fast[c]; - if (k < 255) { - int s = h->size[k]; - if (s > j->code_bits) - return -1; - j->code_buffer <<= s; - j->code_bits -= s; - return h->values[k]; - } - - // naive test is to shift the code_buffer down so k bits are - // valid, then test against maxcode. To speed this up, we've - // preshifted maxcode left so that it has (16-k) 0s at the - // end; in other words, regardless of the number of bits, it - // wants to be compared against something shifted to have 16; - // that way we don't need to shift inside the loop. - temp = j->code_buffer >> 16; - for (k=FAST_BITS+1 ; ; ++k) - if (temp < h->maxcode[k]) - break; - if (k == 17) { - // error! code not found - j->code_bits -= 16; - return -1; - } - - if (k > j->code_bits) - return -1; - - // convert the huffman code to the symbol id - c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k]; - STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]); - - // convert the id to a symbol - j->code_bits -= k; - j->code_buffer <<= k; - return h->values[c]; -} - -// bias[n] = (-1<code_bits < n) stbi__grow_buffer_unsafe(j); - - sgn = (stbi__int32)j->code_buffer >> 31; // sign bit is always in MSB - k = stbi_lrot(j->code_buffer, n); - if (n < 0 || n >= (int) (sizeof(stbi__bmask)/sizeof(*stbi__bmask))) return 0; - j->code_buffer = k & ~stbi__bmask[n]; - k &= stbi__bmask[n]; - j->code_bits -= n; - return k + (stbi__jbias[n] & ~sgn); -} - -// get some unsigned bits -stbi_inline static int stbi__jpeg_get_bits(stbi__jpeg *j, int n) -{ - unsigned int k; - if (j->code_bits < n) stbi__grow_buffer_unsafe(j); - k = stbi_lrot(j->code_buffer, n); - j->code_buffer = k & ~stbi__bmask[n]; - k &= stbi__bmask[n]; - j->code_bits -= n; - return k; -} - -stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg *j) -{ - unsigned int k; - if (j->code_bits < 1) stbi__grow_buffer_unsafe(j); - k = j->code_buffer; - j->code_buffer <<= 1; - --j->code_bits; - return k & 0x80000000; -} - -// given a value that's at position X in the zigzag stream, -// where does it appear in the 8x8 matrix coded as row-major? -static const stbi_uc stbi__jpeg_dezigzag[64+15] = -{ - 0, 1, 8, 16, 9, 2, 3, 10, - 17, 24, 32, 25, 18, 11, 4, 5, - 12, 19, 26, 33, 40, 48, 41, 34, - 27, 20, 13, 6, 7, 14, 21, 28, - 35, 42, 49, 56, 57, 50, 43, 36, - 29, 22, 15, 23, 30, 37, 44, 51, - 58, 59, 52, 45, 38, 31, 39, 46, - 53, 60, 61, 54, 47, 55, 62, 63, - // let corrupt input sample past end - 63, 63, 63, 63, 63, 63, 63, 63, - 63, 63, 63, 63, 63, 63, 63 -}; - -// decode one 64-entry block-- -static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman *hdc, stbi__huffman *hac, stbi__int16 *fac, int b, stbi__uint16 *dequant) -{ - int diff,dc,k; - int t; - - if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); - t = stbi__jpeg_huff_decode(j, hdc); - if (t < 0) return stbi__err("bad huffman code","Corrupt JPEG"); - - // 0 all the ac values now so we can do it 32-bits at a time - memset(data,0,64*sizeof(data[0])); - - diff = t ? stbi__extend_receive(j, t) : 0; - dc = j->img_comp[b].dc_pred + diff; - j->img_comp[b].dc_pred = dc; - data[0] = (short) (dc * dequant[0]); - - // decode AC components, see JPEG spec - k = 1; - do { - unsigned int zig; - int c,r,s; - if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); - c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); - r = fac[c]; - if (r) { // fast-AC path - k += (r >> 4) & 15; // run - s = r & 15; // combined length - j->code_buffer <<= s; - j->code_bits -= s; - // decode into unzigzag'd location - zig = stbi__jpeg_dezigzag[k++]; - data[zig] = (short) ((r >> 8) * dequant[zig]); - } else { - int rs = stbi__jpeg_huff_decode(j, hac); - if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); - s = rs & 15; - r = rs >> 4; - if (s == 0) { - if (rs != 0xf0) break; // end block - k += 16; - } else { - k += r; - // decode into unzigzag'd location - zig = stbi__jpeg_dezigzag[k++]; - data[zig] = (short) (stbi__extend_receive(j,s) * dequant[zig]); - } - } - } while (k < 64); - return 1; -} - -static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg *j, short data[64], stbi__huffman *hdc, int b) -{ - int diff,dc; - int t; - if (j->spec_end != 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); - - if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); - - if (j->succ_high == 0) { - // first scan for DC coefficient, must be first - memset(data,0,64*sizeof(data[0])); // 0 all the ac values now - t = stbi__jpeg_huff_decode(j, hdc); - if (t == -1) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); - diff = t ? stbi__extend_receive(j, t) : 0; - - dc = j->img_comp[b].dc_pred + diff; - j->img_comp[b].dc_pred = dc; - data[0] = (short) (dc << j->succ_low); - } else { - // refinement scan for DC coefficient - if (stbi__jpeg_get_bit(j)) - data[0] += (short) (1 << j->succ_low); - } - return 1; -} - -// @OPTIMIZE: store non-zigzagged during the decode passes, -// and only de-zigzag when dequantizing -static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__huffman *hac, stbi__int16 *fac) -{ - int k; - if (j->spec_start == 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); - - if (j->succ_high == 0) { - int shift = j->succ_low; - - if (j->eob_run) { - --j->eob_run; - return 1; - } - - k = j->spec_start; - do { - unsigned int zig; - int c,r,s; - if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); - c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); - r = fac[c]; - if (r) { // fast-AC path - k += (r >> 4) & 15; // run - s = r & 15; // combined length - j->code_buffer <<= s; - j->code_bits -= s; - zig = stbi__jpeg_dezigzag[k++]; - data[zig] = (short) ((r >> 8) << shift); - } else { - int rs = stbi__jpeg_huff_decode(j, hac); - if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); - s = rs & 15; - r = rs >> 4; - if (s == 0) { - if (r < 15) { - j->eob_run = (1 << r); - if (r) - j->eob_run += stbi__jpeg_get_bits(j, r); - --j->eob_run; - break; - } - k += 16; - } else { - k += r; - zig = stbi__jpeg_dezigzag[k++]; - data[zig] = (short) (stbi__extend_receive(j,s) << shift); - } - } - } while (k <= j->spec_end); - } else { - // refinement scan for these AC coefficients - - short bit = (short) (1 << j->succ_low); - - if (j->eob_run) { - --j->eob_run; - for (k = j->spec_start; k <= j->spec_end; ++k) { - short *p = &data[stbi__jpeg_dezigzag[k]]; - if (*p != 0) - if (stbi__jpeg_get_bit(j)) - if ((*p & bit)==0) { - if (*p > 0) - *p += bit; - else - *p -= bit; - } - } - } else { - k = j->spec_start; - do { - int r,s; - int rs = stbi__jpeg_huff_decode(j, hac); // @OPTIMIZE see if we can use the fast path here, advance-by-r is so slow, eh - if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); - s = rs & 15; - r = rs >> 4; - if (s == 0) { - if (r < 15) { - j->eob_run = (1 << r) - 1; - if (r) - j->eob_run += stbi__jpeg_get_bits(j, r); - r = 64; // force end of block - } else { - // r=15 s=0 should write 16 0s, so we just do - // a run of 15 0s and then write s (which is 0), - // so we don't have to do anything special here - } - } else { - if (s != 1) return stbi__err("bad huffman code", "Corrupt JPEG"); - // sign bit - if (stbi__jpeg_get_bit(j)) - s = bit; - else - s = -bit; - } - - // advance by r - while (k <= j->spec_end) { - short *p = &data[stbi__jpeg_dezigzag[k++]]; - if (*p != 0) { - if (stbi__jpeg_get_bit(j)) - if ((*p & bit)==0) { - if (*p > 0) - *p += bit; - else - *p -= bit; - } - } else { - if (r == 0) { - *p = (short) s; - break; - } - --r; - } - } - } while (k <= j->spec_end); - } - } - return 1; -} - -// take a -128..127 value and stbi__clamp it and convert to 0..255 -stbi_inline static stbi_uc stbi__clamp(int x) -{ - // trick to use a single test to catch both cases - if ((unsigned int) x > 255) { - if (x < 0) return 0; - if (x > 255) return 255; - } - return (stbi_uc) x; -} - -#define stbi__f2f(x) ((int) (((x) * 4096 + 0.5))) -#define stbi__fsh(x) ((x) * 4096) - -// derived from jidctint -- DCT_ISLOW -#define STBI__IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \ - int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \ - p2 = s2; \ - p3 = s6; \ - p1 = (p2+p3) * stbi__f2f(0.5411961f); \ - t2 = p1 + p3*stbi__f2f(-1.847759065f); \ - t3 = p1 + p2*stbi__f2f( 0.765366865f); \ - p2 = s0; \ - p3 = s4; \ - t0 = stbi__fsh(p2+p3); \ - t1 = stbi__fsh(p2-p3); \ - x0 = t0+t3; \ - x3 = t0-t3; \ - x1 = t1+t2; \ - x2 = t1-t2; \ - t0 = s7; \ - t1 = s5; \ - t2 = s3; \ - t3 = s1; \ - p3 = t0+t2; \ - p4 = t1+t3; \ - p1 = t0+t3; \ - p2 = t1+t2; \ - p5 = (p3+p4)*stbi__f2f( 1.175875602f); \ - t0 = t0*stbi__f2f( 0.298631336f); \ - t1 = t1*stbi__f2f( 2.053119869f); \ - t2 = t2*stbi__f2f( 3.072711026f); \ - t3 = t3*stbi__f2f( 1.501321110f); \ - p1 = p5 + p1*stbi__f2f(-0.899976223f); \ - p2 = p5 + p2*stbi__f2f(-2.562915447f); \ - p3 = p3*stbi__f2f(-1.961570560f); \ - p4 = p4*stbi__f2f(-0.390180644f); \ - t3 += p1+p4; \ - t2 += p2+p3; \ - t1 += p2+p4; \ - t0 += p1+p3; - -static void stbi__idct_block(stbi_uc *out, int out_stride, short data[64]) -{ - int i,val[64],*v=val; - stbi_uc *o; - short *d = data; - - // columns - for (i=0; i < 8; ++i,++d, ++v) { - // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing - if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0 - && d[40]==0 && d[48]==0 && d[56]==0) { - // no shortcut 0 seconds - // (1|2|3|4|5|6|7)==0 0 seconds - // all separate -0.047 seconds - // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds - int dcterm = d[0]*4; - v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm; - } else { - STBI__IDCT_1D(d[ 0],d[ 8],d[16],d[24],d[32],d[40],d[48],d[56]) - // constants scaled things up by 1<<12; let's bring them back - // down, but keep 2 extra bits of precision - x0 += 512; x1 += 512; x2 += 512; x3 += 512; - v[ 0] = (x0+t3) >> 10; - v[56] = (x0-t3) >> 10; - v[ 8] = (x1+t2) >> 10; - v[48] = (x1-t2) >> 10; - v[16] = (x2+t1) >> 10; - v[40] = (x2-t1) >> 10; - v[24] = (x3+t0) >> 10; - v[32] = (x3-t0) >> 10; - } - } - - for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) { - // no fast case since the first 1D IDCT spread components out - STBI__IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7]) - // constants scaled things up by 1<<12, plus we had 1<<2 from first - // loop, plus horizontal and vertical each scale by sqrt(8) so together - // we've got an extra 1<<3, so 1<<17 total we need to remove. - // so we want to round that, which means adding 0.5 * 1<<17, - // aka 65536. Also, we'll end up with -128 to 127 that we want - // to encode as 0..255 by adding 128, so we'll add that before the shift - x0 += 65536 + (128<<17); - x1 += 65536 + (128<<17); - x2 += 65536 + (128<<17); - x3 += 65536 + (128<<17); - // tried computing the shifts into temps, or'ing the temps to see - // if any were out of range, but that was slower - o[0] = stbi__clamp((x0+t3) >> 17); - o[7] = stbi__clamp((x0-t3) >> 17); - o[1] = stbi__clamp((x1+t2) >> 17); - o[6] = stbi__clamp((x1-t2) >> 17); - o[2] = stbi__clamp((x2+t1) >> 17); - o[5] = stbi__clamp((x2-t1) >> 17); - o[3] = stbi__clamp((x3+t0) >> 17); - o[4] = stbi__clamp((x3-t0) >> 17); - } -} - -#ifdef STBI_SSE2 -// sse2 integer IDCT. not the fastest possible implementation but it -// produces bit-identical results to the generic C version so it's -// fully "transparent". -static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) -{ - // This is constructed to match our regular (generic) integer IDCT exactly. - __m128i row0, row1, row2, row3, row4, row5, row6, row7; - __m128i tmp; - - // dot product constant: even elems=x, odd elems=y - #define dct_const(x,y) _mm_setr_epi16((x),(y),(x),(y),(x),(y),(x),(y)) - - // out(0) = c0[even]*x + c0[odd]*y (c0, x, y 16-bit, out 32-bit) - // out(1) = c1[even]*x + c1[odd]*y - #define dct_rot(out0,out1, x,y,c0,c1) \ - __m128i c0##lo = _mm_unpacklo_epi16((x),(y)); \ - __m128i c0##hi = _mm_unpackhi_epi16((x),(y)); \ - __m128i out0##_l = _mm_madd_epi16(c0##lo, c0); \ - __m128i out0##_h = _mm_madd_epi16(c0##hi, c0); \ - __m128i out1##_l = _mm_madd_epi16(c0##lo, c1); \ - __m128i out1##_h = _mm_madd_epi16(c0##hi, c1) - - // out = in << 12 (in 16-bit, out 32-bit) - #define dct_widen(out, in) \ - __m128i out##_l = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), (in)), 4); \ - __m128i out##_h = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), (in)), 4) - - // wide add - #define dct_wadd(out, a, b) \ - __m128i out##_l = _mm_add_epi32(a##_l, b##_l); \ - __m128i out##_h = _mm_add_epi32(a##_h, b##_h) - - // wide sub - #define dct_wsub(out, a, b) \ - __m128i out##_l = _mm_sub_epi32(a##_l, b##_l); \ - __m128i out##_h = _mm_sub_epi32(a##_h, b##_h) - - // butterfly a/b, add bias, then shift by "s" and pack - #define dct_bfly32o(out0, out1, a,b,bias,s) \ - { \ - __m128i abiased_l = _mm_add_epi32(a##_l, bias); \ - __m128i abiased_h = _mm_add_epi32(a##_h, bias); \ - dct_wadd(sum, abiased, b); \ - dct_wsub(dif, abiased, b); \ - out0 = _mm_packs_epi32(_mm_srai_epi32(sum_l, s), _mm_srai_epi32(sum_h, s)); \ - out1 = _mm_packs_epi32(_mm_srai_epi32(dif_l, s), _mm_srai_epi32(dif_h, s)); \ - } - - // 8-bit interleave step (for transposes) - #define dct_interleave8(a, b) \ - tmp = a; \ - a = _mm_unpacklo_epi8(a, b); \ - b = _mm_unpackhi_epi8(tmp, b) - - // 16-bit interleave step (for transposes) - #define dct_interleave16(a, b) \ - tmp = a; \ - a = _mm_unpacklo_epi16(a, b); \ - b = _mm_unpackhi_epi16(tmp, b) - - #define dct_pass(bias,shift) \ - { \ - /* even part */ \ - dct_rot(t2e,t3e, row2,row6, rot0_0,rot0_1); \ - __m128i sum04 = _mm_add_epi16(row0, row4); \ - __m128i dif04 = _mm_sub_epi16(row0, row4); \ - dct_widen(t0e, sum04); \ - dct_widen(t1e, dif04); \ - dct_wadd(x0, t0e, t3e); \ - dct_wsub(x3, t0e, t3e); \ - dct_wadd(x1, t1e, t2e); \ - dct_wsub(x2, t1e, t2e); \ - /* odd part */ \ - dct_rot(y0o,y2o, row7,row3, rot2_0,rot2_1); \ - dct_rot(y1o,y3o, row5,row1, rot3_0,rot3_1); \ - __m128i sum17 = _mm_add_epi16(row1, row7); \ - __m128i sum35 = _mm_add_epi16(row3, row5); \ - dct_rot(y4o,y5o, sum17,sum35, rot1_0,rot1_1); \ - dct_wadd(x4, y0o, y4o); \ - dct_wadd(x5, y1o, y5o); \ - dct_wadd(x6, y2o, y5o); \ - dct_wadd(x7, y3o, y4o); \ - dct_bfly32o(row0,row7, x0,x7,bias,shift); \ - dct_bfly32o(row1,row6, x1,x6,bias,shift); \ - dct_bfly32o(row2,row5, x2,x5,bias,shift); \ - dct_bfly32o(row3,row4, x3,x4,bias,shift); \ - } - - __m128i rot0_0 = dct_const(stbi__f2f(0.5411961f), stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f)); - __m128i rot0_1 = dct_const(stbi__f2f(0.5411961f) + stbi__f2f( 0.765366865f), stbi__f2f(0.5411961f)); - __m128i rot1_0 = dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f), stbi__f2f(1.175875602f)); - __m128i rot1_1 = dct_const(stbi__f2f(1.175875602f), stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f)); - __m128i rot2_0 = dct_const(stbi__f2f(-1.961570560f) + stbi__f2f( 0.298631336f), stbi__f2f(-1.961570560f)); - __m128i rot2_1 = dct_const(stbi__f2f(-1.961570560f), stbi__f2f(-1.961570560f) + stbi__f2f( 3.072711026f)); - __m128i rot3_0 = dct_const(stbi__f2f(-0.390180644f) + stbi__f2f( 2.053119869f), stbi__f2f(-0.390180644f)); - __m128i rot3_1 = dct_const(stbi__f2f(-0.390180644f), stbi__f2f(-0.390180644f) + stbi__f2f( 1.501321110f)); - - // rounding biases in column/row passes, see stbi__idct_block for explanation. - __m128i bias_0 = _mm_set1_epi32(512); - __m128i bias_1 = _mm_set1_epi32(65536 + (128<<17)); - - // load - row0 = _mm_load_si128((const __m128i *) (data + 0*8)); - row1 = _mm_load_si128((const __m128i *) (data + 1*8)); - row2 = _mm_load_si128((const __m128i *) (data + 2*8)); - row3 = _mm_load_si128((const __m128i *) (data + 3*8)); - row4 = _mm_load_si128((const __m128i *) (data + 4*8)); - row5 = _mm_load_si128((const __m128i *) (data + 5*8)); - row6 = _mm_load_si128((const __m128i *) (data + 6*8)); - row7 = _mm_load_si128((const __m128i *) (data + 7*8)); - - // column pass - dct_pass(bias_0, 10); - - { - // 16bit 8x8 transpose pass 1 - dct_interleave16(row0, row4); - dct_interleave16(row1, row5); - dct_interleave16(row2, row6); - dct_interleave16(row3, row7); - - // transpose pass 2 - dct_interleave16(row0, row2); - dct_interleave16(row1, row3); - dct_interleave16(row4, row6); - dct_interleave16(row5, row7); - - // transpose pass 3 - dct_interleave16(row0, row1); - dct_interleave16(row2, row3); - dct_interleave16(row4, row5); - dct_interleave16(row6, row7); - } - - // row pass - dct_pass(bias_1, 17); - - { - // pack - __m128i p0 = _mm_packus_epi16(row0, row1); // a0a1a2a3...a7b0b1b2b3...b7 - __m128i p1 = _mm_packus_epi16(row2, row3); - __m128i p2 = _mm_packus_epi16(row4, row5); - __m128i p3 = _mm_packus_epi16(row6, row7); - - // 8bit 8x8 transpose pass 1 - dct_interleave8(p0, p2); // a0e0a1e1... - dct_interleave8(p1, p3); // c0g0c1g1... - - // transpose pass 2 - dct_interleave8(p0, p1); // a0c0e0g0... - dct_interleave8(p2, p3); // b0d0f0h0... - - // transpose pass 3 - dct_interleave8(p0, p2); // a0b0c0d0... - dct_interleave8(p1, p3); // a4b4c4d4... - - // store - _mm_storel_epi64((__m128i *) out, p0); out += out_stride; - _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p0, 0x4e)); out += out_stride; - _mm_storel_epi64((__m128i *) out, p2); out += out_stride; - _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p2, 0x4e)); out += out_stride; - _mm_storel_epi64((__m128i *) out, p1); out += out_stride; - _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p1, 0x4e)); out += out_stride; - _mm_storel_epi64((__m128i *) out, p3); out += out_stride; - _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p3, 0x4e)); - } - -#undef dct_const -#undef dct_rot -#undef dct_widen -#undef dct_wadd -#undef dct_wsub -#undef dct_bfly32o -#undef dct_interleave8 -#undef dct_interleave16 -#undef dct_pass -} - -#endif // STBI_SSE2 - -#ifdef STBI_NEON - -// NEON integer IDCT. should produce bit-identical -// results to the generic C version. -static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) -{ - int16x8_t row0, row1, row2, row3, row4, row5, row6, row7; - - int16x4_t rot0_0 = vdup_n_s16(stbi__f2f(0.5411961f)); - int16x4_t rot0_1 = vdup_n_s16(stbi__f2f(-1.847759065f)); - int16x4_t rot0_2 = vdup_n_s16(stbi__f2f( 0.765366865f)); - int16x4_t rot1_0 = vdup_n_s16(stbi__f2f( 1.175875602f)); - int16x4_t rot1_1 = vdup_n_s16(stbi__f2f(-0.899976223f)); - int16x4_t rot1_2 = vdup_n_s16(stbi__f2f(-2.562915447f)); - int16x4_t rot2_0 = vdup_n_s16(stbi__f2f(-1.961570560f)); - int16x4_t rot2_1 = vdup_n_s16(stbi__f2f(-0.390180644f)); - int16x4_t rot3_0 = vdup_n_s16(stbi__f2f( 0.298631336f)); - int16x4_t rot3_1 = vdup_n_s16(stbi__f2f( 2.053119869f)); - int16x4_t rot3_2 = vdup_n_s16(stbi__f2f( 3.072711026f)); - int16x4_t rot3_3 = vdup_n_s16(stbi__f2f( 1.501321110f)); - -#define dct_long_mul(out, inq, coeff) \ - int32x4_t out##_l = vmull_s16(vget_low_s16(inq), coeff); \ - int32x4_t out##_h = vmull_s16(vget_high_s16(inq), coeff) - -#define dct_long_mac(out, acc, inq, coeff) \ - int32x4_t out##_l = vmlal_s16(acc##_l, vget_low_s16(inq), coeff); \ - int32x4_t out##_h = vmlal_s16(acc##_h, vget_high_s16(inq), coeff) - -#define dct_widen(out, inq) \ - int32x4_t out##_l = vshll_n_s16(vget_low_s16(inq), 12); \ - int32x4_t out##_h = vshll_n_s16(vget_high_s16(inq), 12) - -// wide add -#define dct_wadd(out, a, b) \ - int32x4_t out##_l = vaddq_s32(a##_l, b##_l); \ - int32x4_t out##_h = vaddq_s32(a##_h, b##_h) - -// wide sub -#define dct_wsub(out, a, b) \ - int32x4_t out##_l = vsubq_s32(a##_l, b##_l); \ - int32x4_t out##_h = vsubq_s32(a##_h, b##_h) - -// butterfly a/b, then shift using "shiftop" by "s" and pack -#define dct_bfly32o(out0,out1, a,b,shiftop,s) \ - { \ - dct_wadd(sum, a, b); \ - dct_wsub(dif, a, b); \ - out0 = vcombine_s16(shiftop(sum_l, s), shiftop(sum_h, s)); \ - out1 = vcombine_s16(shiftop(dif_l, s), shiftop(dif_h, s)); \ - } - -#define dct_pass(shiftop, shift) \ - { \ - /* even part */ \ - int16x8_t sum26 = vaddq_s16(row2, row6); \ - dct_long_mul(p1e, sum26, rot0_0); \ - dct_long_mac(t2e, p1e, row6, rot0_1); \ - dct_long_mac(t3e, p1e, row2, rot0_2); \ - int16x8_t sum04 = vaddq_s16(row0, row4); \ - int16x8_t dif04 = vsubq_s16(row0, row4); \ - dct_widen(t0e, sum04); \ - dct_widen(t1e, dif04); \ - dct_wadd(x0, t0e, t3e); \ - dct_wsub(x3, t0e, t3e); \ - dct_wadd(x1, t1e, t2e); \ - dct_wsub(x2, t1e, t2e); \ - /* odd part */ \ - int16x8_t sum15 = vaddq_s16(row1, row5); \ - int16x8_t sum17 = vaddq_s16(row1, row7); \ - int16x8_t sum35 = vaddq_s16(row3, row5); \ - int16x8_t sum37 = vaddq_s16(row3, row7); \ - int16x8_t sumodd = vaddq_s16(sum17, sum35); \ - dct_long_mul(p5o, sumodd, rot1_0); \ - dct_long_mac(p1o, p5o, sum17, rot1_1); \ - dct_long_mac(p2o, p5o, sum35, rot1_2); \ - dct_long_mul(p3o, sum37, rot2_0); \ - dct_long_mul(p4o, sum15, rot2_1); \ - dct_wadd(sump13o, p1o, p3o); \ - dct_wadd(sump24o, p2o, p4o); \ - dct_wadd(sump23o, p2o, p3o); \ - dct_wadd(sump14o, p1o, p4o); \ - dct_long_mac(x4, sump13o, row7, rot3_0); \ - dct_long_mac(x5, sump24o, row5, rot3_1); \ - dct_long_mac(x6, sump23o, row3, rot3_2); \ - dct_long_mac(x7, sump14o, row1, rot3_3); \ - dct_bfly32o(row0,row7, x0,x7,shiftop,shift); \ - dct_bfly32o(row1,row6, x1,x6,shiftop,shift); \ - dct_bfly32o(row2,row5, x2,x5,shiftop,shift); \ - dct_bfly32o(row3,row4, x3,x4,shiftop,shift); \ - } - - // load - row0 = vld1q_s16(data + 0*8); - row1 = vld1q_s16(data + 1*8); - row2 = vld1q_s16(data + 2*8); - row3 = vld1q_s16(data + 3*8); - row4 = vld1q_s16(data + 4*8); - row5 = vld1q_s16(data + 5*8); - row6 = vld1q_s16(data + 6*8); - row7 = vld1q_s16(data + 7*8); - - // add DC bias - row0 = vaddq_s16(row0, vsetq_lane_s16(1024, vdupq_n_s16(0), 0)); - - // column pass - dct_pass(vrshrn_n_s32, 10); - - // 16bit 8x8 transpose - { -// these three map to a single VTRN.16, VTRN.32, and VSWP, respectively. -// whether compilers actually get this is another story, sadly. -#define dct_trn16(x, y) { int16x8x2_t t = vtrnq_s16(x, y); x = t.val[0]; y = t.val[1]; } -#define dct_trn32(x, y) { int32x4x2_t t = vtrnq_s32(vreinterpretq_s32_s16(x), vreinterpretq_s32_s16(y)); x = vreinterpretq_s16_s32(t.val[0]); y = vreinterpretq_s16_s32(t.val[1]); } -#define dct_trn64(x, y) { int16x8_t x0 = x; int16x8_t y0 = y; x = vcombine_s16(vget_low_s16(x0), vget_low_s16(y0)); y = vcombine_s16(vget_high_s16(x0), vget_high_s16(y0)); } - - // pass 1 - dct_trn16(row0, row1); // a0b0a2b2a4b4a6b6 - dct_trn16(row2, row3); - dct_trn16(row4, row5); - dct_trn16(row6, row7); - - // pass 2 - dct_trn32(row0, row2); // a0b0c0d0a4b4c4d4 - dct_trn32(row1, row3); - dct_trn32(row4, row6); - dct_trn32(row5, row7); - - // pass 3 - dct_trn64(row0, row4); // a0b0c0d0e0f0g0h0 - dct_trn64(row1, row5); - dct_trn64(row2, row6); - dct_trn64(row3, row7); - -#undef dct_trn16 -#undef dct_trn32 -#undef dct_trn64 - } - - // row pass - // vrshrn_n_s32 only supports shifts up to 16, we need - // 17. so do a non-rounding shift of 16 first then follow - // up with a rounding shift by 1. - dct_pass(vshrn_n_s32, 16); - - { - // pack and round - uint8x8_t p0 = vqrshrun_n_s16(row0, 1); - uint8x8_t p1 = vqrshrun_n_s16(row1, 1); - uint8x8_t p2 = vqrshrun_n_s16(row2, 1); - uint8x8_t p3 = vqrshrun_n_s16(row3, 1); - uint8x8_t p4 = vqrshrun_n_s16(row4, 1); - uint8x8_t p5 = vqrshrun_n_s16(row5, 1); - uint8x8_t p6 = vqrshrun_n_s16(row6, 1); - uint8x8_t p7 = vqrshrun_n_s16(row7, 1); - - // again, these can translate into one instruction, but often don't. -#define dct_trn8_8(x, y) { uint8x8x2_t t = vtrn_u8(x, y); x = t.val[0]; y = t.val[1]; } -#define dct_trn8_16(x, y) { uint16x4x2_t t = vtrn_u16(vreinterpret_u16_u8(x), vreinterpret_u16_u8(y)); x = vreinterpret_u8_u16(t.val[0]); y = vreinterpret_u8_u16(t.val[1]); } -#define dct_trn8_32(x, y) { uint32x2x2_t t = vtrn_u32(vreinterpret_u32_u8(x), vreinterpret_u32_u8(y)); x = vreinterpret_u8_u32(t.val[0]); y = vreinterpret_u8_u32(t.val[1]); } - - // sadly can't use interleaved stores here since we only write - // 8 bytes to each scan line! - - // 8x8 8-bit transpose pass 1 - dct_trn8_8(p0, p1); - dct_trn8_8(p2, p3); - dct_trn8_8(p4, p5); - dct_trn8_8(p6, p7); - - // pass 2 - dct_trn8_16(p0, p2); - dct_trn8_16(p1, p3); - dct_trn8_16(p4, p6); - dct_trn8_16(p5, p7); - - // pass 3 - dct_trn8_32(p0, p4); - dct_trn8_32(p1, p5); - dct_trn8_32(p2, p6); - dct_trn8_32(p3, p7); - - // store - vst1_u8(out, p0); out += out_stride; - vst1_u8(out, p1); out += out_stride; - vst1_u8(out, p2); out += out_stride; - vst1_u8(out, p3); out += out_stride; - vst1_u8(out, p4); out += out_stride; - vst1_u8(out, p5); out += out_stride; - vst1_u8(out, p6); out += out_stride; - vst1_u8(out, p7); - -#undef dct_trn8_8 -#undef dct_trn8_16 -#undef dct_trn8_32 - } - -#undef dct_long_mul -#undef dct_long_mac -#undef dct_widen -#undef dct_wadd -#undef dct_wsub -#undef dct_bfly32o -#undef dct_pass -} - -#endif // STBI_NEON - -#define STBI__MARKER_none 0xff -// if there's a pending marker from the entropy stream, return that -// otherwise, fetch from the stream and get a marker. if there's no -// marker, return 0xff, which is never a valid marker value -static stbi_uc stbi__get_marker(stbi__jpeg *j) -{ - stbi_uc x; - if (j->marker != STBI__MARKER_none) { x = j->marker; j->marker = STBI__MARKER_none; return x; } - x = stbi__get8(j->s); - if (x != 0xff) return STBI__MARKER_none; - while (x == 0xff) - x = stbi__get8(j->s); // consume repeated 0xff fill bytes - return x; -} - -// in each scan, we'll have scan_n components, and the order -// of the components is specified by order[] -#define STBI__RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7) - -// after a restart interval, stbi__jpeg_reset the entropy decoder and -// the dc prediction -static void stbi__jpeg_reset(stbi__jpeg *j) -{ - j->code_bits = 0; - j->code_buffer = 0; - j->nomore = 0; - j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = j->img_comp[3].dc_pred = 0; - j->marker = STBI__MARKER_none; - j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff; - j->eob_run = 0; - // no more than 1<<31 MCUs if no restart_interal? that's plenty safe, - // since we don't even allow 1<<30 pixels -} - -static int stbi__parse_entropy_coded_data(stbi__jpeg *z) -{ - stbi__jpeg_reset(z); - if (!z->progressive) { - if (z->scan_n == 1) { - int i,j; - STBI_SIMD_ALIGN(short, data[64]); - int n = z->order[0]; - // non-interleaved data, we just need to process one block at a time, - // in trivial scanline order - // number of blocks to do just depends on how many actual "pixels" this - // component has, independent of interleaved MCU blocking and such - int w = (z->img_comp[n].x+7) >> 3; - int h = (z->img_comp[n].y+7) >> 3; - for (j=0; j < h; ++j) { - for (i=0; i < w; ++i) { - int ha = z->img_comp[n].ha; - if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; - z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); - // every data block is an MCU, so countdown the restart interval - if (--z->todo <= 0) { - if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); - // if it's NOT a restart, then just bail, so we get corrupt data - // rather than no data - if (!STBI__RESTART(z->marker)) return 1; - stbi__jpeg_reset(z); - } - } - } - return 1; - } else { // interleaved - int i,j,k,x,y; - STBI_SIMD_ALIGN(short, data[64]); - for (j=0; j < z->img_mcu_y; ++j) { - for (i=0; i < z->img_mcu_x; ++i) { - // scan an interleaved mcu... process scan_n components in order - for (k=0; k < z->scan_n; ++k) { - int n = z->order[k]; - // scan out an mcu's worth of this component; that's just determined - // by the basic H and V specified for the component - for (y=0; y < z->img_comp[n].v; ++y) { - for (x=0; x < z->img_comp[n].h; ++x) { - int x2 = (i*z->img_comp[n].h + x)*8; - int y2 = (j*z->img_comp[n].v + y)*8; - int ha = z->img_comp[n].ha; - if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; - z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data); - } - } - } - // after all interleaved components, that's an interleaved MCU, - // so now count down the restart interval - if (--z->todo <= 0) { - if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); - if (!STBI__RESTART(z->marker)) return 1; - stbi__jpeg_reset(z); - } - } - } - return 1; - } - } else { - if (z->scan_n == 1) { - int i,j; - int n = z->order[0]; - // non-interleaved data, we just need to process one block at a time, - // in trivial scanline order - // number of blocks to do just depends on how many actual "pixels" this - // component has, independent of interleaved MCU blocking and such - int w = (z->img_comp[n].x+7) >> 3; - int h = (z->img_comp[n].y+7) >> 3; - for (j=0; j < h; ++j) { - for (i=0; i < w; ++i) { - short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); - if (z->spec_start == 0) { - if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) - return 0; - } else { - int ha = z->img_comp[n].ha; - if (!stbi__jpeg_decode_block_prog_ac(z, data, &z->huff_ac[ha], z->fast_ac[ha])) - return 0; - } - // every data block is an MCU, so countdown the restart interval - if (--z->todo <= 0) { - if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); - if (!STBI__RESTART(z->marker)) return 1; - stbi__jpeg_reset(z); - } - } - } - return 1; - } else { // interleaved - int i,j,k,x,y; - for (j=0; j < z->img_mcu_y; ++j) { - for (i=0; i < z->img_mcu_x; ++i) { - // scan an interleaved mcu... process scan_n components in order - for (k=0; k < z->scan_n; ++k) { - int n = z->order[k]; - // scan out an mcu's worth of this component; that's just determined - // by the basic H and V specified for the component - for (y=0; y < z->img_comp[n].v; ++y) { - for (x=0; x < z->img_comp[n].h; ++x) { - int x2 = (i*z->img_comp[n].h + x); - int y2 = (j*z->img_comp[n].v + y); - short *data = z->img_comp[n].coeff + 64 * (x2 + y2 * z->img_comp[n].coeff_w); - if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) - return 0; - } - } - } - // after all interleaved components, that's an interleaved MCU, - // so now count down the restart interval - if (--z->todo <= 0) { - if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); - if (!STBI__RESTART(z->marker)) return 1; - stbi__jpeg_reset(z); - } - } - } - return 1; - } - } -} - -static void stbi__jpeg_dequantize(short *data, stbi__uint16 *dequant) -{ - int i; - for (i=0; i < 64; ++i) - data[i] *= dequant[i]; -} - -static void stbi__jpeg_finish(stbi__jpeg *z) -{ - if (z->progressive) { - // dequantize and idct the data - int i,j,n; - for (n=0; n < z->s->img_n; ++n) { - int w = (z->img_comp[n].x+7) >> 3; - int h = (z->img_comp[n].y+7) >> 3; - for (j=0; j < h; ++j) { - for (i=0; i < w; ++i) { - short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); - stbi__jpeg_dequantize(data, z->dequant[z->img_comp[n].tq]); - z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); - } - } - } - } -} - -static int stbi__process_marker(stbi__jpeg *z, int m) -{ - int L; - switch (m) { - case STBI__MARKER_none: // no marker found - return stbi__err("expected marker","Corrupt JPEG"); - - case 0xDD: // DRI - specify restart interval - if (stbi__get16be(z->s) != 4) return stbi__err("bad DRI len","Corrupt JPEG"); - z->restart_interval = stbi__get16be(z->s); - return 1; - - case 0xDB: // DQT - define quantization table - L = stbi__get16be(z->s)-2; - while (L > 0) { - int q = stbi__get8(z->s); - int p = q >> 4, sixteen = (p != 0); - int t = q & 15,i; - if (p != 0 && p != 1) return stbi__err("bad DQT type","Corrupt JPEG"); - if (t > 3) return stbi__err("bad DQT table","Corrupt JPEG"); - - for (i=0; i < 64; ++i) - z->dequant[t][stbi__jpeg_dezigzag[i]] = (stbi__uint16)(sixteen ? stbi__get16be(z->s) : stbi__get8(z->s)); - L -= (sixteen ? 129 : 65); - } - return L==0; - - case 0xC4: // DHT - define huffman table - L = stbi__get16be(z->s)-2; - while (L > 0) { - stbi_uc *v; - int sizes[16],i,n=0; - int q = stbi__get8(z->s); - int tc = q >> 4; - int th = q & 15; - if (tc > 1 || th > 3) return stbi__err("bad DHT header","Corrupt JPEG"); - for (i=0; i < 16; ++i) { - sizes[i] = stbi__get8(z->s); - n += sizes[i]; - } - L -= 17; - if (tc == 0) { - if (!stbi__build_huffman(z->huff_dc+th, sizes)) return 0; - v = z->huff_dc[th].values; - } else { - if (!stbi__build_huffman(z->huff_ac+th, sizes)) return 0; - v = z->huff_ac[th].values; - } - for (i=0; i < n; ++i) - v[i] = stbi__get8(z->s); - if (tc != 0) - stbi__build_fast_ac(z->fast_ac[th], z->huff_ac + th); - L -= n; - } - return L==0; - } - - // check for comment block or APP blocks - if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) { - L = stbi__get16be(z->s); - if (L < 2) { - if (m == 0xFE) - return stbi__err("bad COM len","Corrupt JPEG"); - else - return stbi__err("bad APP len","Corrupt JPEG"); - } - L -= 2; - - if (m == 0xE0 && L >= 5) { // JFIF APP0 segment - static const unsigned char tag[5] = {'J','F','I','F','\0'}; - int ok = 1; - int i; - for (i=0; i < 5; ++i) - if (stbi__get8(z->s) != tag[i]) - ok = 0; - L -= 5; - if (ok) - z->jfif = 1; - } else if (m == 0xEE && L >= 12) { // Adobe APP14 segment - static const unsigned char tag[6] = {'A','d','o','b','e','\0'}; - int ok = 1; - int i; - for (i=0; i < 6; ++i) - if (stbi__get8(z->s) != tag[i]) - ok = 0; - L -= 6; - if (ok) { - stbi__get8(z->s); // version - stbi__get16be(z->s); // flags0 - stbi__get16be(z->s); // flags1 - z->app14_color_transform = stbi__get8(z->s); // color transform - L -= 6; - } - } - - stbi__skip(z->s, L); - return 1; - } - - return stbi__err("unknown marker","Corrupt JPEG"); -} - -// after we see SOS -static int stbi__process_scan_header(stbi__jpeg *z) -{ - int i; - int Ls = stbi__get16be(z->s); - z->scan_n = stbi__get8(z->s); - if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return stbi__err("bad SOS component count","Corrupt JPEG"); - if (Ls != 6+2*z->scan_n) return stbi__err("bad SOS len","Corrupt JPEG"); - for (i=0; i < z->scan_n; ++i) { - int id = stbi__get8(z->s), which; - int q = stbi__get8(z->s); - for (which = 0; which < z->s->img_n; ++which) - if (z->img_comp[which].id == id) - break; - if (which == z->s->img_n) return 0; // no match - z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return stbi__err("bad DC huff","Corrupt JPEG"); - z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return stbi__err("bad AC huff","Corrupt JPEG"); - z->order[i] = which; - } - - { - int aa; - z->spec_start = stbi__get8(z->s); - z->spec_end = stbi__get8(z->s); // should be 63, but might be 0 - aa = stbi__get8(z->s); - z->succ_high = (aa >> 4); - z->succ_low = (aa & 15); - if (z->progressive) { - if (z->spec_start > 63 || z->spec_end > 63 || z->spec_start > z->spec_end || z->succ_high > 13 || z->succ_low > 13) - return stbi__err("bad SOS", "Corrupt JPEG"); - } else { - if (z->spec_start != 0) return stbi__err("bad SOS","Corrupt JPEG"); - if (z->succ_high != 0 || z->succ_low != 0) return stbi__err("bad SOS","Corrupt JPEG"); - z->spec_end = 63; - } - } - - return 1; -} - -static int stbi__free_jpeg_components(stbi__jpeg *z, int ncomp, int why) -{ - int i; - for (i=0; i < ncomp; ++i) { - if (z->img_comp[i].raw_data) { - STBI_FREE(z->img_comp[i].raw_data); - z->img_comp[i].raw_data = NULL; - z->img_comp[i].data = NULL; - } - if (z->img_comp[i].raw_coeff) { - STBI_FREE(z->img_comp[i].raw_coeff); - z->img_comp[i].raw_coeff = 0; - z->img_comp[i].coeff = 0; - } - if (z->img_comp[i].linebuf) { - STBI_FREE(z->img_comp[i].linebuf); - z->img_comp[i].linebuf = NULL; - } - } - return why; -} - -static int stbi__process_frame_header(stbi__jpeg *z, int scan) -{ - stbi__context *s = z->s; - int Lf,p,i,q, h_max=1,v_max=1,c; - Lf = stbi__get16be(s); if (Lf < 11) return stbi__err("bad SOF len","Corrupt JPEG"); // JPEG - p = stbi__get8(s); if (p != 8) return stbi__err("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline - s->img_y = stbi__get16be(s); if (s->img_y == 0) return stbi__err("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG - s->img_x = stbi__get16be(s); if (s->img_x == 0) return stbi__err("0 width","Corrupt JPEG"); // JPEG requires - if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); - if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); - c = stbi__get8(s); - if (c != 3 && c != 1 && c != 4) return stbi__err("bad component count","Corrupt JPEG"); - s->img_n = c; - for (i=0; i < c; ++i) { - z->img_comp[i].data = NULL; - z->img_comp[i].linebuf = NULL; - } - - if (Lf != 8+3*s->img_n) return stbi__err("bad SOF len","Corrupt JPEG"); - - z->rgb = 0; - for (i=0; i < s->img_n; ++i) { - static const unsigned char rgb[3] = { 'R', 'G', 'B' }; - z->img_comp[i].id = stbi__get8(s); - if (s->img_n == 3 && z->img_comp[i].id == rgb[i]) - ++z->rgb; - q = stbi__get8(s); - z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return stbi__err("bad H","Corrupt JPEG"); - z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return stbi__err("bad V","Corrupt JPEG"); - z->img_comp[i].tq = stbi__get8(s); if (z->img_comp[i].tq > 3) return stbi__err("bad TQ","Corrupt JPEG"); - } - - if (scan != STBI__SCAN_load) return 1; - - if (!stbi__mad3sizes_valid(s->img_x, s->img_y, s->img_n, 0)) return stbi__err("too large", "Image too large to decode"); - - for (i=0; i < s->img_n; ++i) { - if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h; - if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v; - } - - // compute interleaved mcu info - z->img_h_max = h_max; - z->img_v_max = v_max; - z->img_mcu_w = h_max * 8; - z->img_mcu_h = v_max * 8; - // these sizes can't be more than 17 bits - z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w; - z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h; - - for (i=0; i < s->img_n; ++i) { - // number of effective pixels (e.g. for non-interleaved MCU) - z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max; - z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max; - // to simplify generation, we'll allocate enough memory to decode - // the bogus oversized data from using interleaved MCUs and their - // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't - // discard the extra data until colorspace conversion - // - // img_mcu_x, img_mcu_y: <=17 bits; comp[i].h and .v are <=4 (checked earlier) - // so these muls can't overflow with 32-bit ints (which we require) - z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8; - z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8; - z->img_comp[i].coeff = 0; - z->img_comp[i].raw_coeff = 0; - z->img_comp[i].linebuf = NULL; - z->img_comp[i].raw_data = stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15); - if (z->img_comp[i].raw_data == NULL) - return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory")); - // align blocks for idct using mmx/sse - z->img_comp[i].data = (stbi_uc*) (((size_t) z->img_comp[i].raw_data + 15) & ~15); - if (z->progressive) { - // w2, h2 are multiples of 8 (see above) - z->img_comp[i].coeff_w = z->img_comp[i].w2 / 8; - z->img_comp[i].coeff_h = z->img_comp[i].h2 / 8; - z->img_comp[i].raw_coeff = stbi__malloc_mad3(z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15); - if (z->img_comp[i].raw_coeff == NULL) - return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory")); - z->img_comp[i].coeff = (short*) (((size_t) z->img_comp[i].raw_coeff + 15) & ~15); - } - } - - return 1; -} - -// use comparisons since in some cases we handle more than one case (e.g. SOF) -#define stbi__DNL(x) ((x) == 0xdc) -#define stbi__SOI(x) ((x) == 0xd8) -#define stbi__EOI(x) ((x) == 0xd9) -#define stbi__SOF(x) ((x) == 0xc0 || (x) == 0xc1 || (x) == 0xc2) -#define stbi__SOS(x) ((x) == 0xda) - -#define stbi__SOF_progressive(x) ((x) == 0xc2) - -static int stbi__decode_jpeg_header(stbi__jpeg *z, int scan) -{ - int m; - z->jfif = 0; - z->app14_color_transform = -1; // valid values are 0,1,2 - z->marker = STBI__MARKER_none; // initialize cached marker to empty - m = stbi__get_marker(z); - if (!stbi__SOI(m)) return stbi__err("no SOI","Corrupt JPEG"); - if (scan == STBI__SCAN_type) return 1; - m = stbi__get_marker(z); - while (!stbi__SOF(m)) { - if (!stbi__process_marker(z,m)) return 0; - m = stbi__get_marker(z); - while (m == STBI__MARKER_none) { - // some files have extra padding after their blocks, so ok, we'll scan - if (stbi__at_eof(z->s)) return stbi__err("no SOF", "Corrupt JPEG"); - m = stbi__get_marker(z); - } - } - z->progressive = stbi__SOF_progressive(m); - if (!stbi__process_frame_header(z, scan)) return 0; - return 1; -} - -// decode image to YCbCr format -static int stbi__decode_jpeg_image(stbi__jpeg *j) -{ - int m; - for (m = 0; m < 4; m++) { - j->img_comp[m].raw_data = NULL; - j->img_comp[m].raw_coeff = NULL; - } - j->restart_interval = 0; - if (!stbi__decode_jpeg_header(j, STBI__SCAN_load)) return 0; - m = stbi__get_marker(j); - while (!stbi__EOI(m)) { - if (stbi__SOS(m)) { - if (!stbi__process_scan_header(j)) return 0; - if (!stbi__parse_entropy_coded_data(j)) return 0; - if (j->marker == STBI__MARKER_none ) { - // handle 0s at the end of image data from IP Kamera 9060 - while (!stbi__at_eof(j->s)) { - int x = stbi__get8(j->s); - if (x == 255) { - j->marker = stbi__get8(j->s); - break; - } - } - // if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 0 - } - } else if (stbi__DNL(m)) { - int Ld = stbi__get16be(j->s); - stbi__uint32 NL = stbi__get16be(j->s); - if (Ld != 4) return stbi__err("bad DNL len", "Corrupt JPEG"); - if (NL != j->s->img_y) return stbi__err("bad DNL height", "Corrupt JPEG"); - } else { - if (!stbi__process_marker(j, m)) return 0; - } - m = stbi__get_marker(j); - } - if (j->progressive) - stbi__jpeg_finish(j); - return 1; -} - -// static jfif-centered resampling (across block boundaries) - -typedef stbi_uc *(*resample_row_func)(stbi_uc *out, stbi_uc *in0, stbi_uc *in1, - int w, int hs); - -#define stbi__div4(x) ((stbi_uc) ((x) >> 2)) - -static stbi_uc *resample_row_1(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) -{ - STBI_NOTUSED(out); - STBI_NOTUSED(in_far); - STBI_NOTUSED(w); - STBI_NOTUSED(hs); - return in_near; -} - -static stbi_uc* stbi__resample_row_v_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) -{ - // need to generate two samples vertically for every one in input - int i; - STBI_NOTUSED(hs); - for (i=0; i < w; ++i) - out[i] = stbi__div4(3*in_near[i] + in_far[i] + 2); - return out; -} - -static stbi_uc* stbi__resample_row_h_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) -{ - // need to generate two samples horizontally for every one in input - int i; - stbi_uc *input = in_near; - - if (w == 1) { - // if only one sample, can't do any interpolation - out[0] = out[1] = input[0]; - return out; - } - - out[0] = input[0]; - out[1] = stbi__div4(input[0]*3 + input[1] + 2); - for (i=1; i < w-1; ++i) { - int n = 3*input[i]+2; - out[i*2+0] = stbi__div4(n+input[i-1]); - out[i*2+1] = stbi__div4(n+input[i+1]); - } - out[i*2+0] = stbi__div4(input[w-2]*3 + input[w-1] + 2); - out[i*2+1] = input[w-1]; - - STBI_NOTUSED(in_far); - STBI_NOTUSED(hs); - - return out; -} - -#define stbi__div16(x) ((stbi_uc) ((x) >> 4)) - -static stbi_uc *stbi__resample_row_hv_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) -{ - // need to generate 2x2 samples for every one in input - int i,t0,t1; - if (w == 1) { - out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); - return out; - } - - t1 = 3*in_near[0] + in_far[0]; - out[0] = stbi__div4(t1+2); - for (i=1; i < w; ++i) { - t0 = t1; - t1 = 3*in_near[i]+in_far[i]; - out[i*2-1] = stbi__div16(3*t0 + t1 + 8); - out[i*2 ] = stbi__div16(3*t1 + t0 + 8); - } - out[w*2-1] = stbi__div4(t1+2); - - STBI_NOTUSED(hs); - - return out; -} - -#if defined(STBI_SSE2) || defined(STBI_NEON) -static stbi_uc *stbi__resample_row_hv_2_simd(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) -{ - // need to generate 2x2 samples for every one in input - int i=0,t0,t1; - - if (w == 1) { - out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); - return out; - } - - t1 = 3*in_near[0] + in_far[0]; - // process groups of 8 pixels for as long as we can. - // note we can't handle the last pixel in a row in this loop - // because we need to handle the filter boundary conditions. - for (; i < ((w-1) & ~7); i += 8) { -#if defined(STBI_SSE2) - // load and perform the vertical filtering pass - // this uses 3*x + y = 4*x + (y - x) - __m128i zero = _mm_setzero_si128(); - __m128i farb = _mm_loadl_epi64((__m128i *) (in_far + i)); - __m128i nearb = _mm_loadl_epi64((__m128i *) (in_near + i)); - __m128i farw = _mm_unpacklo_epi8(farb, zero); - __m128i nearw = _mm_unpacklo_epi8(nearb, zero); - __m128i diff = _mm_sub_epi16(farw, nearw); - __m128i nears = _mm_slli_epi16(nearw, 2); - __m128i curr = _mm_add_epi16(nears, diff); // current row - - // horizontal filter works the same based on shifted vers of current - // row. "prev" is current row shifted right by 1 pixel; we need to - // insert the previous pixel value (from t1). - // "next" is current row shifted left by 1 pixel, with first pixel - // of next block of 8 pixels added in. - __m128i prv0 = _mm_slli_si128(curr, 2); - __m128i nxt0 = _mm_srli_si128(curr, 2); - __m128i prev = _mm_insert_epi16(prv0, t1, 0); - __m128i next = _mm_insert_epi16(nxt0, 3*in_near[i+8] + in_far[i+8], 7); - - // horizontal filter, polyphase implementation since it's convenient: - // even pixels = 3*cur + prev = cur*4 + (prev - cur) - // odd pixels = 3*cur + next = cur*4 + (next - cur) - // note the shared term. - __m128i bias = _mm_set1_epi16(8); - __m128i curs = _mm_slli_epi16(curr, 2); - __m128i prvd = _mm_sub_epi16(prev, curr); - __m128i nxtd = _mm_sub_epi16(next, curr); - __m128i curb = _mm_add_epi16(curs, bias); - __m128i even = _mm_add_epi16(prvd, curb); - __m128i odd = _mm_add_epi16(nxtd, curb); - - // interleave even and odd pixels, then undo scaling. - __m128i int0 = _mm_unpacklo_epi16(even, odd); - __m128i int1 = _mm_unpackhi_epi16(even, odd); - __m128i de0 = _mm_srli_epi16(int0, 4); - __m128i de1 = _mm_srli_epi16(int1, 4); - - // pack and write output - __m128i outv = _mm_packus_epi16(de0, de1); - _mm_storeu_si128((__m128i *) (out + i*2), outv); -#elif defined(STBI_NEON) - // load and perform the vertical filtering pass - // this uses 3*x + y = 4*x + (y - x) - uint8x8_t farb = vld1_u8(in_far + i); - uint8x8_t nearb = vld1_u8(in_near + i); - int16x8_t diff = vreinterpretq_s16_u16(vsubl_u8(farb, nearb)); - int16x8_t nears = vreinterpretq_s16_u16(vshll_n_u8(nearb, 2)); - int16x8_t curr = vaddq_s16(nears, diff); // current row - - // horizontal filter works the same based on shifted vers of current - // row. "prev" is current row shifted right by 1 pixel; we need to - // insert the previous pixel value (from t1). - // "next" is current row shifted left by 1 pixel, with first pixel - // of next block of 8 pixels added in. - int16x8_t prv0 = vextq_s16(curr, curr, 7); - int16x8_t nxt0 = vextq_s16(curr, curr, 1); - int16x8_t prev = vsetq_lane_s16(t1, prv0, 0); - int16x8_t next = vsetq_lane_s16(3*in_near[i+8] + in_far[i+8], nxt0, 7); - - // horizontal filter, polyphase implementation since it's convenient: - // even pixels = 3*cur + prev = cur*4 + (prev - cur) - // odd pixels = 3*cur + next = cur*4 + (next - cur) - // note the shared term. - int16x8_t curs = vshlq_n_s16(curr, 2); - int16x8_t prvd = vsubq_s16(prev, curr); - int16x8_t nxtd = vsubq_s16(next, curr); - int16x8_t even = vaddq_s16(curs, prvd); - int16x8_t odd = vaddq_s16(curs, nxtd); - - // undo scaling and round, then store with even/odd phases interleaved - uint8x8x2_t o; - o.val[0] = vqrshrun_n_s16(even, 4); - o.val[1] = vqrshrun_n_s16(odd, 4); - vst2_u8(out + i*2, o); -#endif - - // "previous" value for next iter - t1 = 3*in_near[i+7] + in_far[i+7]; - } - - t0 = t1; - t1 = 3*in_near[i] + in_far[i]; - out[i*2] = stbi__div16(3*t1 + t0 + 8); - - for (++i; i < w; ++i) { - t0 = t1; - t1 = 3*in_near[i]+in_far[i]; - out[i*2-1] = stbi__div16(3*t0 + t1 + 8); - out[i*2 ] = stbi__div16(3*t1 + t0 + 8); - } - out[w*2-1] = stbi__div4(t1+2); - - STBI_NOTUSED(hs); - - return out; -} -#endif - -static stbi_uc *stbi__resample_row_generic(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) -{ - // resample with nearest-neighbor - int i,j; - STBI_NOTUSED(in_far); - for (i=0; i < w; ++i) - for (j=0; j < hs; ++j) - out[i*hs+j] = in_near[i]; - return out; -} - -// this is a reduced-precision calculation of YCbCr-to-RGB introduced -// to make sure the code produces the same results in both SIMD and scalar -#define stbi__float2fixed(x) (((int) ((x) * 4096.0f + 0.5f)) << 8) -static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step) -{ - int i; - for (i=0; i < count; ++i) { - int y_fixed = (y[i] << 20) + (1<<19); // rounding - int r,g,b; - int cr = pcr[i] - 128; - int cb = pcb[i] - 128; - r = y_fixed + cr* stbi__float2fixed(1.40200f); - g = y_fixed + (cr*-stbi__float2fixed(0.71414f)) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); - b = y_fixed + cb* stbi__float2fixed(1.77200f); - r >>= 20; - g >>= 20; - b >>= 20; - if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } - if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } - if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } - out[0] = (stbi_uc)r; - out[1] = (stbi_uc)g; - out[2] = (stbi_uc)b; - out[3] = 255; - out += step; - } -} - -#if defined(STBI_SSE2) || defined(STBI_NEON) -static void stbi__YCbCr_to_RGB_simd(stbi_uc *out, stbi_uc const *y, stbi_uc const *pcb, stbi_uc const *pcr, int count, int step) -{ - int i = 0; - -#ifdef STBI_SSE2 - // step == 3 is pretty ugly on the final interleave, and i'm not convinced - // it's useful in practice (you wouldn't use it for textures, for example). - // so just accelerate step == 4 case. - if (step == 4) { - // this is a fairly straightforward implementation and not super-optimized. - __m128i signflip = _mm_set1_epi8(-0x80); - __m128i cr_const0 = _mm_set1_epi16( (short) ( 1.40200f*4096.0f+0.5f)); - __m128i cr_const1 = _mm_set1_epi16( - (short) ( 0.71414f*4096.0f+0.5f)); - __m128i cb_const0 = _mm_set1_epi16( - (short) ( 0.34414f*4096.0f+0.5f)); - __m128i cb_const1 = _mm_set1_epi16( (short) ( 1.77200f*4096.0f+0.5f)); - __m128i y_bias = _mm_set1_epi8((char) (unsigned char) 128); - __m128i xw = _mm_set1_epi16(255); // alpha channel - - for (; i+7 < count; i += 8) { - // load - __m128i y_bytes = _mm_loadl_epi64((__m128i *) (y+i)); - __m128i cr_bytes = _mm_loadl_epi64((__m128i *) (pcr+i)); - __m128i cb_bytes = _mm_loadl_epi64((__m128i *) (pcb+i)); - __m128i cr_biased = _mm_xor_si128(cr_bytes, signflip); // -128 - __m128i cb_biased = _mm_xor_si128(cb_bytes, signflip); // -128 - - // unpack to short (and left-shift cr, cb by 8) - __m128i yw = _mm_unpacklo_epi8(y_bias, y_bytes); - __m128i crw = _mm_unpacklo_epi8(_mm_setzero_si128(), cr_biased); - __m128i cbw = _mm_unpacklo_epi8(_mm_setzero_si128(), cb_biased); - - // color transform - __m128i yws = _mm_srli_epi16(yw, 4); - __m128i cr0 = _mm_mulhi_epi16(cr_const0, crw); - __m128i cb0 = _mm_mulhi_epi16(cb_const0, cbw); - __m128i cb1 = _mm_mulhi_epi16(cbw, cb_const1); - __m128i cr1 = _mm_mulhi_epi16(crw, cr_const1); - __m128i rws = _mm_add_epi16(cr0, yws); - __m128i gwt = _mm_add_epi16(cb0, yws); - __m128i bws = _mm_add_epi16(yws, cb1); - __m128i gws = _mm_add_epi16(gwt, cr1); - - // descale - __m128i rw = _mm_srai_epi16(rws, 4); - __m128i bw = _mm_srai_epi16(bws, 4); - __m128i gw = _mm_srai_epi16(gws, 4); - - // back to byte, set up for transpose - __m128i brb = _mm_packus_epi16(rw, bw); - __m128i gxb = _mm_packus_epi16(gw, xw); - - // transpose to interleave channels - __m128i t0 = _mm_unpacklo_epi8(brb, gxb); - __m128i t1 = _mm_unpackhi_epi8(brb, gxb); - __m128i o0 = _mm_unpacklo_epi16(t0, t1); - __m128i o1 = _mm_unpackhi_epi16(t0, t1); - - // store - _mm_storeu_si128((__m128i *) (out + 0), o0); - _mm_storeu_si128((__m128i *) (out + 16), o1); - out += 32; - } - } -#endif - -#ifdef STBI_NEON - // in this version, step=3 support would be easy to add. but is there demand? - if (step == 4) { - // this is a fairly straightforward implementation and not super-optimized. - uint8x8_t signflip = vdup_n_u8(0x80); - int16x8_t cr_const0 = vdupq_n_s16( (short) ( 1.40200f*4096.0f+0.5f)); - int16x8_t cr_const1 = vdupq_n_s16( - (short) ( 0.71414f*4096.0f+0.5f)); - int16x8_t cb_const0 = vdupq_n_s16( - (short) ( 0.34414f*4096.0f+0.5f)); - int16x8_t cb_const1 = vdupq_n_s16( (short) ( 1.77200f*4096.0f+0.5f)); - - for (; i+7 < count; i += 8) { - // load - uint8x8_t y_bytes = vld1_u8(y + i); - uint8x8_t cr_bytes = vld1_u8(pcr + i); - uint8x8_t cb_bytes = vld1_u8(pcb + i); - int8x8_t cr_biased = vreinterpret_s8_u8(vsub_u8(cr_bytes, signflip)); - int8x8_t cb_biased = vreinterpret_s8_u8(vsub_u8(cb_bytes, signflip)); - - // expand to s16 - int16x8_t yws = vreinterpretq_s16_u16(vshll_n_u8(y_bytes, 4)); - int16x8_t crw = vshll_n_s8(cr_biased, 7); - int16x8_t cbw = vshll_n_s8(cb_biased, 7); - - // color transform - int16x8_t cr0 = vqdmulhq_s16(crw, cr_const0); - int16x8_t cb0 = vqdmulhq_s16(cbw, cb_const0); - int16x8_t cr1 = vqdmulhq_s16(crw, cr_const1); - int16x8_t cb1 = vqdmulhq_s16(cbw, cb_const1); - int16x8_t rws = vaddq_s16(yws, cr0); - int16x8_t gws = vaddq_s16(vaddq_s16(yws, cb0), cr1); - int16x8_t bws = vaddq_s16(yws, cb1); - - // undo scaling, round, convert to byte - uint8x8x4_t o; - o.val[0] = vqrshrun_n_s16(rws, 4); - o.val[1] = vqrshrun_n_s16(gws, 4); - o.val[2] = vqrshrun_n_s16(bws, 4); - o.val[3] = vdup_n_u8(255); - - // store, interleaving r/g/b/a - vst4_u8(out, o); - out += 8*4; - } - } -#endif - - for (; i < count; ++i) { - int y_fixed = (y[i] << 20) + (1<<19); // rounding - int r,g,b; - int cr = pcr[i] - 128; - int cb = pcb[i] - 128; - r = y_fixed + cr* stbi__float2fixed(1.40200f); - g = y_fixed + cr*-stbi__float2fixed(0.71414f) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); - b = y_fixed + cb* stbi__float2fixed(1.77200f); - r >>= 20; - g >>= 20; - b >>= 20; - if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } - if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } - if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } - out[0] = (stbi_uc)r; - out[1] = (stbi_uc)g; - out[2] = (stbi_uc)b; - out[3] = 255; - out += step; - } -} -#endif - -// set up the kernels -static void stbi__setup_jpeg(stbi__jpeg *j) -{ - j->idct_block_kernel = stbi__idct_block; - j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_row; - j->resample_row_hv_2_kernel = stbi__resample_row_hv_2; - -#ifdef STBI_SSE2 - if (stbi__sse2_available()) { - j->idct_block_kernel = stbi__idct_simd; - j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; - j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; - } -#endif - -#ifdef STBI_NEON - j->idct_block_kernel = stbi__idct_simd; - j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; - j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; -#endif -} - -// clean up the temporary component buffers -static void stbi__cleanup_jpeg(stbi__jpeg *j) -{ - stbi__free_jpeg_components(j, j->s->img_n, 0); -} - -typedef struct -{ - resample_row_func resample; - stbi_uc *line0,*line1; - int hs,vs; // expansion factor in each axis - int w_lores; // horizontal pixels pre-expansion - int ystep; // how far through vertical expansion we are - int ypos; // which pre-expansion row we're on -} stbi__resample; - -// fast 0..255 * 0..255 => 0..255 rounded multiplication -static stbi_uc stbi__blinn_8x8(stbi_uc x, stbi_uc y) -{ - unsigned int t = x*y + 128; - return (stbi_uc) ((t + (t >>8)) >> 8); -} - -static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp, int req_comp) -{ - int n, decode_n, is_rgb; - z->s->img_n = 0; // make stbi__cleanup_jpeg safe - - // validate req_comp - if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); - - // load a jpeg image from whichever source, but leave in YCbCr format - if (!stbi__decode_jpeg_image(z)) { stbi__cleanup_jpeg(z); return NULL; } - - // determine actual number of components to generate - n = req_comp ? req_comp : z->s->img_n >= 3 ? 3 : 1; - - is_rgb = z->s->img_n == 3 && (z->rgb == 3 || (z->app14_color_transform == 0 && !z->jfif)); - - if (z->s->img_n == 3 && n < 3 && !is_rgb) - decode_n = 1; - else - decode_n = z->s->img_n; - - // resample and color-convert - { - int k; - unsigned int i,j; - stbi_uc *output; - stbi_uc *coutput[4] = { NULL, NULL, NULL, NULL }; - - stbi__resample res_comp[4]; - - for (k=0; k < decode_n; ++k) { - stbi__resample *r = &res_comp[k]; - - // allocate line buffer big enough for upsampling off the edges - // with upsample factor of 4 - z->img_comp[k].linebuf = (stbi_uc *) stbi__malloc(z->s->img_x + 3); - if (!z->img_comp[k].linebuf) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } - - r->hs = z->img_h_max / z->img_comp[k].h; - r->vs = z->img_v_max / z->img_comp[k].v; - r->ystep = r->vs >> 1; - r->w_lores = (z->s->img_x + r->hs-1) / r->hs; - r->ypos = 0; - r->line0 = r->line1 = z->img_comp[k].data; - - if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1; - else if (r->hs == 1 && r->vs == 2) r->resample = stbi__resample_row_v_2; - else if (r->hs == 2 && r->vs == 1) r->resample = stbi__resample_row_h_2; - else if (r->hs == 2 && r->vs == 2) r->resample = z->resample_row_hv_2_kernel; - else r->resample = stbi__resample_row_generic; - } - - // can't error after this so, this is safe - output = (stbi_uc *) stbi__malloc_mad3(n, z->s->img_x, z->s->img_y, 1); - if (!output) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } - - // now go ahead and resample - for (j=0; j < z->s->img_y; ++j) { - stbi_uc *out = output + n * z->s->img_x * j; - for (k=0; k < decode_n; ++k) { - stbi__resample *r = &res_comp[k]; - int y_bot = r->ystep >= (r->vs >> 1); - coutput[k] = r->resample(z->img_comp[k].linebuf, - y_bot ? r->line1 : r->line0, - y_bot ? r->line0 : r->line1, - r->w_lores, r->hs); - if (++r->ystep >= r->vs) { - r->ystep = 0; - r->line0 = r->line1; - if (++r->ypos < z->img_comp[k].y) - r->line1 += z->img_comp[k].w2; - } - } - if (n >= 3) { - stbi_uc *y = coutput[0]; - if (z->s->img_n == 3) { - if (is_rgb) { - for (i=0; i < z->s->img_x; ++i) { - out[0] = y[i]; - out[1] = coutput[1][i]; - out[2] = coutput[2][i]; - out[3] = 255; - out += n; - } - } else { - z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); - } - } else if (z->s->img_n == 4) { - if (z->app14_color_transform == 0) { // CMYK - for (i=0; i < z->s->img_x; ++i) { - stbi_uc m = coutput[3][i]; - out[0] = stbi__blinn_8x8(coutput[0][i], m); - out[1] = stbi__blinn_8x8(coutput[1][i], m); - out[2] = stbi__blinn_8x8(coutput[2][i], m); - out[3] = 255; - out += n; - } - } else if (z->app14_color_transform == 2) { // YCCK - z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); - for (i=0; i < z->s->img_x; ++i) { - stbi_uc m = coutput[3][i]; - out[0] = stbi__blinn_8x8(255 - out[0], m); - out[1] = stbi__blinn_8x8(255 - out[1], m); - out[2] = stbi__blinn_8x8(255 - out[2], m); - out += n; - } - } else { // YCbCr + alpha? Ignore the fourth channel for now - z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); - } - } else - for (i=0; i < z->s->img_x; ++i) { - out[0] = out[1] = out[2] = y[i]; - out[3] = 255; // not used if n==3 - out += n; - } - } else { - if (is_rgb) { - if (n == 1) - for (i=0; i < z->s->img_x; ++i) - *out++ = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); - else { - for (i=0; i < z->s->img_x; ++i, out += 2) { - out[0] = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); - out[1] = 255; - } - } - } else if (z->s->img_n == 4 && z->app14_color_transform == 0) { - for (i=0; i < z->s->img_x; ++i) { - stbi_uc m = coutput[3][i]; - stbi_uc r = stbi__blinn_8x8(coutput[0][i], m); - stbi_uc g = stbi__blinn_8x8(coutput[1][i], m); - stbi_uc b = stbi__blinn_8x8(coutput[2][i], m); - out[0] = stbi__compute_y(r, g, b); - out[1] = 255; - out += n; - } - } else if (z->s->img_n == 4 && z->app14_color_transform == 2) { - for (i=0; i < z->s->img_x; ++i) { - out[0] = stbi__blinn_8x8(255 - coutput[0][i], coutput[3][i]); - out[1] = 255; - out += n; - } - } else { - stbi_uc *y = coutput[0]; - if (n == 1) - for (i=0; i < z->s->img_x; ++i) out[i] = y[i]; - else - for (i=0; i < z->s->img_x; ++i) { *out++ = y[i]; *out++ = 255; } - } - } - } - stbi__cleanup_jpeg(z); - *out_x = z->s->img_x; - *out_y = z->s->img_y; - if (comp) *comp = z->s->img_n >= 3 ? 3 : 1; // report original components, not output - return output; - } -} - -static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) -{ - unsigned char* result; - stbi__jpeg* j = (stbi__jpeg*) stbi__malloc(sizeof(stbi__jpeg)); - STBI_NOTUSED(ri); - j->s = s; - stbi__setup_jpeg(j); - result = load_jpeg_image(j, x,y,comp,req_comp); - STBI_FREE(j); - return result; -} - -static int stbi__jpeg_test(stbi__context *s) -{ - int r; - stbi__jpeg* j = (stbi__jpeg*)stbi__malloc(sizeof(stbi__jpeg)); - j->s = s; - stbi__setup_jpeg(j); - r = stbi__decode_jpeg_header(j, STBI__SCAN_type); - stbi__rewind(s); - STBI_FREE(j); - return r; -} - -static int stbi__jpeg_info_raw(stbi__jpeg *j, int *x, int *y, int *comp) -{ - if (!stbi__decode_jpeg_header(j, STBI__SCAN_header)) { - stbi__rewind( j->s ); - return 0; - } - if (x) *x = j->s->img_x; - if (y) *y = j->s->img_y; - if (comp) *comp = j->s->img_n >= 3 ? 3 : 1; - return 1; -} - -static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp) -{ - int result; - stbi__jpeg* j = (stbi__jpeg*) (stbi__malloc(sizeof(stbi__jpeg))); - j->s = s; - result = stbi__jpeg_info_raw(j, x, y, comp); - STBI_FREE(j); - return result; -} -#endif - -// public domain zlib decode v0.2 Sean Barrett 2006-11-18 -// simple implementation -// - all input must be provided in an upfront buffer -// - all output is written to a single output buffer (can malloc/realloc) -// performance -// - fast huffman - -#ifndef STBI_NO_ZLIB - -// fast-way is faster to check than jpeg huffman, but slow way is slower -#define STBI__ZFAST_BITS 9 // accelerate all cases in default tables -#define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1) - -// zlib-style huffman encoding -// (jpegs packs from left, zlib from right, so can't share code) -typedef struct -{ - stbi__uint16 fast[1 << STBI__ZFAST_BITS]; - stbi__uint16 firstcode[16]; - int maxcode[17]; - stbi__uint16 firstsymbol[16]; - stbi_uc size[288]; - stbi__uint16 value[288]; -} stbi__zhuffman; - -stbi_inline static int stbi__bitreverse16(int n) -{ - n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1); - n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2); - n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4); - n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8); - return n; -} - -stbi_inline static int stbi__bit_reverse(int v, int bits) -{ - STBI_ASSERT(bits <= 16); - // to bit reverse n bits, reverse 16 and shift - // e.g. 11 bits, bit reverse and shift away 5 - return stbi__bitreverse16(v) >> (16-bits); -} - -static int stbi__zbuild_huffman(stbi__zhuffman *z, const stbi_uc *sizelist, int num) -{ - int i,k=0; - int code, next_code[16], sizes[17]; - - // DEFLATE spec for generating codes - memset(sizes, 0, sizeof(sizes)); - memset(z->fast, 0, sizeof(z->fast)); - for (i=0; i < num; ++i) - ++sizes[sizelist[i]]; - sizes[0] = 0; - for (i=1; i < 16; ++i) - if (sizes[i] > (1 << i)) - return stbi__err("bad sizes", "Corrupt PNG"); - code = 0; - for (i=1; i < 16; ++i) { - next_code[i] = code; - z->firstcode[i] = (stbi__uint16) code; - z->firstsymbol[i] = (stbi__uint16) k; - code = (code + sizes[i]); - if (sizes[i]) - if (code-1 >= (1 << i)) return stbi__err("bad codelengths","Corrupt PNG"); - z->maxcode[i] = code << (16-i); // preshift for inner loop - code <<= 1; - k += sizes[i]; - } - z->maxcode[16] = 0x10000; // sentinel - for (i=0; i < num; ++i) { - int s = sizelist[i]; - if (s) { - int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s]; - stbi__uint16 fastv = (stbi__uint16) ((s << 9) | i); - z->size [c] = (stbi_uc ) s; - z->value[c] = (stbi__uint16) i; - if (s <= STBI__ZFAST_BITS) { - int j = stbi__bit_reverse(next_code[s],s); - while (j < (1 << STBI__ZFAST_BITS)) { - z->fast[j] = fastv; - j += (1 << s); - } - } - ++next_code[s]; - } - } - return 1; -} - -// zlib-from-memory implementation for PNG reading -// because PNG allows splitting the zlib stream arbitrarily, -// and it's annoying structurally to have PNG call ZLIB call PNG, -// we require PNG read all the IDATs and combine them into a single -// memory buffer - -typedef struct -{ - stbi_uc *zbuffer, *zbuffer_end; - int num_bits; - stbi__uint32 code_buffer; - - char *zout; - char *zout_start; - char *zout_end; - int z_expandable; - - stbi__zhuffman z_length, z_distance; -} stbi__zbuf; - -stbi_inline static int stbi__zeof(stbi__zbuf *z) -{ - return (z->zbuffer >= z->zbuffer_end); -} - -stbi_inline static stbi_uc stbi__zget8(stbi__zbuf *z) -{ - return stbi__zeof(z) ? 0 : *z->zbuffer++; -} - -static void stbi__fill_bits(stbi__zbuf *z) -{ - do { - if (z->code_buffer >= (1U << z->num_bits)) { - z->zbuffer = z->zbuffer_end; /* treat this as EOF so we fail. */ - return; - } - z->code_buffer |= (unsigned int) stbi__zget8(z) << z->num_bits; - z->num_bits += 8; - } while (z->num_bits <= 24); -} - -stbi_inline static unsigned int stbi__zreceive(stbi__zbuf *z, int n) -{ - unsigned int k; - if (z->num_bits < n) stbi__fill_bits(z); - k = z->code_buffer & ((1 << n) - 1); - z->code_buffer >>= n; - z->num_bits -= n; - return k; -} - -static int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z) -{ - int b,s,k; - // not resolved by fast table, so compute it the slow way - // use jpeg approach, which requires MSbits at top - k = stbi__bit_reverse(a->code_buffer, 16); - for (s=STBI__ZFAST_BITS+1; ; ++s) - if (k < z->maxcode[s]) - break; - if (s >= 16) return -1; // invalid code! - // code size is s, so: - b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s]; - if (b >= (int) sizeof (z->size)) return -1; // some data was corrupt somewhere! - if (z->size[b] != s) return -1; // was originally an assert, but report failure instead. - a->code_buffer >>= s; - a->num_bits -= s; - return z->value[b]; -} - -stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z) -{ - int b,s; - if (a->num_bits < 16) { - if (stbi__zeof(a)) { - return -1; /* report error for unexpected end of data. */ - } - stbi__fill_bits(a); - } - b = z->fast[a->code_buffer & STBI__ZFAST_MASK]; - if (b) { - s = b >> 9; - a->code_buffer >>= s; - a->num_bits -= s; - return b & 511; - } - return stbi__zhuffman_decode_slowpath(a, z); -} - -static int stbi__zexpand(stbi__zbuf *z, char *zout, int n) // need to make room for n bytes -{ - char *q; - unsigned int cur, limit, old_limit; - z->zout = zout; - if (!z->z_expandable) return stbi__err("output buffer limit","Corrupt PNG"); - cur = (unsigned int) (z->zout - z->zout_start); - limit = old_limit = (unsigned) (z->zout_end - z->zout_start); - if (UINT_MAX - cur < (unsigned) n) return stbi__err("outofmem", "Out of memory"); - while (cur + n > limit) { - if(limit > UINT_MAX / 2) return stbi__err("outofmem", "Out of memory"); - limit *= 2; - } - q = (char *) STBI_REALLOC_SIZED(z->zout_start, old_limit, limit); - STBI_NOTUSED(old_limit); - if (q == NULL) return stbi__err("outofmem", "Out of memory"); - z->zout_start = q; - z->zout = q + cur; - z->zout_end = q + limit; - return 1; -} - -static const int stbi__zlength_base[31] = { - 3,4,5,6,7,8,9,10,11,13, - 15,17,19,23,27,31,35,43,51,59, - 67,83,99,115,131,163,195,227,258,0,0 }; - -static const int stbi__zlength_extra[31]= -{ 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; - -static const int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, -257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; - -static const int stbi__zdist_extra[32] = -{ 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; - -static int stbi__parse_huffman_block(stbi__zbuf *a) -{ - char *zout = a->zout; - for(;;) { - int z = stbi__zhuffman_decode(a, &a->z_length); - if (z < 256) { - if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); // error in huffman codes - if (zout >= a->zout_end) { - if (!stbi__zexpand(a, zout, 1)) return 0; - zout = a->zout; - } - *zout++ = (char) z; - } else { - stbi_uc *p; - int len,dist; - if (z == 256) { - a->zout = zout; - return 1; - } - z -= 257; - len = stbi__zlength_base[z]; - if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]); - z = stbi__zhuffman_decode(a, &a->z_distance); - if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); - dist = stbi__zdist_base[z]; - if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]); - if (zout - a->zout_start < dist) return stbi__err("bad dist","Corrupt PNG"); - if (zout + len > a->zout_end) { - if (!stbi__zexpand(a, zout, len)) return 0; - zout = a->zout; - } - p = (stbi_uc *) (zout - dist); - if (dist == 1) { // run of one byte; common in images. - stbi_uc v = *p; - if (len) { do *zout++ = v; while (--len); } - } else { - if (len) { do *zout++ = *p++; while (--len); } - } - } - } -} - -static int stbi__compute_huffman_codes(stbi__zbuf *a) -{ - static const stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; - stbi__zhuffman z_codelength; - stbi_uc lencodes[286+32+137];//padding for maximum single op - stbi_uc codelength_sizes[19]; - int i,n; - - int hlit = stbi__zreceive(a,5) + 257; - int hdist = stbi__zreceive(a,5) + 1; - int hclen = stbi__zreceive(a,4) + 4; - int ntot = hlit + hdist; - - memset(codelength_sizes, 0, sizeof(codelength_sizes)); - for (i=0; i < hclen; ++i) { - int s = stbi__zreceive(a,3); - codelength_sizes[length_dezigzag[i]] = (stbi_uc) s; - } - if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0; - - n = 0; - while (n < ntot) { - int c = stbi__zhuffman_decode(a, &z_codelength); - if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG"); - if (c < 16) - lencodes[n++] = (stbi_uc) c; - else { - stbi_uc fill = 0; - if (c == 16) { - c = stbi__zreceive(a,2)+3; - if (n == 0) return stbi__err("bad codelengths", "Corrupt PNG"); - fill = lencodes[n-1]; - } else if (c == 17) { - c = stbi__zreceive(a,3)+3; - } else if (c == 18) { - c = stbi__zreceive(a,7)+11; - } else { - return stbi__err("bad codelengths", "Corrupt PNG"); - } - if (ntot - n < c) return stbi__err("bad codelengths", "Corrupt PNG"); - memset(lencodes+n, fill, c); - n += c; - } - } - if (n != ntot) return stbi__err("bad codelengths","Corrupt PNG"); - if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0; - if (!stbi__zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0; - return 1; -} - -static int stbi__parse_uncompressed_block(stbi__zbuf *a) -{ - stbi_uc header[4]; - int len,nlen,k; - if (a->num_bits & 7) - stbi__zreceive(a, a->num_bits & 7); // discard - // drain the bit-packed data into header - k = 0; - while (a->num_bits > 0) { - header[k++] = (stbi_uc) (a->code_buffer & 255); // suppress MSVC run-time check - a->code_buffer >>= 8; - a->num_bits -= 8; - } - if (a->num_bits < 0) return stbi__err("zlib corrupt","Corrupt PNG"); - // now fill header the normal way - while (k < 4) - header[k++] = stbi__zget8(a); - len = header[1] * 256 + header[0]; - nlen = header[3] * 256 + header[2]; - if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt","Corrupt PNG"); - if (a->zbuffer + len > a->zbuffer_end) return stbi__err("read past buffer","Corrupt PNG"); - if (a->zout + len > a->zout_end) - if (!stbi__zexpand(a, a->zout, len)) return 0; - memcpy(a->zout, a->zbuffer, len); - a->zbuffer += len; - a->zout += len; - return 1; -} - -static int stbi__parse_zlib_header(stbi__zbuf *a) -{ - int cmf = stbi__zget8(a); - int cm = cmf & 15; - /* int cinfo = cmf >> 4; */ - int flg = stbi__zget8(a); - if (stbi__zeof(a)) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec - if ((cmf*256+flg) % 31 != 0) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec - if (flg & 32) return stbi__err("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png - if (cm != 8) return stbi__err("bad compression","Corrupt PNG"); // DEFLATE required for png - // window = 1 << (8 + cinfo)... but who cares, we fully buffer output - return 1; -} - -static const stbi_uc stbi__zdefault_length[288] = -{ - 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, - 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, - 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, - 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, - 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, - 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, - 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, - 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, - 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8 -}; -static const stbi_uc stbi__zdefault_distance[32] = -{ - 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5 -}; -/* -Init algorithm: -{ - int i; // use <= to match clearly with spec - for (i=0; i <= 143; ++i) stbi__zdefault_length[i] = 8; - for ( ; i <= 255; ++i) stbi__zdefault_length[i] = 9; - for ( ; i <= 279; ++i) stbi__zdefault_length[i] = 7; - for ( ; i <= 287; ++i) stbi__zdefault_length[i] = 8; - - for (i=0; i <= 31; ++i) stbi__zdefault_distance[i] = 5; -} -*/ - -static int stbi__parse_zlib(stbi__zbuf *a, int parse_header) -{ - int final, type; - if (parse_header) - if (!stbi__parse_zlib_header(a)) return 0; - a->num_bits = 0; - a->code_buffer = 0; - do { - final = stbi__zreceive(a,1); - type = stbi__zreceive(a,2); - if (type == 0) { - if (!stbi__parse_uncompressed_block(a)) return 0; - } else if (type == 3) { - return 0; - } else { - if (type == 1) { - // use fixed code lengths - if (!stbi__zbuild_huffman(&a->z_length , stbi__zdefault_length , 288)) return 0; - if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0; - } else { - if (!stbi__compute_huffman_codes(a)) return 0; - } - if (!stbi__parse_huffman_block(a)) return 0; - } - } while (!final); - return 1; -} - -static int stbi__do_zlib(stbi__zbuf *a, char *obuf, int olen, int exp, int parse_header) -{ - a->zout_start = obuf; - a->zout = obuf; - a->zout_end = obuf + olen; - a->z_expandable = exp; - - return stbi__parse_zlib(a, parse_header); -} - -STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen) -{ - stbi__zbuf a; - char *p = (char *) stbi__malloc(initial_size); - if (p == NULL) return NULL; - a.zbuffer = (stbi_uc *) buffer; - a.zbuffer_end = (stbi_uc *) buffer + len; - if (stbi__do_zlib(&a, p, initial_size, 1, 1)) { - if (outlen) *outlen = (int) (a.zout - a.zout_start); - return a.zout_start; - } else { - STBI_FREE(a.zout_start); - return NULL; - } -} - -STBIDEF char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen) -{ - return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen); -} - -STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header) -{ - stbi__zbuf a; - char *p = (char *) stbi__malloc(initial_size); - if (p == NULL) return NULL; - a.zbuffer = (stbi_uc *) buffer; - a.zbuffer_end = (stbi_uc *) buffer + len; - if (stbi__do_zlib(&a, p, initial_size, 1, parse_header)) { - if (outlen) *outlen = (int) (a.zout - a.zout_start); - return a.zout_start; - } else { - STBI_FREE(a.zout_start); - return NULL; - } -} - -STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen) -{ - stbi__zbuf a; - a.zbuffer = (stbi_uc *) ibuffer; - a.zbuffer_end = (stbi_uc *) ibuffer + ilen; - if (stbi__do_zlib(&a, obuffer, olen, 0, 1)) - return (int) (a.zout - a.zout_start); - else - return -1; -} - -STBIDEF char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen) -{ - stbi__zbuf a; - char *p = (char *) stbi__malloc(16384); - if (p == NULL) return NULL; - a.zbuffer = (stbi_uc *) buffer; - a.zbuffer_end = (stbi_uc *) buffer+len; - if (stbi__do_zlib(&a, p, 16384, 1, 0)) { - if (outlen) *outlen = (int) (a.zout - a.zout_start); - return a.zout_start; - } else { - STBI_FREE(a.zout_start); - return NULL; - } -} - -STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen) -{ - stbi__zbuf a; - a.zbuffer = (stbi_uc *) ibuffer; - a.zbuffer_end = (stbi_uc *) ibuffer + ilen; - if (stbi__do_zlib(&a, obuffer, olen, 0, 0)) - return (int) (a.zout - a.zout_start); - else - return -1; -} -#endif - -// public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18 -// simple implementation -// - only 8-bit samples -// - no CRC checking -// - allocates lots of intermediate memory -// - avoids problem of streaming data between subsystems -// - avoids explicit window management -// performance -// - uses stb_zlib, a PD zlib implementation with fast huffman decoding - -#ifndef STBI_NO_PNG -typedef struct -{ - stbi__uint32 length; - stbi__uint32 type; -} stbi__pngchunk; - -static stbi__pngchunk stbi__get_chunk_header(stbi__context *s) -{ - stbi__pngchunk c; - c.length = stbi__get32be(s); - c.type = stbi__get32be(s); - return c; -} - -static int stbi__check_png_header(stbi__context *s) -{ - static const stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 }; - int i; - for (i=0; i < 8; ++i) - if (stbi__get8(s) != png_sig[i]) return stbi__err("bad png sig","Not a PNG"); - return 1; -} - -typedef struct -{ - stbi__context *s; - stbi_uc *idata, *expanded, *out; - int depth; -} stbi__png; - - -enum { - STBI__F_none=0, - STBI__F_sub=1, - STBI__F_up=2, - STBI__F_avg=3, - STBI__F_paeth=4, - // synthetic filters used for first scanline to avoid needing a dummy row of 0s - STBI__F_avg_first, - STBI__F_paeth_first -}; - -static stbi_uc first_row_filter[5] = -{ - STBI__F_none, - STBI__F_sub, - STBI__F_none, - STBI__F_avg_first, - STBI__F_paeth_first -}; - -static int stbi__paeth(int a, int b, int c) -{ - int p = a + b - c; - int pa = abs(p-a); - int pb = abs(p-b); - int pc = abs(p-c); - if (pa <= pb && pa <= pc) return a; - if (pb <= pc) return b; - return c; -} - -static const stbi_uc stbi__depth_scale_table[9] = { 0, 0xff, 0x55, 0, 0x11, 0,0,0, 0x01 }; - -// create the png data from post-deflated data -static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color) -{ - int bytes = (depth == 16? 2 : 1); - stbi__context *s = a->s; - stbi__uint32 i,j,stride = x*out_n*bytes; - stbi__uint32 img_len, img_width_bytes; - int k; - int img_n = s->img_n; // copy it into a local for later - - int output_bytes = out_n*bytes; - int filter_bytes = img_n*bytes; - int width = x; - - STBI_ASSERT(out_n == s->img_n || out_n == s->img_n+1); - a->out = (stbi_uc *) stbi__malloc_mad3(x, y, output_bytes, 0); // extra bytes to write off the end into - if (!a->out) return stbi__err("outofmem", "Out of memory"); - - if (!stbi__mad3sizes_valid(img_n, x, depth, 7)) return stbi__err("too large", "Corrupt PNG"); - img_width_bytes = (((img_n * x * depth) + 7) >> 3); - img_len = (img_width_bytes + 1) * y; - - // we used to check for exact match between raw_len and img_len on non-interlaced PNGs, - // but issue #276 reported a PNG in the wild that had extra data at the end (all zeros), - // so just check for raw_len < img_len always. - if (raw_len < img_len) return stbi__err("not enough pixels","Corrupt PNG"); - - for (j=0; j < y; ++j) { - stbi_uc *cur = a->out + stride*j; - stbi_uc *prior; - int filter = *raw++; - - if (filter > 4) - return stbi__err("invalid filter","Corrupt PNG"); - - if (depth < 8) { - if (img_width_bytes > x) return stbi__err("invalid width","Corrupt PNG"); - cur += x*out_n - img_width_bytes; // store output to the rightmost img_len bytes, so we can decode in place - filter_bytes = 1; - width = img_width_bytes; - } - prior = cur - stride; // bugfix: need to compute this after 'cur +=' computation above - - // if first row, use special filter that doesn't sample previous row - if (j == 0) filter = first_row_filter[filter]; - - // handle first byte explicitly - for (k=0; k < filter_bytes; ++k) { - switch (filter) { - case STBI__F_none : cur[k] = raw[k]; break; - case STBI__F_sub : cur[k] = raw[k]; break; - case STBI__F_up : cur[k] = STBI__BYTECAST(raw[k] + prior[k]); break; - case STBI__F_avg : cur[k] = STBI__BYTECAST(raw[k] + (prior[k]>>1)); break; - case STBI__F_paeth : cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(0,prior[k],0)); break; - case STBI__F_avg_first : cur[k] = raw[k]; break; - case STBI__F_paeth_first: cur[k] = raw[k]; break; - } - } - - if (depth == 8) { - if (img_n != out_n) - cur[img_n] = 255; // first pixel - raw += img_n; - cur += out_n; - prior += out_n; - } else if (depth == 16) { - if (img_n != out_n) { - cur[filter_bytes] = 255; // first pixel top byte - cur[filter_bytes+1] = 255; // first pixel bottom byte - } - raw += filter_bytes; - cur += output_bytes; - prior += output_bytes; - } else { - raw += 1; - cur += 1; - prior += 1; - } - - // this is a little gross, so that we don't switch per-pixel or per-component - if (depth < 8 || img_n == out_n) { - int nk = (width - 1)*filter_bytes; - #define STBI__CASE(f) \ - case f: \ - for (k=0; k < nk; ++k) - switch (filter) { - // "none" filter turns into a memcpy here; make that explicit. - case STBI__F_none: memcpy(cur, raw, nk); break; - STBI__CASE(STBI__F_sub) { cur[k] = STBI__BYTECAST(raw[k] + cur[k-filter_bytes]); } break; - STBI__CASE(STBI__F_up) { cur[k] = STBI__BYTECAST(raw[k] + prior[k]); } break; - STBI__CASE(STBI__F_avg) { cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-filter_bytes])>>1)); } break; - STBI__CASE(STBI__F_paeth) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],prior[k],prior[k-filter_bytes])); } break; - STBI__CASE(STBI__F_avg_first) { cur[k] = STBI__BYTECAST(raw[k] + (cur[k-filter_bytes] >> 1)); } break; - STBI__CASE(STBI__F_paeth_first) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],0,0)); } break; - } - #undef STBI__CASE - raw += nk; - } else { - STBI_ASSERT(img_n+1 == out_n); - #define STBI__CASE(f) \ - case f: \ - for (i=x-1; i >= 1; --i, cur[filter_bytes]=255,raw+=filter_bytes,cur+=output_bytes,prior+=output_bytes) \ - for (k=0; k < filter_bytes; ++k) - switch (filter) { - STBI__CASE(STBI__F_none) { cur[k] = raw[k]; } break; - STBI__CASE(STBI__F_sub) { cur[k] = STBI__BYTECAST(raw[k] + cur[k- output_bytes]); } break; - STBI__CASE(STBI__F_up) { cur[k] = STBI__BYTECAST(raw[k] + prior[k]); } break; - STBI__CASE(STBI__F_avg) { cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k- output_bytes])>>1)); } break; - STBI__CASE(STBI__F_paeth) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k- output_bytes],prior[k],prior[k- output_bytes])); } break; - STBI__CASE(STBI__F_avg_first) { cur[k] = STBI__BYTECAST(raw[k] + (cur[k- output_bytes] >> 1)); } break; - STBI__CASE(STBI__F_paeth_first) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k- output_bytes],0,0)); } break; - } - #undef STBI__CASE - - // the loop above sets the high byte of the pixels' alpha, but for - // 16 bit png files we also need the low byte set. we'll do that here. - if (depth == 16) { - cur = a->out + stride*j; // start at the beginning of the row again - for (i=0; i < x; ++i,cur+=output_bytes) { - cur[filter_bytes+1] = 255; - } - } - } - } - - // we make a separate pass to expand bits to pixels; for performance, - // this could run two scanlines behind the above code, so it won't - // intefere with filtering but will still be in the cache. - if (depth < 8) { - for (j=0; j < y; ++j) { - stbi_uc *cur = a->out + stride*j; - stbi_uc *in = a->out + stride*j + x*out_n - img_width_bytes; - // unpack 1/2/4-bit into a 8-bit buffer. allows us to keep the common 8-bit path optimal at minimal cost for 1/2/4-bit - // png guarante byte alignment, if width is not multiple of 8/4/2 we'll decode dummy trailing data that will be skipped in the later loop - stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] : 1; // scale grayscale values to 0..255 range - - // note that the final byte might overshoot and write more data than desired. - // we can allocate enough data that this never writes out of memory, but it - // could also overwrite the next scanline. can it overwrite non-empty data - // on the next scanline? yes, consider 1-pixel-wide scanlines with 1-bit-per-pixel. - // so we need to explicitly clamp the final ones - - if (depth == 4) { - for (k=x*img_n; k >= 2; k-=2, ++in) { - *cur++ = scale * ((*in >> 4) ); - *cur++ = scale * ((*in ) & 0x0f); - } - if (k > 0) *cur++ = scale * ((*in >> 4) ); - } else if (depth == 2) { - for (k=x*img_n; k >= 4; k-=4, ++in) { - *cur++ = scale * ((*in >> 6) ); - *cur++ = scale * ((*in >> 4) & 0x03); - *cur++ = scale * ((*in >> 2) & 0x03); - *cur++ = scale * ((*in ) & 0x03); - } - if (k > 0) *cur++ = scale * ((*in >> 6) ); - if (k > 1) *cur++ = scale * ((*in >> 4) & 0x03); - if (k > 2) *cur++ = scale * ((*in >> 2) & 0x03); - } else if (depth == 1) { - for (k=x*img_n; k >= 8; k-=8, ++in) { - *cur++ = scale * ((*in >> 7) ); - *cur++ = scale * ((*in >> 6) & 0x01); - *cur++ = scale * ((*in >> 5) & 0x01); - *cur++ = scale * ((*in >> 4) & 0x01); - *cur++ = scale * ((*in >> 3) & 0x01); - *cur++ = scale * ((*in >> 2) & 0x01); - *cur++ = scale * ((*in >> 1) & 0x01); - *cur++ = scale * ((*in ) & 0x01); - } - if (k > 0) *cur++ = scale * ((*in >> 7) ); - if (k > 1) *cur++ = scale * ((*in >> 6) & 0x01); - if (k > 2) *cur++ = scale * ((*in >> 5) & 0x01); - if (k > 3) *cur++ = scale * ((*in >> 4) & 0x01); - if (k > 4) *cur++ = scale * ((*in >> 3) & 0x01); - if (k > 5) *cur++ = scale * ((*in >> 2) & 0x01); - if (k > 6) *cur++ = scale * ((*in >> 1) & 0x01); - } - if (img_n != out_n) { - int q; - // insert alpha = 255 - cur = a->out + stride*j; - if (img_n == 1) { - for (q=x-1; q >= 0; --q) { - cur[q*2+1] = 255; - cur[q*2+0] = cur[q]; - } - } else { - STBI_ASSERT(img_n == 3); - for (q=x-1; q >= 0; --q) { - cur[q*4+3] = 255; - cur[q*4+2] = cur[q*3+2]; - cur[q*4+1] = cur[q*3+1]; - cur[q*4+0] = cur[q*3+0]; - } - } - } - } - } else if (depth == 16) { - // force the image data from big-endian to platform-native. - // this is done in a separate pass due to the decoding relying - // on the data being untouched, but could probably be done - // per-line during decode if care is taken. - stbi_uc *cur = a->out; - stbi__uint16 *cur16 = (stbi__uint16*)cur; - - for(i=0; i < x*y*out_n; ++i,cur16++,cur+=2) { - *cur16 = (cur[0] << 8) | cur[1]; - } - } - - return 1; -} - -static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint32 image_data_len, int out_n, int depth, int color, int interlaced) -{ - int bytes = (depth == 16 ? 2 : 1); - int out_bytes = out_n * bytes; - stbi_uc *final; - int p; - if (!interlaced) - return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, a->s->img_y, depth, color); - - // de-interlacing - final = (stbi_uc *) stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0); - for (p=0; p < 7; ++p) { - int xorig[] = { 0,4,0,2,0,1,0 }; - int yorig[] = { 0,0,4,0,2,0,1 }; - int xspc[] = { 8,8,4,4,2,2,1 }; - int yspc[] = { 8,8,8,4,4,2,2 }; - int i,j,x,y; - // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1 - x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p]; - y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p]; - if (x && y) { - stbi__uint32 img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y; - if (!stbi__create_png_image_raw(a, image_data, image_data_len, out_n, x, y, depth, color)) { - STBI_FREE(final); - return 0; - } - for (j=0; j < y; ++j) { - for (i=0; i < x; ++i) { - int out_y = j*yspc[p]+yorig[p]; - int out_x = i*xspc[p]+xorig[p]; - memcpy(final + out_y*a->s->img_x*out_bytes + out_x*out_bytes, - a->out + (j*x+i)*out_bytes, out_bytes); - } - } - STBI_FREE(a->out); - image_data += img_len; - image_data_len -= img_len; - } - } - a->out = final; - - return 1; -} - -static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n) -{ - stbi__context *s = z->s; - stbi__uint32 i, pixel_count = s->img_x * s->img_y; - stbi_uc *p = z->out; - - // compute color-based transparency, assuming we've - // already got 255 as the alpha value in the output - STBI_ASSERT(out_n == 2 || out_n == 4); - - if (out_n == 2) { - for (i=0; i < pixel_count; ++i) { - p[1] = (p[0] == tc[0] ? 0 : 255); - p += 2; - } - } else { - for (i=0; i < pixel_count; ++i) { - if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) - p[3] = 0; - p += 4; - } - } - return 1; -} - -static int stbi__compute_transparency16(stbi__png *z, stbi__uint16 tc[3], int out_n) -{ - stbi__context *s = z->s; - stbi__uint32 i, pixel_count = s->img_x * s->img_y; - stbi__uint16 *p = (stbi__uint16*) z->out; - - // compute color-based transparency, assuming we've - // already got 65535 as the alpha value in the output - STBI_ASSERT(out_n == 2 || out_n == 4); - - if (out_n == 2) { - for (i = 0; i < pixel_count; ++i) { - p[1] = (p[0] == tc[0] ? 0 : 65535); - p += 2; - } - } else { - for (i = 0; i < pixel_count; ++i) { - if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) - p[3] = 0; - p += 4; - } - } - return 1; -} - -static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int pal_img_n) -{ - stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y; - stbi_uc *p, *temp_out, *orig = a->out; - - p = (stbi_uc *) stbi__malloc_mad2(pixel_count, pal_img_n, 0); - if (p == NULL) return stbi__err("outofmem", "Out of memory"); - - // between here and free(out) below, exitting would leak - temp_out = p; - - if (pal_img_n == 3) { - for (i=0; i < pixel_count; ++i) { - int n = orig[i]*4; - p[0] = palette[n ]; - p[1] = palette[n+1]; - p[2] = palette[n+2]; - p += 3; - } - } else { - for (i=0; i < pixel_count; ++i) { - int n = orig[i]*4; - p[0] = palette[n ]; - p[1] = palette[n+1]; - p[2] = palette[n+2]; - p[3] = palette[n+3]; - p += 4; - } - } - STBI_FREE(a->out); - a->out = temp_out; - - STBI_NOTUSED(len); - - return 1; -} - -static int stbi__unpremultiply_on_load = 0; -static int stbi__de_iphone_flag = 0; - -STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply) -{ - stbi__unpremultiply_on_load = flag_true_if_should_unpremultiply; -} - -STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert) -{ - stbi__de_iphone_flag = flag_true_if_should_convert; -} - -static void stbi__de_iphone(stbi__png *z) -{ - stbi__context *s = z->s; - stbi__uint32 i, pixel_count = s->img_x * s->img_y; - stbi_uc *p = z->out; - - if (s->img_out_n == 3) { // convert bgr to rgb - for (i=0; i < pixel_count; ++i) { - stbi_uc t = p[0]; - p[0] = p[2]; - p[2] = t; - p += 3; - } - } else { - STBI_ASSERT(s->img_out_n == 4); - if (stbi__unpremultiply_on_load) { - // convert bgr to rgb and unpremultiply - for (i=0; i < pixel_count; ++i) { - stbi_uc a = p[3]; - stbi_uc t = p[0]; - if (a) { - stbi_uc half = a / 2; - p[0] = (p[2] * 255 + half) / a; - p[1] = (p[1] * 255 + half) / a; - p[2] = ( t * 255 + half) / a; - } else { - p[0] = p[2]; - p[2] = t; - } - p += 4; - } - } else { - // convert bgr to rgb - for (i=0; i < pixel_count; ++i) { - stbi_uc t = p[0]; - p[0] = p[2]; - p[2] = t; - p += 4; - } - } - } -} - -#define STBI__PNG_TYPE(a,b,c,d) (((unsigned) (a) << 24) + ((unsigned) (b) << 16) + ((unsigned) (c) << 8) + (unsigned) (d)) - -static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) -{ - stbi_uc palette[1024], pal_img_n=0; - stbi_uc has_trans=0, tc[3]={0}; - stbi__uint16 tc16[3]; - stbi__uint32 ioff=0, idata_limit=0, i, pal_len=0; - int first=1,k,interlace=0, color=0, is_iphone=0; - stbi__context *s = z->s; - - z->expanded = NULL; - z->idata = NULL; - z->out = NULL; - - if (!stbi__check_png_header(s)) return 0; - - if (scan == STBI__SCAN_type) return 1; - - for (;;) { - stbi__pngchunk c = stbi__get_chunk_header(s); - switch (c.type) { - case STBI__PNG_TYPE('C','g','B','I'): - is_iphone = 1; - stbi__skip(s, c.length); - break; - case STBI__PNG_TYPE('I','H','D','R'): { - int comp,filter; - if (!first) return stbi__err("multiple IHDR","Corrupt PNG"); - first = 0; - if (c.length != 13) return stbi__err("bad IHDR len","Corrupt PNG"); - s->img_x = stbi__get32be(s); - s->img_y = stbi__get32be(s); - if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); - if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); - z->depth = stbi__get8(s); if (z->depth != 1 && z->depth != 2 && z->depth != 4 && z->depth != 8 && z->depth != 16) return stbi__err("1/2/4/8/16-bit only","PNG not supported: 1/2/4/8/16-bit only"); - color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype","Corrupt PNG"); - if (color == 3 && z->depth == 16) return stbi__err("bad ctype","Corrupt PNG"); - if (color == 3) pal_img_n = 3; else if (color & 1) return stbi__err("bad ctype","Corrupt PNG"); - comp = stbi__get8(s); if (comp) return stbi__err("bad comp method","Corrupt PNG"); - filter= stbi__get8(s); if (filter) return stbi__err("bad filter method","Corrupt PNG"); - interlace = stbi__get8(s); if (interlace>1) return stbi__err("bad interlace method","Corrupt PNG"); - if (!s->img_x || !s->img_y) return stbi__err("0-pixel image","Corrupt PNG"); - if (!pal_img_n) { - s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0); - if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode"); - if (scan == STBI__SCAN_header) return 1; - } else { - // if paletted, then pal_n is our final components, and - // img_n is # components to decompress/filter. - s->img_n = 1; - if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err("too large","Corrupt PNG"); - // if SCAN_header, have to scan to see if we have a tRNS - } - break; - } - - case STBI__PNG_TYPE('P','L','T','E'): { - if (first) return stbi__err("first not IHDR", "Corrupt PNG"); - if (c.length > 256*3) return stbi__err("invalid PLTE","Corrupt PNG"); - pal_len = c.length / 3; - if (pal_len * 3 != c.length) return stbi__err("invalid PLTE","Corrupt PNG"); - for (i=0; i < pal_len; ++i) { - palette[i*4+0] = stbi__get8(s); - palette[i*4+1] = stbi__get8(s); - palette[i*4+2] = stbi__get8(s); - palette[i*4+3] = 255; - } - break; - } - - case STBI__PNG_TYPE('t','R','N','S'): { - if (first) return stbi__err("first not IHDR", "Corrupt PNG"); - if (z->idata) return stbi__err("tRNS after IDAT","Corrupt PNG"); - if (pal_img_n) { - if (scan == STBI__SCAN_header) { s->img_n = 4; return 1; } - if (pal_len == 0) return stbi__err("tRNS before PLTE","Corrupt PNG"); - if (c.length > pal_len) return stbi__err("bad tRNS len","Corrupt PNG"); - pal_img_n = 4; - for (i=0; i < c.length; ++i) - palette[i*4+3] = stbi__get8(s); - } else { - if (!(s->img_n & 1)) return stbi__err("tRNS with alpha","Corrupt PNG"); - if (c.length != (stbi__uint32) s->img_n*2) return stbi__err("bad tRNS len","Corrupt PNG"); - has_trans = 1; - if (z->depth == 16) { - for (k = 0; k < s->img_n; ++k) tc16[k] = (stbi__uint16)stbi__get16be(s); // copy the values as-is - } else { - for (k = 0; k < s->img_n; ++k) tc[k] = (stbi_uc)(stbi__get16be(s) & 255) * stbi__depth_scale_table[z->depth]; // non 8-bit images will be larger - } - } - break; - } - - case STBI__PNG_TYPE('I','D','A','T'): { - if (first) return stbi__err("first not IHDR", "Corrupt PNG"); - if (pal_img_n && !pal_len) return stbi__err("no PLTE","Corrupt PNG"); - if (scan == STBI__SCAN_header) { s->img_n = pal_img_n; return 1; } - if ((int)(ioff + c.length) < (int)ioff) return 0; - if (ioff + c.length > idata_limit) { - stbi__uint32 idata_limit_old = idata_limit; - stbi_uc *p; - if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096; - while (ioff + c.length > idata_limit) - idata_limit *= 2; - STBI_NOTUSED(idata_limit_old); - p = (stbi_uc *) STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory"); - z->idata = p; - } - if (!stbi__getn(s, z->idata+ioff,c.length)) return stbi__err("outofdata","Corrupt PNG"); - ioff += c.length; - break; - } - - case STBI__PNG_TYPE('I','E','N','D'): { - stbi__uint32 raw_len, bpl; - if (first) return stbi__err("first not IHDR", "Corrupt PNG"); - if (scan != STBI__SCAN_load) return 1; - if (z->idata == NULL) return stbi__err("no IDAT","Corrupt PNG"); - // initial guess for decoded data size to avoid unnecessary reallocs - bpl = (s->img_x * z->depth + 7) / 8; // bytes per line, per component - raw_len = bpl * s->img_y * s->img_n /* pixels */ + s->img_y /* filter mode per row */; - z->expanded = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, raw_len, (int *) &raw_len, !is_iphone); - if (z->expanded == NULL) return 0; // zlib should set error - STBI_FREE(z->idata); z->idata = NULL; - if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans) - s->img_out_n = s->img_n+1; - else - s->img_out_n = s->img_n; - if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, z->depth, color, interlace)) return 0; - if (has_trans) { - if (z->depth == 16) { - if (!stbi__compute_transparency16(z, tc16, s->img_out_n)) return 0; - } else { - if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0; - } - } - if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2) - stbi__de_iphone(z); - if (pal_img_n) { - // pal_img_n == 3 or 4 - s->img_n = pal_img_n; // record the actual colors we had - s->img_out_n = pal_img_n; - if (req_comp >= 3) s->img_out_n = req_comp; - if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n)) - return 0; - } else if (has_trans) { - // non-paletted image with tRNS -> source image has (constant) alpha - ++s->img_n; - } - STBI_FREE(z->expanded); z->expanded = NULL; - // end of PNG chunk, read and skip CRC - stbi__get32be(s); - return 1; - } - - default: - // if critical, fail - if (first) return stbi__err("first not IHDR", "Corrupt PNG"); - if ((c.type & (1 << 29)) == 0) { - #ifndef STBI_NO_FAILURE_STRINGS - // not threadsafe - static char invalid_chunk[] = "XXXX PNG chunk not known"; - invalid_chunk[0] = STBI__BYTECAST(c.type >> 24); - invalid_chunk[1] = STBI__BYTECAST(c.type >> 16); - invalid_chunk[2] = STBI__BYTECAST(c.type >> 8); - invalid_chunk[3] = STBI__BYTECAST(c.type >> 0); - #endif - return stbi__err(invalid_chunk, "PNG not supported: unknown PNG chunk type"); - } - stbi__skip(s, c.length); - break; - } - // end of PNG chunk, read and skip CRC - stbi__get32be(s); - } -} - -static void *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp, stbi__result_info *ri) -{ - void *result=NULL; - if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); - if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) { - if (p->depth <= 8) - ri->bits_per_channel = 8; - else if (p->depth == 16) - ri->bits_per_channel = 16; - else - return stbi__errpuc("bad bits_per_channel", "PNG not supported: unsupported color depth"); - result = p->out; - p->out = NULL; - if (req_comp && req_comp != p->s->img_out_n) { - if (ri->bits_per_channel == 8) - result = stbi__convert_format((unsigned char *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); - else - result = stbi__convert_format16((stbi__uint16 *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); - p->s->img_out_n = req_comp; - if (result == NULL) return result; - } - *x = p->s->img_x; - *y = p->s->img_y; - if (n) *n = p->s->img_n; - } - STBI_FREE(p->out); p->out = NULL; - STBI_FREE(p->expanded); p->expanded = NULL; - STBI_FREE(p->idata); p->idata = NULL; - - return result; -} - -static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) -{ - stbi__png p; - p.s = s; - return stbi__do_png(&p, x,y,comp,req_comp, ri); -} - -static int stbi__png_test(stbi__context *s) -{ - int r; - r = stbi__check_png_header(s); - stbi__rewind(s); - return r; -} - -static int stbi__png_info_raw(stbi__png *p, int *x, int *y, int *comp) -{ - if (!stbi__parse_png_file(p, STBI__SCAN_header, 0)) { - stbi__rewind( p->s ); - return 0; - } - if (x) *x = p->s->img_x; - if (y) *y = p->s->img_y; - if (comp) *comp = p->s->img_n; - return 1; -} - -static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp) -{ - stbi__png p; - p.s = s; - return stbi__png_info_raw(&p, x, y, comp); -} - -static int stbi__png_is16(stbi__context *s) -{ - stbi__png p; - p.s = s; - if (!stbi__png_info_raw(&p, NULL, NULL, NULL)) - return 0; - if (p.depth != 16) { - stbi__rewind(p.s); - return 0; - } - return 1; -} -#endif - -// Microsoft/Windows BMP image - -#ifndef STBI_NO_BMP -static int stbi__bmp_test_raw(stbi__context *s) -{ - int r; - int sz; - if (stbi__get8(s) != 'B') return 0; - if (stbi__get8(s) != 'M') return 0; - stbi__get32le(s); // discard filesize - stbi__get16le(s); // discard reserved - stbi__get16le(s); // discard reserved - stbi__get32le(s); // discard data offset - sz = stbi__get32le(s); - r = (sz == 12 || sz == 40 || sz == 56 || sz == 108 || sz == 124); - return r; -} - -static int stbi__bmp_test(stbi__context *s) -{ - int r = stbi__bmp_test_raw(s); - stbi__rewind(s); - return r; -} - - -// returns 0..31 for the highest set bit -static int stbi__high_bit(unsigned int z) -{ - int n=0; - if (z == 0) return -1; - if (z >= 0x10000) { n += 16; z >>= 16; } - if (z >= 0x00100) { n += 8; z >>= 8; } - if (z >= 0x00010) { n += 4; z >>= 4; } - if (z >= 0x00004) { n += 2; z >>= 2; } - if (z >= 0x00002) { n += 1;/* >>= 1;*/ } - return n; -} - -static int stbi__bitcount(unsigned int a) -{ - a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2 - a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4 - a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits - a = (a + (a >> 8)); // max 16 per 8 bits - a = (a + (a >> 16)); // max 32 per 8 bits - return a & 0xff; -} - -// extract an arbitrarily-aligned N-bit value (N=bits) -// from v, and then make it 8-bits long and fractionally -// extend it to full full range. -static int stbi__shiftsigned(unsigned int v, int shift, int bits) -{ - static unsigned int mul_table[9] = { - 0, - 0xff/*0b11111111*/, 0x55/*0b01010101*/, 0x49/*0b01001001*/, 0x11/*0b00010001*/, - 0x21/*0b00100001*/, 0x41/*0b01000001*/, 0x81/*0b10000001*/, 0x01/*0b00000001*/, - }; - static unsigned int shift_table[9] = { - 0, 0,0,1,0,2,4,6,0, - }; - if (shift < 0) - v <<= -shift; - else - v >>= shift; - STBI_ASSERT(v < 256); - v >>= (8-bits); - STBI_ASSERT(bits >= 0 && bits <= 8); - return (int) ((unsigned) v * mul_table[bits]) >> shift_table[bits]; -} - -typedef struct -{ - int bpp, offset, hsz; - unsigned int mr,mg,mb,ma, all_a; - int extra_read; -} stbi__bmp_data; - -static void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info) -{ - int hsz; - if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') return stbi__errpuc("not BMP", "Corrupt BMP"); - stbi__get32le(s); // discard filesize - stbi__get16le(s); // discard reserved - stbi__get16le(s); // discard reserved - info->offset = stbi__get32le(s); - info->hsz = hsz = stbi__get32le(s); - info->mr = info->mg = info->mb = info->ma = 0; - info->extra_read = 14; - - if (info->offset < 0) return stbi__errpuc("bad BMP", "bad BMP"); - - if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) return stbi__errpuc("unknown BMP", "BMP type not supported: unknown"); - if (hsz == 12) { - s->img_x = stbi__get16le(s); - s->img_y = stbi__get16le(s); - } else { - s->img_x = stbi__get32le(s); - s->img_y = stbi__get32le(s); - } - if (stbi__get16le(s) != 1) return stbi__errpuc("bad BMP", "bad BMP"); - info->bpp = stbi__get16le(s); - if (hsz != 12) { - int compress = stbi__get32le(s); - if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE"); - stbi__get32le(s); // discard sizeof - stbi__get32le(s); // discard hres - stbi__get32le(s); // discard vres - stbi__get32le(s); // discard colorsused - stbi__get32le(s); // discard max important - if (hsz == 40 || hsz == 56) { - if (hsz == 56) { - stbi__get32le(s); - stbi__get32le(s); - stbi__get32le(s); - stbi__get32le(s); - } - if (info->bpp == 16 || info->bpp == 32) { - if (compress == 0) { - if (info->bpp == 32) { - info->mr = 0xffu << 16; - info->mg = 0xffu << 8; - info->mb = 0xffu << 0; - info->ma = 0xffu << 24; - info->all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 0 - } else { - info->mr = 31u << 10; - info->mg = 31u << 5; - info->mb = 31u << 0; - } - } else if (compress == 3) { - info->mr = stbi__get32le(s); - info->mg = stbi__get32le(s); - info->mb = stbi__get32le(s); - info->extra_read += 12; - // not documented, but generated by photoshop and handled by mspaint - if (info->mr == info->mg && info->mg == info->mb) { - // ?!?!? - return stbi__errpuc("bad BMP", "bad BMP"); - } - } else - return stbi__errpuc("bad BMP", "bad BMP"); - } - } else { - int i; - if (hsz != 108 && hsz != 124) - return stbi__errpuc("bad BMP", "bad BMP"); - info->mr = stbi__get32le(s); - info->mg = stbi__get32le(s); - info->mb = stbi__get32le(s); - info->ma = stbi__get32le(s); - stbi__get32le(s); // discard color space - for (i=0; i < 12; ++i) - stbi__get32le(s); // discard color space parameters - if (hsz == 124) { - stbi__get32le(s); // discard rendering intent - stbi__get32le(s); // discard offset of profile data - stbi__get32le(s); // discard size of profile data - stbi__get32le(s); // discard reserved - } - } - } - return (void *) 1; -} - - -static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) -{ - stbi_uc *out; - unsigned int mr=0,mg=0,mb=0,ma=0, all_a; - stbi_uc pal[256][4]; - int psize=0,i,j,width; - int flip_vertically, pad, target; - stbi__bmp_data info; - STBI_NOTUSED(ri); - - info.all_a = 255; - if (stbi__bmp_parse_header(s, &info) == NULL) - return NULL; // error code already set - - flip_vertically = ((int) s->img_y) > 0; - s->img_y = abs((int) s->img_y); - - if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); - if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); - - mr = info.mr; - mg = info.mg; - mb = info.mb; - ma = info.ma; - all_a = info.all_a; - - if (info.hsz == 12) { - if (info.bpp < 24) - psize = (info.offset - info.extra_read - 24) / 3; - } else { - if (info.bpp < 16) - psize = (info.offset - info.extra_read - info.hsz) >> 2; - } - if (psize == 0) { - STBI_ASSERT(info.offset == s->callback_already_read + (int) (s->img_buffer - s->img_buffer_original)); - if (info.offset != s->callback_already_read + (s->img_buffer - s->buffer_start)) { - return stbi__errpuc("bad offset", "Corrupt BMP"); - } - } - - if (info.bpp == 24 && ma == 0xff000000) - s->img_n = 3; - else - s->img_n = ma ? 4 : 3; - if (req_comp && req_comp >= 3) // we can directly decode 3 or 4 - target = req_comp; - else - target = s->img_n; // if they want monochrome, we'll post-convert - - // sanity-check size - if (!stbi__mad3sizes_valid(target, s->img_x, s->img_y, 0)) - return stbi__errpuc("too large", "Corrupt BMP"); - - out = (stbi_uc *) stbi__malloc_mad3(target, s->img_x, s->img_y, 0); - if (!out) return stbi__errpuc("outofmem", "Out of memory"); - if (info.bpp < 16) { - int z=0; - if (psize == 0 || psize > 256) { STBI_FREE(out); return stbi__errpuc("invalid", "Corrupt BMP"); } - for (i=0; i < psize; ++i) { - pal[i][2] = stbi__get8(s); - pal[i][1] = stbi__get8(s); - pal[i][0] = stbi__get8(s); - if (info.hsz != 12) stbi__get8(s); - pal[i][3] = 255; - } - stbi__skip(s, info.offset - info.extra_read - info.hsz - psize * (info.hsz == 12 ? 3 : 4)); - if (info.bpp == 1) width = (s->img_x + 7) >> 3; - else if (info.bpp == 4) width = (s->img_x + 1) >> 1; - else if (info.bpp == 8) width = s->img_x; - else { STBI_FREE(out); return stbi__errpuc("bad bpp", "Corrupt BMP"); } - pad = (-width)&3; - if (info.bpp == 1) { - for (j=0; j < (int) s->img_y; ++j) { - int bit_offset = 7, v = stbi__get8(s); - for (i=0; i < (int) s->img_x; ++i) { - int color = (v>>bit_offset)&0x1; - out[z++] = pal[color][0]; - out[z++] = pal[color][1]; - out[z++] = pal[color][2]; - if (target == 4) out[z++] = 255; - if (i+1 == (int) s->img_x) break; - if((--bit_offset) < 0) { - bit_offset = 7; - v = stbi__get8(s); - } - } - stbi__skip(s, pad); - } - } else { - for (j=0; j < (int) s->img_y; ++j) { - for (i=0; i < (int) s->img_x; i += 2) { - int v=stbi__get8(s),v2=0; - if (info.bpp == 4) { - v2 = v & 15; - v >>= 4; - } - out[z++] = pal[v][0]; - out[z++] = pal[v][1]; - out[z++] = pal[v][2]; - if (target == 4) out[z++] = 255; - if (i+1 == (int) s->img_x) break; - v = (info.bpp == 8) ? stbi__get8(s) : v2; - out[z++] = pal[v][0]; - out[z++] = pal[v][1]; - out[z++] = pal[v][2]; - if (target == 4) out[z++] = 255; - } - stbi__skip(s, pad); - } - } - } else { - int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0; - int z = 0; - int easy=0; - stbi__skip(s, info.offset - info.extra_read - info.hsz); - if (info.bpp == 24) width = 3 * s->img_x; - else if (info.bpp == 16) width = 2*s->img_x; - else /* bpp = 32 and pad = 0 */ width=0; - pad = (-width) & 3; - if (info.bpp == 24) { - easy = 1; - } else if (info.bpp == 32) { - if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000) - easy = 2; - } - if (!easy) { - if (!mr || !mg || !mb) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } - // right shift amt to put high bit in position #7 - rshift = stbi__high_bit(mr)-7; rcount = stbi__bitcount(mr); - gshift = stbi__high_bit(mg)-7; gcount = stbi__bitcount(mg); - bshift = stbi__high_bit(mb)-7; bcount = stbi__bitcount(mb); - ashift = stbi__high_bit(ma)-7; acount = stbi__bitcount(ma); - if (rcount > 8 || gcount > 8 || bcount > 8 || acount > 8) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } - } - for (j=0; j < (int) s->img_y; ++j) { - if (easy) { - for (i=0; i < (int) s->img_x; ++i) { - unsigned char a; - out[z+2] = stbi__get8(s); - out[z+1] = stbi__get8(s); - out[z+0] = stbi__get8(s); - z += 3; - a = (easy == 2 ? stbi__get8(s) : 255); - all_a |= a; - if (target == 4) out[z++] = a; - } - } else { - int bpp = info.bpp; - for (i=0; i < (int) s->img_x; ++i) { - stbi__uint32 v = (bpp == 16 ? (stbi__uint32) stbi__get16le(s) : stbi__get32le(s)); - unsigned int a; - out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mr, rshift, rcount)); - out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mg, gshift, gcount)); - out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mb, bshift, bcount)); - a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255); - all_a |= a; - if (target == 4) out[z++] = STBI__BYTECAST(a); - } - } - stbi__skip(s, pad); - } - } - - // if alpha channel is all 0s, replace with all 255s - if (target == 4 && all_a == 0) - for (i=4*s->img_x*s->img_y-1; i >= 0; i -= 4) - out[i] = 255; - - if (flip_vertically) { - stbi_uc t; - for (j=0; j < (int) s->img_y>>1; ++j) { - stbi_uc *p1 = out + j *s->img_x*target; - stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target; - for (i=0; i < (int) s->img_x*target; ++i) { - t = p1[i]; p1[i] = p2[i]; p2[i] = t; - } - } - } - - if (req_comp && req_comp != target) { - out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y); - if (out == NULL) return out; // stbi__convert_format frees input on failure - } - - *x = s->img_x; - *y = s->img_y; - if (comp) *comp = s->img_n; - return out; -} -#endif - -// Targa Truevision - TGA -// by Jonathan Dummer -#ifndef STBI_NO_TGA -// returns STBI_rgb or whatever, 0 on error -static int stbi__tga_get_comp(int bits_per_pixel, int is_grey, int* is_rgb16) -{ - // only RGB or RGBA (incl. 16bit) or grey allowed - if (is_rgb16) *is_rgb16 = 0; - switch(bits_per_pixel) { - case 8: return STBI_grey; - case 16: if(is_grey) return STBI_grey_alpha; - // fallthrough - case 15: if(is_rgb16) *is_rgb16 = 1; - return STBI_rgb; - case 24: // fallthrough - case 32: return bits_per_pixel/8; - default: return 0; - } -} - -static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp) -{ - int tga_w, tga_h, tga_comp, tga_image_type, tga_bits_per_pixel, tga_colormap_bpp; - int sz, tga_colormap_type; - stbi__get8(s); // discard Offset - tga_colormap_type = stbi__get8(s); // colormap type - if( tga_colormap_type > 1 ) { - stbi__rewind(s); - return 0; // only RGB or indexed allowed - } - tga_image_type = stbi__get8(s); // image type - if ( tga_colormap_type == 1 ) { // colormapped (paletted) image - if (tga_image_type != 1 && tga_image_type != 9) { - stbi__rewind(s); - return 0; - } - stbi__skip(s,4); // skip index of first colormap entry and number of entries - sz = stbi__get8(s); // check bits per palette color entry - if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) { - stbi__rewind(s); - return 0; - } - stbi__skip(s,4); // skip image x and y origin - tga_colormap_bpp = sz; - } else { // "normal" image w/o colormap - only RGB or grey allowed, +/- RLE - if ( (tga_image_type != 2) && (tga_image_type != 3) && (tga_image_type != 10) && (tga_image_type != 11) ) { - stbi__rewind(s); - return 0; // only RGB or grey allowed, +/- RLE - } - stbi__skip(s,9); // skip colormap specification and image x/y origin - tga_colormap_bpp = 0; - } - tga_w = stbi__get16le(s); - if( tga_w < 1 ) { - stbi__rewind(s); - return 0; // test width - } - tga_h = stbi__get16le(s); - if( tga_h < 1 ) { - stbi__rewind(s); - return 0; // test height - } - tga_bits_per_pixel = stbi__get8(s); // bits per pixel - stbi__get8(s); // ignore alpha bits - if (tga_colormap_bpp != 0) { - if((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16)) { - // when using a colormap, tga_bits_per_pixel is the size of the indexes - // I don't think anything but 8 or 16bit indexes makes sense - stbi__rewind(s); - return 0; - } - tga_comp = stbi__tga_get_comp(tga_colormap_bpp, 0, NULL); - } else { - tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3) || (tga_image_type == 11), NULL); - } - if(!tga_comp) { - stbi__rewind(s); - return 0; - } - if (x) *x = tga_w; - if (y) *y = tga_h; - if (comp) *comp = tga_comp; - return 1; // seems to have passed everything -} - -static int stbi__tga_test(stbi__context *s) -{ - int res = 0; - int sz, tga_color_type; - stbi__get8(s); // discard Offset - tga_color_type = stbi__get8(s); // color type - if ( tga_color_type > 1 ) goto errorEnd; // only RGB or indexed allowed - sz = stbi__get8(s); // image type - if ( tga_color_type == 1 ) { // colormapped (paletted) image - if (sz != 1 && sz != 9) goto errorEnd; // colortype 1 demands image type 1 or 9 - stbi__skip(s,4); // skip index of first colormap entry and number of entries - sz = stbi__get8(s); // check bits per palette color entry - if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; - stbi__skip(s,4); // skip image x and y origin - } else { // "normal" image w/o colormap - if ( (sz != 2) && (sz != 3) && (sz != 10) && (sz != 11) ) goto errorEnd; // only RGB or grey allowed, +/- RLE - stbi__skip(s,9); // skip colormap specification and image x/y origin - } - if ( stbi__get16le(s) < 1 ) goto errorEnd; // test width - if ( stbi__get16le(s) < 1 ) goto errorEnd; // test height - sz = stbi__get8(s); // bits per pixel - if ( (tga_color_type == 1) && (sz != 8) && (sz != 16) ) goto errorEnd; // for colormapped images, bpp is size of an index - if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; - - res = 1; // if we got this far, everything's good and we can return 1 instead of 0 - -errorEnd: - stbi__rewind(s); - return res; -} - -// read 16bit value and convert to 24bit RGB -static void stbi__tga_read_rgb16(stbi__context *s, stbi_uc* out) -{ - stbi__uint16 px = (stbi__uint16)stbi__get16le(s); - stbi__uint16 fiveBitMask = 31; - // we have 3 channels with 5bits each - int r = (px >> 10) & fiveBitMask; - int g = (px >> 5) & fiveBitMask; - int b = px & fiveBitMask; - // Note that this saves the data in RGB(A) order, so it doesn't need to be swapped later - out[0] = (stbi_uc)((r * 255)/31); - out[1] = (stbi_uc)((g * 255)/31); - out[2] = (stbi_uc)((b * 255)/31); - - // some people claim that the most significant bit might be used for alpha - // (possibly if an alpha-bit is set in the "image descriptor byte") - // but that only made 16bit test images completely translucent.. - // so let's treat all 15 and 16bit TGAs as RGB with no alpha. -} - -static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) -{ - // read in the TGA header stuff - int tga_offset = stbi__get8(s); - int tga_indexed = stbi__get8(s); - int tga_image_type = stbi__get8(s); - int tga_is_RLE = 0; - int tga_palette_start = stbi__get16le(s); - int tga_palette_len = stbi__get16le(s); - int tga_palette_bits = stbi__get8(s); - int tga_x_origin = stbi__get16le(s); - int tga_y_origin = stbi__get16le(s); - int tga_width = stbi__get16le(s); - int tga_height = stbi__get16le(s); - int tga_bits_per_pixel = stbi__get8(s); - int tga_comp, tga_rgb16=0; - int tga_inverted = stbi__get8(s); - // int tga_alpha_bits = tga_inverted & 15; // the 4 lowest bits - unused (useless?) - // image data - unsigned char *tga_data; - unsigned char *tga_palette = NULL; - int i, j; - unsigned char raw_data[4] = {0}; - int RLE_count = 0; - int RLE_repeating = 0; - int read_next_pixel = 1; - STBI_NOTUSED(ri); - STBI_NOTUSED(tga_x_origin); // @TODO - STBI_NOTUSED(tga_y_origin); // @TODO - - if (tga_height > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); - if (tga_width > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); - - // do a tiny bit of precessing - if ( tga_image_type >= 8 ) - { - tga_image_type -= 8; - tga_is_RLE = 1; - } - tga_inverted = 1 - ((tga_inverted >> 5) & 1); - - // If I'm paletted, then I'll use the number of bits from the palette - if ( tga_indexed ) tga_comp = stbi__tga_get_comp(tga_palette_bits, 0, &tga_rgb16); - else tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3), &tga_rgb16); - - if(!tga_comp) // shouldn't really happen, stbi__tga_test() should have ensured basic consistency - return stbi__errpuc("bad format", "Can't find out TGA pixelformat"); - - // tga info - *x = tga_width; - *y = tga_height; - if (comp) *comp = tga_comp; - - if (!stbi__mad3sizes_valid(tga_width, tga_height, tga_comp, 0)) - return stbi__errpuc("too large", "Corrupt TGA"); - - tga_data = (unsigned char*)stbi__malloc_mad3(tga_width, tga_height, tga_comp, 0); - if (!tga_data) return stbi__errpuc("outofmem", "Out of memory"); - - // skip to the data's starting position (offset usually = 0) - stbi__skip(s, tga_offset ); - - if ( !tga_indexed && !tga_is_RLE && !tga_rgb16 ) { - for (i=0; i < tga_height; ++i) { - int row = tga_inverted ? tga_height -i - 1 : i; - stbi_uc *tga_row = tga_data + row*tga_width*tga_comp; - stbi__getn(s, tga_row, tga_width * tga_comp); - } - } else { - // do I need to load a palette? - if ( tga_indexed) - { - if (tga_palette_len == 0) { /* you have to have at least one entry! */ - STBI_FREE(tga_data); - return stbi__errpuc("bad palette", "Corrupt TGA"); - } - - // any data to skip? (offset usually = 0) - stbi__skip(s, tga_palette_start ); - // load the palette - tga_palette = (unsigned char*)stbi__malloc_mad2(tga_palette_len, tga_comp, 0); - if (!tga_palette) { - STBI_FREE(tga_data); - return stbi__errpuc("outofmem", "Out of memory"); - } - if (tga_rgb16) { - stbi_uc *pal_entry = tga_palette; - STBI_ASSERT(tga_comp == STBI_rgb); - for (i=0; i < tga_palette_len; ++i) { - stbi__tga_read_rgb16(s, pal_entry); - pal_entry += tga_comp; - } - } else if (!stbi__getn(s, tga_palette, tga_palette_len * tga_comp)) { - STBI_FREE(tga_data); - STBI_FREE(tga_palette); - return stbi__errpuc("bad palette", "Corrupt TGA"); - } - } - // load the data - for (i=0; i < tga_width * tga_height; ++i) - { - // if I'm in RLE mode, do I need to get a RLE stbi__pngchunk? - if ( tga_is_RLE ) - { - if ( RLE_count == 0 ) - { - // yep, get the next byte as a RLE command - int RLE_cmd = stbi__get8(s); - RLE_count = 1 + (RLE_cmd & 127); - RLE_repeating = RLE_cmd >> 7; - read_next_pixel = 1; - } else if ( !RLE_repeating ) - { - read_next_pixel = 1; - } - } else - { - read_next_pixel = 1; - } - // OK, if I need to read a pixel, do it now - if ( read_next_pixel ) - { - // load however much data we did have - if ( tga_indexed ) - { - // read in index, then perform the lookup - int pal_idx = (tga_bits_per_pixel == 8) ? stbi__get8(s) : stbi__get16le(s); - if ( pal_idx >= tga_palette_len ) { - // invalid index - pal_idx = 0; - } - pal_idx *= tga_comp; - for (j = 0; j < tga_comp; ++j) { - raw_data[j] = tga_palette[pal_idx+j]; - } - } else if(tga_rgb16) { - STBI_ASSERT(tga_comp == STBI_rgb); - stbi__tga_read_rgb16(s, raw_data); - } else { - // read in the data raw - for (j = 0; j < tga_comp; ++j) { - raw_data[j] = stbi__get8(s); - } - } - // clear the reading flag for the next pixel - read_next_pixel = 0; - } // end of reading a pixel - - // copy data - for (j = 0; j < tga_comp; ++j) - tga_data[i*tga_comp+j] = raw_data[j]; - - // in case we're in RLE mode, keep counting down - --RLE_count; - } - // do I need to invert the image? - if ( tga_inverted ) - { - for (j = 0; j*2 < tga_height; ++j) - { - int index1 = j * tga_width * tga_comp; - int index2 = (tga_height - 1 - j) * tga_width * tga_comp; - for (i = tga_width * tga_comp; i > 0; --i) - { - unsigned char temp = tga_data[index1]; - tga_data[index1] = tga_data[index2]; - tga_data[index2] = temp; - ++index1; - ++index2; - } - } - } - // clear my palette, if I had one - if ( tga_palette != NULL ) - { - STBI_FREE( tga_palette ); - } - } - - // swap RGB - if the source data was RGB16, it already is in the right order - if (tga_comp >= 3 && !tga_rgb16) - { - unsigned char* tga_pixel = tga_data; - for (i=0; i < tga_width * tga_height; ++i) - { - unsigned char temp = tga_pixel[0]; - tga_pixel[0] = tga_pixel[2]; - tga_pixel[2] = temp; - tga_pixel += tga_comp; - } - } - - // convert to target component count - if (req_comp && req_comp != tga_comp) - tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height); - - // the things I do to get rid of an error message, and yet keep - // Microsoft's C compilers happy... [8^( - tga_palette_start = tga_palette_len = tga_palette_bits = - tga_x_origin = tga_y_origin = 0; - STBI_NOTUSED(tga_palette_start); - // OK, done - return tga_data; -} -#endif - -// ************************************************************************************************* -// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB - -#ifndef STBI_NO_PSD -static int stbi__psd_test(stbi__context *s) -{ - int r = (stbi__get32be(s) == 0x38425053); - stbi__rewind(s); - return r; -} - -static int stbi__psd_decode_rle(stbi__context *s, stbi_uc *p, int pixelCount) -{ - int count, nleft, len; - - count = 0; - while ((nleft = pixelCount - count) > 0) { - len = stbi__get8(s); - if (len == 128) { - // No-op. - } else if (len < 128) { - // Copy next len+1 bytes literally. - len++; - if (len > nleft) return 0; // corrupt data - count += len; - while (len) { - *p = stbi__get8(s); - p += 4; - len--; - } - } else if (len > 128) { - stbi_uc val; - // Next -len+1 bytes in the dest are replicated from next source byte. - // (Interpret len as a negative 8-bit int.) - len = 257 - len; - if (len > nleft) return 0; // corrupt data - val = stbi__get8(s); - count += len; - while (len) { - *p = val; - p += 4; - len--; - } - } - } - - return 1; -} - -static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) -{ - int pixelCount; - int channelCount, compression; - int channel, i; - int bitdepth; - int w,h; - stbi_uc *out; - STBI_NOTUSED(ri); - - // Check identifier - if (stbi__get32be(s) != 0x38425053) // "8BPS" - return stbi__errpuc("not PSD", "Corrupt PSD image"); - - // Check file type version. - if (stbi__get16be(s) != 1) - return stbi__errpuc("wrong version", "Unsupported version of PSD image"); - - // Skip 6 reserved bytes. - stbi__skip(s, 6 ); - - // Read the number of channels (R, G, B, A, etc). - channelCount = stbi__get16be(s); - if (channelCount < 0 || channelCount > 16) - return stbi__errpuc("wrong channel count", "Unsupported number of channels in PSD image"); - - // Read the rows and columns of the image. - h = stbi__get32be(s); - w = stbi__get32be(s); - - if (h > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); - if (w > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); - - // Make sure the depth is 8 bits. - bitdepth = stbi__get16be(s); - if (bitdepth != 8 && bitdepth != 16) - return stbi__errpuc("unsupported bit depth", "PSD bit depth is not 8 or 16 bit"); - - // Make sure the color mode is RGB. - // Valid options are: - // 0: Bitmap - // 1: Grayscale - // 2: Indexed color - // 3: RGB color - // 4: CMYK color - // 7: Multichannel - // 8: Duotone - // 9: Lab color - if (stbi__get16be(s) != 3) - return stbi__errpuc("wrong color format", "PSD is not in RGB color format"); - - // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.) - stbi__skip(s,stbi__get32be(s) ); - - // Skip the image resources. (resolution, pen tool paths, etc) - stbi__skip(s, stbi__get32be(s) ); - - // Skip the reserved data. - stbi__skip(s, stbi__get32be(s) ); - - // Find out if the data is compressed. - // Known values: - // 0: no compression - // 1: RLE compressed - compression = stbi__get16be(s); - if (compression > 1) - return stbi__errpuc("bad compression", "PSD has an unknown compression format"); - - // Check size - if (!stbi__mad3sizes_valid(4, w, h, 0)) - return stbi__errpuc("too large", "Corrupt PSD"); - - // Create the destination image. - - if (!compression && bitdepth == 16 && bpc == 16) { - out = (stbi_uc *) stbi__malloc_mad3(8, w, h, 0); - ri->bits_per_channel = 16; - } else - out = (stbi_uc *) stbi__malloc(4 * w*h); - - if (!out) return stbi__errpuc("outofmem", "Out of memory"); - pixelCount = w*h; - - // Initialize the data to zero. - //memset( out, 0, pixelCount * 4 ); - - // Finally, the image data. - if (compression) { - // RLE as used by .PSD and .TIFF - // Loop until you get the number of unpacked bytes you are expecting: - // Read the next source byte into n. - // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally. - // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times. - // Else if n is 128, noop. - // Endloop - - // The RLE-compressed data is preceded by a 2-byte data count for each row in the data, - // which we're going to just skip. - stbi__skip(s, h * channelCount * 2 ); - - // Read the RLE data by channel. - for (channel = 0; channel < 4; channel++) { - stbi_uc *p; - - p = out+channel; - if (channel >= channelCount) { - // Fill this channel with default data. - for (i = 0; i < pixelCount; i++, p += 4) - *p = (channel == 3 ? 255 : 0); - } else { - // Read the RLE data. - if (!stbi__psd_decode_rle(s, p, pixelCount)) { - STBI_FREE(out); - return stbi__errpuc("corrupt", "bad RLE data"); - } - } - } - - } else { - // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...) - // where each channel consists of an 8-bit (or 16-bit) value for each pixel in the image. - - // Read the data by channel. - for (channel = 0; channel < 4; channel++) { - if (channel >= channelCount) { - // Fill this channel with default data. - if (bitdepth == 16 && bpc == 16) { - stbi__uint16 *q = ((stbi__uint16 *) out) + channel; - stbi__uint16 val = channel == 3 ? 65535 : 0; - for (i = 0; i < pixelCount; i++, q += 4) - *q = val; - } else { - stbi_uc *p = out+channel; - stbi_uc val = channel == 3 ? 255 : 0; - for (i = 0; i < pixelCount; i++, p += 4) - *p = val; - } - } else { - if (ri->bits_per_channel == 16) { // output bpc - stbi__uint16 *q = ((stbi__uint16 *) out) + channel; - for (i = 0; i < pixelCount; i++, q += 4) - *q = (stbi__uint16) stbi__get16be(s); - } else { - stbi_uc *p = out+channel; - if (bitdepth == 16) { // input bpc - for (i = 0; i < pixelCount; i++, p += 4) - *p = (stbi_uc) (stbi__get16be(s) >> 8); - } else { - for (i = 0; i < pixelCount; i++, p += 4) - *p = stbi__get8(s); - } - } - } - } - } - - // remove weird white matte from PSD - if (channelCount >= 4) { - if (ri->bits_per_channel == 16) { - for (i=0; i < w*h; ++i) { - stbi__uint16 *pixel = (stbi__uint16 *) out + 4*i; - if (pixel[3] != 0 && pixel[3] != 65535) { - float a = pixel[3] / 65535.0f; - float ra = 1.0f / a; - float inv_a = 65535.0f * (1 - ra); - pixel[0] = (stbi__uint16) (pixel[0]*ra + inv_a); - pixel[1] = (stbi__uint16) (pixel[1]*ra + inv_a); - pixel[2] = (stbi__uint16) (pixel[2]*ra + inv_a); - } - } - } else { - for (i=0; i < w*h; ++i) { - unsigned char *pixel = out + 4*i; - if (pixel[3] != 0 && pixel[3] != 255) { - float a = pixel[3] / 255.0f; - float ra = 1.0f / a; - float inv_a = 255.0f * (1 - ra); - pixel[0] = (unsigned char) (pixel[0]*ra + inv_a); - pixel[1] = (unsigned char) (pixel[1]*ra + inv_a); - pixel[2] = (unsigned char) (pixel[2]*ra + inv_a); - } - } - } - } - - // convert to desired output format - if (req_comp && req_comp != 4) { - if (ri->bits_per_channel == 16) - out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, 4, req_comp, w, h); - else - out = stbi__convert_format(out, 4, req_comp, w, h); - if (out == NULL) return out; // stbi__convert_format frees input on failure - } - - if (comp) *comp = 4; - *y = h; - *x = w; - - return out; -} -#endif - -// ************************************************************************************************* -// Softimage PIC loader -// by Tom Seddon -// -// See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format -// See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/ - -#ifndef STBI_NO_PIC -static int stbi__pic_is4(stbi__context *s,const char *str) -{ - int i; - for (i=0; i<4; ++i) - if (stbi__get8(s) != (stbi_uc)str[i]) - return 0; - - return 1; -} - -static int stbi__pic_test_core(stbi__context *s) -{ - int i; - - if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) - return 0; - - for(i=0;i<84;++i) - stbi__get8(s); - - if (!stbi__pic_is4(s,"PICT")) - return 0; - - return 1; -} - -typedef struct -{ - stbi_uc size,type,channel; -} stbi__pic_packet; - -static stbi_uc *stbi__readval(stbi__context *s, int channel, stbi_uc *dest) -{ - int mask=0x80, i; - - for (i=0; i<4; ++i, mask>>=1) { - if (channel & mask) { - if (stbi__at_eof(s)) return stbi__errpuc("bad file","PIC file too short"); - dest[i]=stbi__get8(s); - } - } - - return dest; -} - -static void stbi__copyval(int channel,stbi_uc *dest,const stbi_uc *src) -{ - int mask=0x80,i; - - for (i=0;i<4; ++i, mask>>=1) - if (channel&mask) - dest[i]=src[i]; -} - -static stbi_uc *stbi__pic_load_core(stbi__context *s,int width,int height,int *comp, stbi_uc *result) -{ - int act_comp=0,num_packets=0,y,chained; - stbi__pic_packet packets[10]; - - // this will (should...) cater for even some bizarre stuff like having data - // for the same channel in multiple packets. - do { - stbi__pic_packet *packet; - - if (num_packets==sizeof(packets)/sizeof(packets[0])) - return stbi__errpuc("bad format","too many packets"); - - packet = &packets[num_packets++]; - - chained = stbi__get8(s); - packet->size = stbi__get8(s); - packet->type = stbi__get8(s); - packet->channel = stbi__get8(s); - - act_comp |= packet->channel; - - if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (reading packets)"); - if (packet->size != 8) return stbi__errpuc("bad format","packet isn't 8bpp"); - } while (chained); - - *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel? - - for(y=0; ytype) { - default: - return stbi__errpuc("bad format","packet has bad compression type"); - - case 0: {//uncompressed - int x; - - for(x=0;xchannel,dest)) - return 0; - break; - } - - case 1://Pure RLE - { - int left=width, i; - - while (left>0) { - stbi_uc count,value[4]; - - count=stbi__get8(s); - if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pure read count)"); - - if (count > left) - count = (stbi_uc) left; - - if (!stbi__readval(s,packet->channel,value)) return 0; - - for(i=0; ichannel,dest,value); - left -= count; - } - } - break; - - case 2: {//Mixed RLE - int left=width; - while (left>0) { - int count = stbi__get8(s), i; - if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (mixed read count)"); - - if (count >= 128) { // Repeated - stbi_uc value[4]; - - if (count==128) - count = stbi__get16be(s); - else - count -= 127; - if (count > left) - return stbi__errpuc("bad file","scanline overrun"); - - if (!stbi__readval(s,packet->channel,value)) - return 0; - - for(i=0;ichannel,dest,value); - } else { // Raw - ++count; - if (count>left) return stbi__errpuc("bad file","scanline overrun"); - - for(i=0;ichannel,dest)) - return 0; - } - left-=count; - } - break; - } - } - } - } - - return result; -} - -static void *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_comp, stbi__result_info *ri) -{ - stbi_uc *result; - int i, x,y, internal_comp; - STBI_NOTUSED(ri); - - if (!comp) comp = &internal_comp; - - for (i=0; i<92; ++i) - stbi__get8(s); - - x = stbi__get16be(s); - y = stbi__get16be(s); - - if (y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); - if (x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); - - if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pic header)"); - if (!stbi__mad3sizes_valid(x, y, 4, 0)) return stbi__errpuc("too large", "PIC image too large to decode"); - - stbi__get32be(s); //skip `ratio' - stbi__get16be(s); //skip `fields' - stbi__get16be(s); //skip `pad' - - // intermediate buffer is RGBA - result = (stbi_uc *) stbi__malloc_mad3(x, y, 4, 0); - memset(result, 0xff, x*y*4); - - if (!stbi__pic_load_core(s,x,y,comp, result)) { - STBI_FREE(result); - result=0; - } - *px = x; - *py = y; - if (req_comp == 0) req_comp = *comp; - result=stbi__convert_format(result,4,req_comp,x,y); - - return result; -} - -static int stbi__pic_test(stbi__context *s) -{ - int r = stbi__pic_test_core(s); - stbi__rewind(s); - return r; -} -#endif - -// ************************************************************************************************* -// GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb - -#ifndef STBI_NO_GIF -typedef struct -{ - stbi__int16 prefix; - stbi_uc first; - stbi_uc suffix; -} stbi__gif_lzw; - -typedef struct -{ - int w,h; - stbi_uc *out; // output buffer (always 4 components) - stbi_uc *background; // The current "background" as far as a gif is concerned - stbi_uc *history; - int flags, bgindex, ratio, transparent, eflags; - stbi_uc pal[256][4]; - stbi_uc lpal[256][4]; - stbi__gif_lzw codes[8192]; - stbi_uc *color_table; - int parse, step; - int lflags; - int start_x, start_y; - int max_x, max_y; - int cur_x, cur_y; - int line_size; - int delay; -} stbi__gif; - -static int stbi__gif_test_raw(stbi__context *s) -{ - int sz; - if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return 0; - sz = stbi__get8(s); - if (sz != '9' && sz != '7') return 0; - if (stbi__get8(s) != 'a') return 0; - return 1; -} - -static int stbi__gif_test(stbi__context *s) -{ - int r = stbi__gif_test_raw(s); - stbi__rewind(s); - return r; -} - -static void stbi__gif_parse_colortable(stbi__context *s, stbi_uc pal[256][4], int num_entries, int transp) -{ - int i; - for (i=0; i < num_entries; ++i) { - pal[i][2] = stbi__get8(s); - pal[i][1] = stbi__get8(s); - pal[i][0] = stbi__get8(s); - pal[i][3] = transp == i ? 0 : 255; - } -} - -static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_info) -{ - stbi_uc version; - if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') - return stbi__err("not GIF", "Corrupt GIF"); - - version = stbi__get8(s); - if (version != '7' && version != '9') return stbi__err("not GIF", "Corrupt GIF"); - if (stbi__get8(s) != 'a') return stbi__err("not GIF", "Corrupt GIF"); - - stbi__g_failure_reason = ""; - g->w = stbi__get16le(s); - g->h = stbi__get16le(s); - g->flags = stbi__get8(s); - g->bgindex = stbi__get8(s); - g->ratio = stbi__get8(s); - g->transparent = -1; - - if (g->w > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); - if (g->h > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); - - if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments - - if (is_info) return 1; - - if (g->flags & 0x80) - stbi__gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1); - - return 1; -} - -static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp) -{ - stbi__gif* g = (stbi__gif*) stbi__malloc(sizeof(stbi__gif)); - if (!stbi__gif_header(s, g, comp, 1)) { - STBI_FREE(g); - stbi__rewind( s ); - return 0; - } - if (x) *x = g->w; - if (y) *y = g->h; - STBI_FREE(g); - return 1; -} - -static void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code) -{ - stbi_uc *p, *c; - int idx; - - // recurse to decode the prefixes, since the linked-list is backwards, - // and working backwards through an interleaved image would be nasty - if (g->codes[code].prefix >= 0) - stbi__out_gif_code(g, g->codes[code].prefix); - - if (g->cur_y >= g->max_y) return; - - idx = g->cur_x + g->cur_y; - p = &g->out[idx]; - g->history[idx / 4] = 1; - - c = &g->color_table[g->codes[code].suffix * 4]; - if (c[3] > 128) { // don't render transparent pixels; - p[0] = c[2]; - p[1] = c[1]; - p[2] = c[0]; - p[3] = c[3]; - } - g->cur_x += 4; - - if (g->cur_x >= g->max_x) { - g->cur_x = g->start_x; - g->cur_y += g->step; - - while (g->cur_y >= g->max_y && g->parse > 0) { - g->step = (1 << g->parse) * g->line_size; - g->cur_y = g->start_y + (g->step >> 1); - --g->parse; - } - } -} - -static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g) -{ - stbi_uc lzw_cs; - stbi__int32 len, init_code; - stbi__uint32 first; - stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear; - stbi__gif_lzw *p; - - lzw_cs = stbi__get8(s); - if (lzw_cs > 12) return NULL; - clear = 1 << lzw_cs; - first = 1; - codesize = lzw_cs + 1; - codemask = (1 << codesize) - 1; - bits = 0; - valid_bits = 0; - for (init_code = 0; init_code < clear; init_code++) { - g->codes[init_code].prefix = -1; - g->codes[init_code].first = (stbi_uc) init_code; - g->codes[init_code].suffix = (stbi_uc) init_code; - } - - // support no starting clear code - avail = clear+2; - oldcode = -1; - - len = 0; - for(;;) { - if (valid_bits < codesize) { - if (len == 0) { - len = stbi__get8(s); // start new block - if (len == 0) - return g->out; - } - --len; - bits |= (stbi__int32) stbi__get8(s) << valid_bits; - valid_bits += 8; - } else { - stbi__int32 code = bits & codemask; - bits >>= codesize; - valid_bits -= codesize; - // @OPTIMIZE: is there some way we can accelerate the non-clear path? - if (code == clear) { // clear code - codesize = lzw_cs + 1; - codemask = (1 << codesize) - 1; - avail = clear + 2; - oldcode = -1; - first = 0; - } else if (code == clear + 1) { // end of stream code - stbi__skip(s, len); - while ((len = stbi__get8(s)) > 0) - stbi__skip(s,len); - return g->out; - } else if (code <= avail) { - if (first) { - return stbi__errpuc("no clear code", "Corrupt GIF"); - } - - if (oldcode >= 0) { - p = &g->codes[avail++]; - if (avail > 8192) { - return stbi__errpuc("too many codes", "Corrupt GIF"); - } - - p->prefix = (stbi__int16) oldcode; - p->first = g->codes[oldcode].first; - p->suffix = (code == avail) ? p->first : g->codes[code].first; - } else if (code == avail) - return stbi__errpuc("illegal code in raster", "Corrupt GIF"); - - stbi__out_gif_code(g, (stbi__uint16) code); - - if ((avail & codemask) == 0 && avail <= 0x0FFF) { - codesize++; - codemask = (1 << codesize) - 1; - } - - oldcode = code; - } else { - return stbi__errpuc("illegal code in raster", "Corrupt GIF"); - } - } - } -} - -// this function is designed to support animated gifs, although stb_image doesn't support it -// two back is the image from two frames ago, used for a very specific disposal format -static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp, stbi_uc *two_back) -{ - int dispose; - int first_frame; - int pi; - int pcount; - STBI_NOTUSED(req_comp); - - // on first frame, any non-written pixels get the background colour (non-transparent) - first_frame = 0; - if (g->out == 0) { - if (!stbi__gif_header(s, g, comp,0)) return 0; // stbi__g_failure_reason set by stbi__gif_header - if (!stbi__mad3sizes_valid(4, g->w, g->h, 0)) - return stbi__errpuc("too large", "GIF image is too large"); - pcount = g->w * g->h; - g->out = (stbi_uc *) stbi__malloc(4 * pcount); - g->background = (stbi_uc *) stbi__malloc(4 * pcount); - g->history = (stbi_uc *) stbi__malloc(pcount); - if (!g->out || !g->background || !g->history) - return stbi__errpuc("outofmem", "Out of memory"); - - // image is treated as "transparent" at the start - ie, nothing overwrites the current background; - // background colour is only used for pixels that are not rendered first frame, after that "background" - // color refers to the color that was there the previous frame. - memset(g->out, 0x00, 4 * pcount); - memset(g->background, 0x00, 4 * pcount); // state of the background (starts transparent) - memset(g->history, 0x00, pcount); // pixels that were affected previous frame - first_frame = 1; - } else { - // second frame - how do we dispose of the previous one? - dispose = (g->eflags & 0x1C) >> 2; - pcount = g->w * g->h; - - if ((dispose == 3) && (two_back == 0)) { - dispose = 2; // if I don't have an image to revert back to, default to the old background - } - - if (dispose == 3) { // use previous graphic - for (pi = 0; pi < pcount; ++pi) { - if (g->history[pi]) { - memcpy( &g->out[pi * 4], &two_back[pi * 4], 4 ); - } - } - } else if (dispose == 2) { - // restore what was changed last frame to background before that frame; - for (pi = 0; pi < pcount; ++pi) { - if (g->history[pi]) { - memcpy( &g->out[pi * 4], &g->background[pi * 4], 4 ); - } - } - } else { - // This is a non-disposal case eithe way, so just - // leave the pixels as is, and they will become the new background - // 1: do not dispose - // 0: not specified. - } - - // background is what out is after the undoing of the previou frame; - memcpy( g->background, g->out, 4 * g->w * g->h ); - } - - // clear my history; - memset( g->history, 0x00, g->w * g->h ); // pixels that were affected previous frame - - for (;;) { - int tag = stbi__get8(s); - switch (tag) { - case 0x2C: /* Image Descriptor */ - { - stbi__int32 x, y, w, h; - stbi_uc *o; - - x = stbi__get16le(s); - y = stbi__get16le(s); - w = stbi__get16le(s); - h = stbi__get16le(s); - if (((x + w) > (g->w)) || ((y + h) > (g->h))) - return stbi__errpuc("bad Image Descriptor", "Corrupt GIF"); - - g->line_size = g->w * 4; - g->start_x = x * 4; - g->start_y = y * g->line_size; - g->max_x = g->start_x + w * 4; - g->max_y = g->start_y + h * g->line_size; - g->cur_x = g->start_x; - g->cur_y = g->start_y; - - // if the width of the specified rectangle is 0, that means - // we may not see *any* pixels or the image is malformed; - // to make sure this is caught, move the current y down to - // max_y (which is what out_gif_code checks). - if (w == 0) - g->cur_y = g->max_y; - - g->lflags = stbi__get8(s); - - if (g->lflags & 0x40) { - g->step = 8 * g->line_size; // first interlaced spacing - g->parse = 3; - } else { - g->step = g->line_size; - g->parse = 0; - } - - if (g->lflags & 0x80) { - stbi__gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1); - g->color_table = (stbi_uc *) g->lpal; - } else if (g->flags & 0x80) { - g->color_table = (stbi_uc *) g->pal; - } else - return stbi__errpuc("missing color table", "Corrupt GIF"); - - o = stbi__process_gif_raster(s, g); - if (!o) return NULL; - - // if this was the first frame, - pcount = g->w * g->h; - if (first_frame && (g->bgindex > 0)) { - // if first frame, any pixel not drawn to gets the background color - for (pi = 0; pi < pcount; ++pi) { - if (g->history[pi] == 0) { - g->pal[g->bgindex][3] = 255; // just in case it was made transparent, undo that; It will be reset next frame if need be; - memcpy( &g->out[pi * 4], &g->pal[g->bgindex], 4 ); - } - } - } - - return o; - } - - case 0x21: // Comment Extension. - { - int len; - int ext = stbi__get8(s); - if (ext == 0xF9) { // Graphic Control Extension. - len = stbi__get8(s); - if (len == 4) { - g->eflags = stbi__get8(s); - g->delay = 10 * stbi__get16le(s); // delay - 1/100th of a second, saving as 1/1000ths. - - // unset old transparent - if (g->transparent >= 0) { - g->pal[g->transparent][3] = 255; - } - if (g->eflags & 0x01) { - g->transparent = stbi__get8(s); - if (g->transparent >= 0) { - g->pal[g->transparent][3] = 0; - } - } else { - // don't need transparent - stbi__skip(s, 1); - g->transparent = -1; - } - } else { - stbi__skip(s, len); - break; - } - } - while ((len = stbi__get8(s)) != 0) { - stbi__skip(s, len); - } - break; - } - - case 0x3B: // gif stream termination code - return (stbi_uc *) s; // using '1' causes warning on some compilers - - default: - return stbi__errpuc("unknown code", "Corrupt GIF"); - } - } -} - -static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp) -{ - if (stbi__gif_test(s)) { - int layers = 0; - stbi_uc *u = 0; - stbi_uc *out = 0; - stbi_uc *two_back = 0; - stbi__gif g; - int stride; - int out_size = 0; - int delays_size = 0; - memset(&g, 0, sizeof(g)); - if (delays) { - *delays = 0; - } - - do { - u = stbi__gif_load_next(s, &g, comp, req_comp, two_back); - if (u == (stbi_uc *) s) u = 0; // end of animated gif marker - - if (u) { - *x = g.w; - *y = g.h; - ++layers; - stride = g.w * g.h * 4; - - if (out) { - void *tmp = (stbi_uc*) STBI_REALLOC_SIZED( out, out_size, layers * stride ); - if (NULL == tmp) { - STBI_FREE(g.out); - STBI_FREE(g.history); - STBI_FREE(g.background); - return stbi__errpuc("outofmem", "Out of memory"); - } - else { - out = (stbi_uc*) tmp; - out_size = layers * stride; - } - - if (delays) { - *delays = (int*) STBI_REALLOC_SIZED( *delays, delays_size, sizeof(int) * layers ); - delays_size = layers * sizeof(int); - } - } else { - out = (stbi_uc*)stbi__malloc( layers * stride ); - out_size = layers * stride; - if (delays) { - *delays = (int*) stbi__malloc( layers * sizeof(int) ); - delays_size = layers * sizeof(int); - } - } - memcpy( out + ((layers - 1) * stride), u, stride ); - if (layers >= 2) { - two_back = out - 2 * stride; - } - - if (delays) { - (*delays)[layers - 1U] = g.delay; - } - } - } while (u != 0); - - // free temp buffer; - STBI_FREE(g.out); - STBI_FREE(g.history); - STBI_FREE(g.background); - - // do the final conversion after loading everything; - if (req_comp && req_comp != 4) - out = stbi__convert_format(out, 4, req_comp, layers * g.w, g.h); - - *z = layers; - return out; - } else { - return stbi__errpuc("not GIF", "Image was not as a gif type."); - } -} - -static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) -{ - stbi_uc *u = 0; - stbi__gif g; - memset(&g, 0, sizeof(g)); - STBI_NOTUSED(ri); - - u = stbi__gif_load_next(s, &g, comp, req_comp, 0); - if (u == (stbi_uc *) s) u = 0; // end of animated gif marker - if (u) { - *x = g.w; - *y = g.h; - - // moved conversion to after successful load so that the same - // can be done for multiple frames. - if (req_comp && req_comp != 4) - u = stbi__convert_format(u, 4, req_comp, g.w, g.h); - } else if (g.out) { - // if there was an error and we allocated an image buffer, free it! - STBI_FREE(g.out); - } - - // free buffers needed for multiple frame loading; - STBI_FREE(g.history); - STBI_FREE(g.background); - - return u; -} - -static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp) -{ - return stbi__gif_info_raw(s,x,y,comp); -} -#endif - -// ************************************************************************************************* -// Radiance RGBE HDR loader -// originally by Nicolas Schulz -#ifndef STBI_NO_HDR -static int stbi__hdr_test_core(stbi__context *s, const char *signature) -{ - int i; - for (i=0; signature[i]; ++i) - if (stbi__get8(s) != signature[i]) - return 0; - stbi__rewind(s); - return 1; -} - -static int stbi__hdr_test(stbi__context* s) -{ - int r = stbi__hdr_test_core(s, "#?RADIANCE\n"); - stbi__rewind(s); - if(!r) { - r = stbi__hdr_test_core(s, "#?RGBE\n"); - stbi__rewind(s); - } - return r; -} - -#define STBI__HDR_BUFLEN 1024 -static char *stbi__hdr_gettoken(stbi__context *z, char *buffer) -{ - int len=0; - char c = '\0'; - - c = (char) stbi__get8(z); - - while (!stbi__at_eof(z) && c != '\n') { - buffer[len++] = c; - if (len == STBI__HDR_BUFLEN-1) { - // flush to end of line - while (!stbi__at_eof(z) && stbi__get8(z) != '\n') - ; - break; - } - c = (char) stbi__get8(z); - } - - buffer[len] = 0; - return buffer; -} - -static void stbi__hdr_convert(float *output, stbi_uc *input, int req_comp) -{ - if ( input[3] != 0 ) { - float f1; - // Exponent - f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8)); - if (req_comp <= 2) - output[0] = (input[0] + input[1] + input[2]) * f1 / 3; - else { - output[0] = input[0] * f1; - output[1] = input[1] * f1; - output[2] = input[2] * f1; - } - if (req_comp == 2) output[1] = 1; - if (req_comp == 4) output[3] = 1; - } else { - switch (req_comp) { - case 4: output[3] = 1; /* fallthrough */ - case 3: output[0] = output[1] = output[2] = 0; - break; - case 2: output[1] = 1; /* fallthrough */ - case 1: output[0] = 0; - break; - } - } -} - -static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) -{ - char buffer[STBI__HDR_BUFLEN]; - char *token; - int valid = 0; - int width, height; - stbi_uc *scanline; - float *hdr_data; - int len; - unsigned char count, value; - int i, j, k, c1,c2, z; - const char *headerToken; - STBI_NOTUSED(ri); - - // Check identifier - headerToken = stbi__hdr_gettoken(s,buffer); - if (strcmp(headerToken, "#?RADIANCE") != 0 && strcmp(headerToken, "#?RGBE") != 0) - return stbi__errpf("not HDR", "Corrupt HDR image"); - - // Parse header - for(;;) { - token = stbi__hdr_gettoken(s,buffer); - if (token[0] == 0) break; - if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; - } - - if (!valid) return stbi__errpf("unsupported format", "Unsupported HDR format"); - - // Parse width and height - // can't use sscanf() if we're not using stdio! - token = stbi__hdr_gettoken(s,buffer); - if (strncmp(token, "-Y ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); - token += 3; - height = (int) strtol(token, &token, 10); - while (*token == ' ') ++token; - if (strncmp(token, "+X ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); - token += 3; - width = (int) strtol(token, NULL, 10); - - if (height > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)"); - if (width > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)"); - - *x = width; - *y = height; - - if (comp) *comp = 3; - if (req_comp == 0) req_comp = 3; - - if (!stbi__mad4sizes_valid(width, height, req_comp, sizeof(float), 0)) - return stbi__errpf("too large", "HDR image is too large"); - - // Read data - hdr_data = (float *) stbi__malloc_mad4(width, height, req_comp, sizeof(float), 0); - if (!hdr_data) - return stbi__errpf("outofmem", "Out of memory"); - - // Load image data - // image data is stored as some number of sca - if ( width < 8 || width >= 32768) { - // Read flat data - for (j=0; j < height; ++j) { - for (i=0; i < width; ++i) { - stbi_uc rgbe[4]; - main_decode_loop: - stbi__getn(s, rgbe, 4); - stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp); - } - } - } else { - // Read RLE-encoded data - scanline = NULL; - - for (j = 0; j < height; ++j) { - c1 = stbi__get8(s); - c2 = stbi__get8(s); - len = stbi__get8(s); - if (c1 != 2 || c2 != 2 || (len & 0x80)) { - // not run-length encoded, so we have to actually use THIS data as a decoded - // pixel (note this can't be a valid pixel--one of RGB must be >= 128) - stbi_uc rgbe[4]; - rgbe[0] = (stbi_uc) c1; - rgbe[1] = (stbi_uc) c2; - rgbe[2] = (stbi_uc) len; - rgbe[3] = (stbi_uc) stbi__get8(s); - stbi__hdr_convert(hdr_data, rgbe, req_comp); - i = 1; - j = 0; - STBI_FREE(scanline); - goto main_decode_loop; // yes, this makes no sense - } - len <<= 8; - len |= stbi__get8(s); - if (len != width) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("invalid decoded scanline length", "corrupt HDR"); } - if (scanline == NULL) { - scanline = (stbi_uc *) stbi__malloc_mad2(width, 4, 0); - if (!scanline) { - STBI_FREE(hdr_data); - return stbi__errpf("outofmem", "Out of memory"); - } - } - - for (k = 0; k < 4; ++k) { - int nleft; - i = 0; - while ((nleft = width - i) > 0) { - count = stbi__get8(s); - if (count > 128) { - // Run - value = stbi__get8(s); - count -= 128; - if (count > nleft) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } - for (z = 0; z < count; ++z) - scanline[i++ * 4 + k] = value; - } else { - // Dump - if (count > nleft) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } - for (z = 0; z < count; ++z) - scanline[i++ * 4 + k] = stbi__get8(s); - } - } - } - for (i=0; i < width; ++i) - stbi__hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp); - } - if (scanline) - STBI_FREE(scanline); - } - - return hdr_data; -} - -static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp) -{ - char buffer[STBI__HDR_BUFLEN]; - char *token; - int valid = 0; - int dummy; - - if (!x) x = &dummy; - if (!y) y = &dummy; - if (!comp) comp = &dummy; - - if (stbi__hdr_test(s) == 0) { - stbi__rewind( s ); - return 0; - } - - for(;;) { - token = stbi__hdr_gettoken(s,buffer); - if (token[0] == 0) break; - if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; - } - - if (!valid) { - stbi__rewind( s ); - return 0; - } - token = stbi__hdr_gettoken(s,buffer); - if (strncmp(token, "-Y ", 3)) { - stbi__rewind( s ); - return 0; - } - token += 3; - *y = (int) strtol(token, &token, 10); - while (*token == ' ') ++token; - if (strncmp(token, "+X ", 3)) { - stbi__rewind( s ); - return 0; - } - token += 3; - *x = (int) strtol(token, NULL, 10); - *comp = 3; - return 1; -} -#endif // STBI_NO_HDR - -#ifndef STBI_NO_BMP -static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp) -{ - void *p; - stbi__bmp_data info; - - info.all_a = 255; - p = stbi__bmp_parse_header(s, &info); - stbi__rewind( s ); - if (p == NULL) - return 0; - if (x) *x = s->img_x; - if (y) *y = s->img_y; - if (comp) { - if (info.bpp == 24 && info.ma == 0xff000000) - *comp = 3; - else - *comp = info.ma ? 4 : 3; - } - return 1; -} -#endif - -#ifndef STBI_NO_PSD -static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp) -{ - int channelCount, dummy, depth; - if (!x) x = &dummy; - if (!y) y = &dummy; - if (!comp) comp = &dummy; - if (stbi__get32be(s) != 0x38425053) { - stbi__rewind( s ); - return 0; - } - if (stbi__get16be(s) != 1) { - stbi__rewind( s ); - return 0; - } - stbi__skip(s, 6); - channelCount = stbi__get16be(s); - if (channelCount < 0 || channelCount > 16) { - stbi__rewind( s ); - return 0; - } - *y = stbi__get32be(s); - *x = stbi__get32be(s); - depth = stbi__get16be(s); - if (depth != 8 && depth != 16) { - stbi__rewind( s ); - return 0; - } - if (stbi__get16be(s) != 3) { - stbi__rewind( s ); - return 0; - } - *comp = 4; - return 1; -} - -static int stbi__psd_is16(stbi__context *s) -{ - int channelCount, depth; - if (stbi__get32be(s) != 0x38425053) { - stbi__rewind( s ); - return 0; - } - if (stbi__get16be(s) != 1) { - stbi__rewind( s ); - return 0; - } - stbi__skip(s, 6); - channelCount = stbi__get16be(s); - if (channelCount < 0 || channelCount > 16) { - stbi__rewind( s ); - return 0; - } - (void) stbi__get32be(s); - (void) stbi__get32be(s); - depth = stbi__get16be(s); - if (depth != 16) { - stbi__rewind( s ); - return 0; - } - return 1; -} -#endif - -#ifndef STBI_NO_PIC -static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp) -{ - int act_comp=0,num_packets=0,chained,dummy; - stbi__pic_packet packets[10]; - - if (!x) x = &dummy; - if (!y) y = &dummy; - if (!comp) comp = &dummy; - - if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) { - stbi__rewind(s); - return 0; - } - - stbi__skip(s, 88); - - *x = stbi__get16be(s); - *y = stbi__get16be(s); - if (stbi__at_eof(s)) { - stbi__rewind( s); - return 0; - } - if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) { - stbi__rewind( s ); - return 0; - } - - stbi__skip(s, 8); - - do { - stbi__pic_packet *packet; - - if (num_packets==sizeof(packets)/sizeof(packets[0])) - return 0; - - packet = &packets[num_packets++]; - chained = stbi__get8(s); - packet->size = stbi__get8(s); - packet->type = stbi__get8(s); - packet->channel = stbi__get8(s); - act_comp |= packet->channel; - - if (stbi__at_eof(s)) { - stbi__rewind( s ); - return 0; - } - if (packet->size != 8) { - stbi__rewind( s ); - return 0; - } - } while (chained); - - *comp = (act_comp & 0x10 ? 4 : 3); - - return 1; -} -#endif - -// ************************************************************************************************* -// Portable Gray Map and Portable Pixel Map loader -// by Ken Miller -// -// PGM: http://netpbm.sourceforge.net/doc/pgm.html -// PPM: http://netpbm.sourceforge.net/doc/ppm.html -// -// Known limitations: -// Does not support comments in the header section -// Does not support ASCII image data (formats P2 and P3) -// Does not support 16-bit-per-channel - -#ifndef STBI_NO_PNM - -static int stbi__pnm_test(stbi__context *s) -{ - char p, t; - p = (char) stbi__get8(s); - t = (char) stbi__get8(s); - if (p != 'P' || (t != '5' && t != '6')) { - stbi__rewind( s ); - return 0; - } - return 1; -} - -static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) -{ - stbi_uc *out; - STBI_NOTUSED(ri); - - if (!stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n)) - return 0; - - if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); - if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); - - *x = s->img_x; - *y = s->img_y; - if (comp) *comp = s->img_n; - - if (!stbi__mad3sizes_valid(s->img_n, s->img_x, s->img_y, 0)) - return stbi__errpuc("too large", "PNM too large"); - - out = (stbi_uc *) stbi__malloc_mad3(s->img_n, s->img_x, s->img_y, 0); - if (!out) return stbi__errpuc("outofmem", "Out of memory"); - stbi__getn(s, out, s->img_n * s->img_x * s->img_y); - - if (req_comp && req_comp != s->img_n) { - out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y); - if (out == NULL) return out; // stbi__convert_format frees input on failure - } - return out; -} - -static int stbi__pnm_isspace(char c) -{ - return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r'; -} - -static void stbi__pnm_skip_whitespace(stbi__context *s, char *c) -{ - for (;;) { - while (!stbi__at_eof(s) && stbi__pnm_isspace(*c)) - *c = (char) stbi__get8(s); - - if (stbi__at_eof(s) || *c != '#') - break; - - while (!stbi__at_eof(s) && *c != '\n' && *c != '\r' ) - *c = (char) stbi__get8(s); - } -} - -static int stbi__pnm_isdigit(char c) -{ - return c >= '0' && c <= '9'; -} - -static int stbi__pnm_getinteger(stbi__context *s, char *c) -{ - int value = 0; - - while (!stbi__at_eof(s) && stbi__pnm_isdigit(*c)) { - value = value*10 + (*c - '0'); - *c = (char) stbi__get8(s); - } - - return value; -} - -static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp) -{ - int maxv, dummy; - char c, p, t; - - if (!x) x = &dummy; - if (!y) y = &dummy; - if (!comp) comp = &dummy; - - stbi__rewind(s); - - // Get identifier - p = (char) stbi__get8(s); - t = (char) stbi__get8(s); - if (p != 'P' || (t != '5' && t != '6')) { - stbi__rewind(s); - return 0; - } - - *comp = (t == '6') ? 3 : 1; // '5' is 1-component .pgm; '6' is 3-component .ppm - - c = (char) stbi__get8(s); - stbi__pnm_skip_whitespace(s, &c); - - *x = stbi__pnm_getinteger(s, &c); // read width - stbi__pnm_skip_whitespace(s, &c); - - *y = stbi__pnm_getinteger(s, &c); // read height - stbi__pnm_skip_whitespace(s, &c); - - maxv = stbi__pnm_getinteger(s, &c); // read max value - - if (maxv > 255) - return stbi__err("max value > 255", "PPM image not 8-bit"); - else - return 1; -} -#endif - -static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp) -{ - #ifndef STBI_NO_JPEG - if (stbi__jpeg_info(s, x, y, comp)) return 1; - #endif - - #ifndef STBI_NO_PNG - if (stbi__png_info(s, x, y, comp)) return 1; - #endif - - #ifndef STBI_NO_GIF - if (stbi__gif_info(s, x, y, comp)) return 1; - #endif - - #ifndef STBI_NO_BMP - if (stbi__bmp_info(s, x, y, comp)) return 1; - #endif - - #ifndef STBI_NO_PSD - if (stbi__psd_info(s, x, y, comp)) return 1; - #endif - - #ifndef STBI_NO_PIC - if (stbi__pic_info(s, x, y, comp)) return 1; - #endif - - #ifndef STBI_NO_PNM - if (stbi__pnm_info(s, x, y, comp)) return 1; - #endif - - #ifndef STBI_NO_HDR - if (stbi__hdr_info(s, x, y, comp)) return 1; - #endif - - // test tga last because it's a crappy test! - #ifndef STBI_NO_TGA - if (stbi__tga_info(s, x, y, comp)) - return 1; - #endif - return stbi__err("unknown image type", "Image not of any known type, or corrupt"); -} - -static int stbi__is_16_main(stbi__context *s) -{ - #ifndef STBI_NO_PNG - if (stbi__png_is16(s)) return 1; - #endif - - #ifndef STBI_NO_PSD - if (stbi__psd_is16(s)) return 1; - #endif - - return 0; -} - -#ifndef STBI_NO_STDIO -STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp) -{ - FILE *f = stbi__fopen(filename, "rb"); - int result; - if (!f) return stbi__err("can't fopen", "Unable to open file"); - result = stbi_info_from_file(f, x, y, comp); - fclose(f); - return result; -} - -STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp) -{ - int r; - stbi__context s; - long pos = ftell(f); - stbi__start_file(&s, f); - r = stbi__info_main(&s,x,y,comp); - fseek(f,pos,SEEK_SET); - return r; -} - -STBIDEF int stbi_is_16_bit(char const *filename) -{ - FILE *f = stbi__fopen(filename, "rb"); - int result; - if (!f) return stbi__err("can't fopen", "Unable to open file"); - result = stbi_is_16_bit_from_file(f); - fclose(f); - return result; -} - -STBIDEF int stbi_is_16_bit_from_file(FILE *f) -{ - int r; - stbi__context s; - long pos = ftell(f); - stbi__start_file(&s, f); - r = stbi__is_16_main(&s); - fseek(f,pos,SEEK_SET); - return r; -} -#endif // !STBI_NO_STDIO - -STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp) -{ - stbi__context s; - stbi__start_mem(&s,buffer,len); - return stbi__info_main(&s,x,y,comp); -} - -STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp) -{ - stbi__context s; - stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); - return stbi__info_main(&s,x,y,comp); -} - -STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len) -{ - stbi__context s; - stbi__start_mem(&s,buffer,len); - return stbi__is_16_main(&s); -} - -STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *c, void *user) -{ - stbi__context s; - stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); - return stbi__is_16_main(&s); -} - -#endif // STB_IMAGE_IMPLEMENTATION - -/* - revision history: - 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs - 2.19 (2018-02-11) fix warning - 2.18 (2018-01-30) fix warnings - 2.17 (2018-01-29) change sbti__shiftsigned to avoid clang -O2 bug - 1-bit BMP - *_is_16_bit api - avoid warnings - 2.16 (2017-07-23) all functions have 16-bit variants; - STBI_NO_STDIO works again; - compilation fixes; - fix rounding in unpremultiply; - optimize vertical flip; - disable raw_len validation; - documentation fixes - 2.15 (2017-03-18) fix png-1,2,4 bug; now all Imagenet JPGs decode; - warning fixes; disable run-time SSE detection on gcc; - uniform handling of optional "return" values; - thread-safe initialization of zlib tables - 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs - 2.13 (2016-11-29) add 16-bit API, only supported for PNG right now - 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes - 2.11 (2016-04-02) allocate large structures on the stack - remove white matting for transparent PSD - fix reported channel count for PNG & BMP - re-enable SSE2 in non-gcc 64-bit - support RGB-formatted JPEG - read 16-bit PNGs (only as 8-bit) - 2.10 (2016-01-22) avoid warning introduced in 2.09 by STBI_REALLOC_SIZED - 2.09 (2016-01-16) allow comments in PNM files - 16-bit-per-pixel TGA (not bit-per-component) - info() for TGA could break due to .hdr handling - info() for BMP to shares code instead of sloppy parse - can use STBI_REALLOC_SIZED if allocator doesn't support realloc - code cleanup - 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA - 2.07 (2015-09-13) fix compiler warnings - partial animated GIF support - limited 16-bpc PSD support - #ifdef unused functions - bug with < 92 byte PIC,PNM,HDR,TGA - 2.06 (2015-04-19) fix bug where PSD returns wrong '*comp' value - 2.05 (2015-04-19) fix bug in progressive JPEG handling, fix warning - 2.04 (2015-04-15) try to re-enable SIMD on MinGW 64-bit - 2.03 (2015-04-12) extra corruption checking (mmozeiko) - stbi_set_flip_vertically_on_load (nguillemot) - fix NEON support; fix mingw support - 2.02 (2015-01-19) fix incorrect assert, fix warning - 2.01 (2015-01-17) fix various warnings; suppress SIMD on gcc 32-bit without -msse2 - 2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG - 2.00 (2014-12-25) optimize JPG, including x86 SSE2 & NEON SIMD (ryg) - progressive JPEG (stb) - PGM/PPM support (Ken Miller) - STBI_MALLOC,STBI_REALLOC,STBI_FREE - GIF bugfix -- seemingly never worked - STBI_NO_*, STBI_ONLY_* - 1.48 (2014-12-14) fix incorrectly-named assert() - 1.47 (2014-12-14) 1/2/4-bit PNG support, both direct and paletted (Omar Cornut & stb) - optimize PNG (ryg) - fix bug in interlaced PNG with user-specified channel count (stb) - 1.46 (2014-08-26) - fix broken tRNS chunk (colorkey-style transparency) in non-paletted PNG - 1.45 (2014-08-16) - fix MSVC-ARM internal compiler error by wrapping malloc - 1.44 (2014-08-07) - various warning fixes from Ronny Chevalier - 1.43 (2014-07-15) - fix MSVC-only compiler problem in code changed in 1.42 - 1.42 (2014-07-09) - don't define _CRT_SECURE_NO_WARNINGS (affects user code) - fixes to stbi__cleanup_jpeg path - added STBI_ASSERT to avoid requiring assert.h - 1.41 (2014-06-25) - fix search&replace from 1.36 that messed up comments/error messages - 1.40 (2014-06-22) - fix gcc struct-initialization warning - 1.39 (2014-06-15) - fix to TGA optimization when req_comp != number of components in TGA; - fix to GIF loading because BMP wasn't rewinding (whoops, no GIFs in my test suite) - add support for BMP version 5 (more ignored fields) - 1.38 (2014-06-06) - suppress MSVC warnings on integer casts truncating values - fix accidental rename of 'skip' field of I/O - 1.37 (2014-06-04) - remove duplicate typedef - 1.36 (2014-06-03) - convert to header file single-file library - if de-iphone isn't set, load iphone images color-swapped instead of returning NULL - 1.35 (2014-05-27) - various warnings - fix broken STBI_SIMD path - fix bug where stbi_load_from_file no longer left file pointer in correct place - fix broken non-easy path for 32-bit BMP (possibly never used) - TGA optimization by Arseny Kapoulkine - 1.34 (unknown) - use STBI_NOTUSED in stbi__resample_row_generic(), fix one more leak in tga failure case - 1.33 (2011-07-14) - make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements - 1.32 (2011-07-13) - support for "info" function for all supported filetypes (SpartanJ) - 1.31 (2011-06-20) - a few more leak fixes, bug in PNG handling (SpartanJ) - 1.30 (2011-06-11) - added ability to load files via callbacks to accomidate custom input streams (Ben Wenger) - removed deprecated format-specific test/load functions - removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway - error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha) - fix inefficiency in decoding 32-bit BMP (David Woo) - 1.29 (2010-08-16) - various warning fixes from Aurelien Pocheville - 1.28 (2010-08-01) - fix bug in GIF palette transparency (SpartanJ) - 1.27 (2010-08-01) - cast-to-stbi_uc to fix warnings - 1.26 (2010-07-24) - fix bug in file buffering for PNG reported by SpartanJ - 1.25 (2010-07-17) - refix trans_data warning (Won Chun) - 1.24 (2010-07-12) - perf improvements reading from files on platforms with lock-heavy fgetc() - minor perf improvements for jpeg - deprecated type-specific functions so we'll get feedback if they're needed - attempt to fix trans_data warning (Won Chun) - 1.23 fixed bug in iPhone support - 1.22 (2010-07-10) - removed image *writing* support - stbi_info support from Jetro Lauha - GIF support from Jean-Marc Lienher - iPhone PNG-extensions from James Brown - warning-fixes from Nicolas Schulz and Janez Zemva (i.stbi__err. Janez (U+017D)emva) - 1.21 fix use of 'stbi_uc' in header (reported by jon blow) - 1.20 added support for Softimage PIC, by Tom Seddon - 1.19 bug in interlaced PNG corruption check (found by ryg) - 1.18 (2008-08-02) - fix a threading bug (local mutable static) - 1.17 support interlaced PNG - 1.16 major bugfix - stbi__convert_format converted one too many pixels - 1.15 initialize some fields for thread safety - 1.14 fix threadsafe conversion bug - header-file-only version (#define STBI_HEADER_FILE_ONLY before including) - 1.13 threadsafe - 1.12 const qualifiers in the API - 1.11 Support installable IDCT, colorspace conversion routines - 1.10 Fixes for 64-bit (don't use "unsigned long") - optimized upsampling by Fabian "ryg" Giesen - 1.09 Fix format-conversion for PSD code (bad global variables!) - 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz - 1.07 attempt to fix C++ warning/errors again - 1.06 attempt to fix C++ warning/errors again - 1.05 fix TGA loading to return correct *comp and use good luminance calc - 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free - 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR - 1.02 support for (subset of) HDR files, float interface for preferred access to them - 1.01 fix bug: possible bug in handling right-side up bmps... not sure - fix bug: the stbi__bmp_load() and stbi__tga_load() functions didn't work at all - 1.00 interface to zlib that skips zlib header - 0.99 correct handling of alpha in palette - 0.98 TGA loader by lonesock; dynamically add loaders (untested) - 0.97 jpeg errors on too large a file; also catch another malloc failure - 0.96 fix detection of invalid v value - particleman@mollyrocket forum - 0.95 during header scan, seek to markers in case of padding - 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same - 0.93 handle jpegtran output; verbose errors - 0.92 read 4,8,16,24,32-bit BMP files of several formats - 0.91 output 24-bit Windows 3.0 BMP files - 0.90 fix a few more warnings; bump version number to approach 1.0 - 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd - 0.60 fix compiling as c++ - 0.59 fix warnings: merge Dave Moore's -Wall fixes - 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian - 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available - 0.56 fix bug: zlib uncompressed mode len vs. nlen - 0.55 fix bug: restart_interval not initialized to 0 - 0.54 allow NULL for 'int *comp' - 0.53 fix bug in png 3->4; speedup png decoding - 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments - 0.51 obey req_comp requests, 1-component jpegs return as 1-component, - on 'test' only check type, not whether we support this variant - 0.50 (2006-11-19) - first released version -*/ - - -/* ------------------------------------------------------------------------------- -This software is available under 2 licenses -- choose whichever you prefer. ------------------------------------------------------------------------------- -ALTERNATIVE A - MIT License -Copyright (c) 2017 Sean Barrett -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. ------------------------------------------------------------------------------- -ALTERNATIVE B - Public Domain (www.unlicense.org) -This is free and unencumbered software released into the public domain. -Anyone is free to copy, modify, publish, use, compile, sell, or distribute this -software, either in source code form or as a compiled binary, for any purpose, -commercial or non-commercial, and by any means. -In jurisdictions that recognize copyright laws, the author or authors of this -software dedicate any and all copyright interest in the software to the public -domain. We make this dedication for the benefit of the public at large and to -the detriment of our heirs and successors. We intend this dedication to be an -overt act of relinquishment in perpetuity of all present and future rights to -this software under copyright law. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------- -*/ diff --git a/gfx/doc/extern/2013SiggraphPresentationsNotes-26915738.pdf b/gfx/doc/extern/2013SiggraphPresentationsNotes-26915738.pdf deleted file mode 100644 index 989658e..0000000 Binary files a/gfx/doc/extern/2013SiggraphPresentationsNotes-26915738.pdf and /dev/null differ diff --git a/gfx/doc/extern/Scene Graph - CSE 167.pdf b/gfx/doc/extern/Scene Graph - CSE 167.pdf deleted file mode 100644 index 5fbbb10..0000000 Binary files a/gfx/doc/extern/Scene Graph - CSE 167.pdf and /dev/null differ diff --git a/gfx/doc/gfx.png b/gfx/doc/gfx.png deleted file mode 100644 index e64f6e1..0000000 Binary files a/gfx/doc/gfx.png and /dev/null differ diff --git a/gfx/doc/gfx.txt b/gfx/doc/gfx.txt deleted file mode 100644 index d3ce01b..0000000 --- a/gfx/doc/gfx.txt +++ /dev/null @@ -1,10 +0,0 @@ -@startuml - -class Gfx { - -} - -Gfx --> Render -Gfx *-- Scene - -@enduml diff --git a/gfx/doc/gltfOverview-2.0.0b.png b/gfx/doc/gltfOverview-2.0.0b.png deleted file mode 100644 index 6a5bb61..0000000 Binary files a/gfx/doc/gltfOverview-2.0.0b.png and /dev/null differ diff --git a/gfx/doc/pipeline.png b/gfx/doc/pipeline.png deleted file mode 100644 index 426f39e..0000000 Binary files a/gfx/doc/pipeline.png and /dev/null differ diff --git a/gfx/doc/pipeline.txt b/gfx/doc/pipeline.txt deleted file mode 100644 index 51523d6..0000000 --- a/gfx/doc/pipeline.txt +++ /dev/null @@ -1,16 +0,0 @@ -@startuml - -class RenderPipeline { - -} - -RenderPipeline *-- RenderPass - -class RenderPass { - +clear colour -} - -RenderPass --> Shader -RenderPass o-- RenderTarget - -@enduml diff --git a/gfx/doc/renderer.png b/gfx/doc/renderer.png deleted file mode 100644 index d0516b0..0000000 Binary files a/gfx/doc/renderer.png and /dev/null differ diff --git a/gfx/doc/renderer.txt b/gfx/doc/renderer.txt deleted file mode 100644 index 90b18f8..0000000 --- a/gfx/doc/renderer.txt +++ /dev/null @@ -1,18 +0,0 @@ -@startuml - -class Render { - -} - -Render *-- RenderPipeline -Render --> Assets - -class Assets { - -} - -Assets *-- Shader -Assets *-- Geometry -Assets *-- Texture - -@enduml diff --git a/gfx/doc/scene.png b/gfx/doc/scene.png deleted file mode 100644 index 85d2447..0000000 Binary files a/gfx/doc/scene.png and /dev/null differ diff --git a/gfx/doc/scene.txt b/gfx/doc/scene.txt deleted file mode 100644 index a771488..0000000 --- a/gfx/doc/scene.txt +++ /dev/null @@ -1,109 +0,0 @@ -@startuml - -class Scene { - -} - -Scene *-- Node - -class Camera { - -} - -class Node { - + transform -} - -Node *-- AnimationObject -Node *-- Object -Node *-- Light -Node *-- Camera -Node *-- Node - -class AnimationObject { - -} - -AnimationObject *-- Animation -AnimationObject --> AnimationState -AnimationObject --> Skeleton - -class AnimationState { - + time - + current_animation - + pose -} - -class Animation { - + name -} - -Animation *-- Keyframe - -class Keyframe { - + time - + transforms -} - -class Skeleton { - + joints -} - -class Object { - + transform -} - -Object *-- Mesh - -class Mesh { - -} - -Mesh --> BoundingVolume -Mesh --> Geometry -Mesh --> Material -Mesh --> Shader - -class Geometry { - + positions - + normals - + texcoords - + indices -} - -class BoundingVolume { - -} - -class Material { - + shader params -} - -Material o-- Texture - -class Shader { - + uniforms -} - -Shader --> VertexShader -Shader --> FragmentShader - -class VertexShader { - + pos - + normal - + texcoords - + Modelview - + Projection -} - -class FragmentShader { - + lights - + textures -} - -class Texture { - + pixels - + format -} - -@enduml diff --git a/gfx/include/gfx/asset.h b/gfx/include/gfx/asset.h deleted file mode 100644 index caf40c1..0000000 --- a/gfx/include/gfx/asset.h +++ /dev/null @@ -1,99 +0,0 @@ -/* Asset Management */ -#pragma once - -#include - -#include - -typedef struct Gfx Gfx; -typedef struct Model Model; -typedef struct ShaderProgram ShaderProgram; -typedef struct Texture Texture; - -/// Describes where the asset comes from. -typedef enum AssetOrigin { - AssetFromMemory, - AssetFromFile, -} AssetOrigin; - -/// Describes a texture's colour space. -typedef enum TextureColourSpace { - sRGB, // The most likely default. - LinearColourSpace, -} TextureColourSpace; - -/// Describes a command to load a texture. -typedef struct LoadTextureCmd { - AssetOrigin origin; - enum { LoadTexture, LoadCubemap } type; - TextureColourSpace colour_space; - TextureFiltering filtering; - TextureWrapping wrap; - bool mipmaps; - union { - // A single texture. - struct { - union { - struct { - mstring filepath; - }; - struct { - const void* data; - size_t size_bytes; - }; - }; - } texture; - // Cubemap texture. - struct { - union { - struct { - mstring filepath_pos_x; - mstring filepath_neg_x; - mstring filepath_pos_y; - mstring filepath_neg_y; - mstring filepath_pos_z; - mstring filepath_neg_z; - } filepaths; - struct { - const void* data_pos_x; - const void* data_neg_x; - const void* data_pos_y; - const void* data_neg_y; - const void* data_pos_z; - const void* data_neg_z; - } buffers; - }; - } cubemap; - } data; -} LoadTextureCmd; - -/// Describes a command to load a model. -/// -/// |shader| is an optional shader program assigned to the loaded model objects. -/// If no shader is given, a Cook-Torrance shader based on the object's -/// characteristics (presence of normals, tangents, etc) is assigned. -typedef struct LoadModelCmd { - AssetOrigin origin; - union { - struct { - mstring filepath; - }; - struct { - const void* data; - size_t size_bytes; - }; - }; - ShaderProgram* shader; -} LoadModelCmd; - -/// Load a model. -/// -/// For animated models, this function returns a (shallow) clone of the model -/// that is safe to mutate. For static models, this returns the original model -/// in the cache. -/// -/// Currently only supports the GLTF format. -Model* gfx_load_model(Gfx*, const LoadModelCmd*); - -/// Load a texture. -const Texture* gfx_load_texture(Gfx*, const LoadTextureCmd*); diff --git a/gfx/include/gfx/core.h b/gfx/include/gfx/core.h deleted file mode 100644 index 44509c9..0000000 --- a/gfx/include/gfx/core.h +++ /dev/null @@ -1,501 +0,0 @@ -/// Render Backend. -/// -/// The Render Backend creates and owns graphics objects and performs low-level -/// rendering operations. -#pragma once - -#include "sizes.h" - -#include -#include -#include -#include - -#include - -#include -#include - -// Implementation objects. -typedef struct Buffer Buffer; -typedef struct FrameBuffer FrameBuffer; -typedef struct Geometry Geometry; -typedef struct GfxCore GfxCore; -typedef struct RenderBuffer RenderBuffer; -typedef struct Shader Shader; -typedef struct ShaderProgram ShaderProgram; -typedef struct Texture Texture; - -/// Data type for vertex indices. -/// Might need U32 for bigger models. -typedef uint8_t VertexIndex8; -typedef uint16_t VertexIndex16; -typedef uint16_t VertexCount; - -/// Geometry drawing modes. -typedef enum PrimitiveType { - Triangles, - TriangleFan, - TriangleStrip -} PrimitiveType; - -/// Buffer usage. -typedef enum BufferUsage { BufferStatic, BufferDynamic } BufferUsage; - -/// Buffer type. -typedef enum BufferType { - BufferUntyped, - Buffer2d, - Buffer3d, - Buffer4d, - BufferFloat, - BufferU8, - BufferU16 -} BufferType; - -/// Buffer data descriptor. -typedef struct BufferDataDesc { - union { - const void* data; - const vec2* vec2s; - const vec3* vec3s; - const float* floats; - const uint8_t* u8s; - const uint16_t* u16s; - }; - size_t count; -} BufferDataDesc; - -/// Buffer descriptor. -/// -/// 'count' is the number of elements in the array. For untyped buffers, this is -/// the size in bytes of the 'data' array. For other types, it is the number of -/// vec2s, vec3s, etc. in the corresponding array. -/// -/// The data pointers can also be null. In such a case, a buffer of the given -/// size is created with its contents uninitialized. -/// -/// TODO: Think about typed buffers (Buffer, Buffer2d, Buffer3d, BufferU8, etc). -/// Typed buffers don't work well with interleaved vertex attributes. Not sure -/// this is really worth it. -typedef struct BufferDesc { - BufferUsage usage; - BufferType type; - BufferDataDesc data; -} BufferDesc; - -/// A buffer view for vertex data (attributes or indices). -/// Either 'data' or 'buffer' must be set. -#define MAKE_BUFFER_VIEW(NAME, TYPE) \ - typedef struct NAME { \ - const TYPE* data; \ - Buffer* buffer; \ - size_t offset_bytes; \ - size_t size_bytes; \ - size_t stride_bytes; \ - } NAME; - -/// A buffer view for untyped data. -MAKE_BUFFER_VIEW(BufferView, void) - -/// A buffer view for 2D vectors. -MAKE_BUFFER_VIEW(BufferView2d, vec2) - -/// A buffer view for 3D vectors. -MAKE_BUFFER_VIEW(BufferView3d, vec3) - -/// A buffer view for 4D vectors. -MAKE_BUFFER_VIEW(BufferView4d, vec4) - -/// A buffer view for floats. -MAKE_BUFFER_VIEW(BufferViewFloat, float) - -/// A buffer view for 8-bit unsigned integers. -MAKE_BUFFER_VIEW(BufferViewU8, uint8_t) - -/// A buffer view for 16-bit unsigned integers. -MAKE_BUFFER_VIEW(BufferViewU16, uint16_t) - -/// A buffer view for 8-bit vertex indices. -MAKE_BUFFER_VIEW(BufferViewIdx8, uint16_t) - -/// A buffer view for 16-bit vertex indices. -MAKE_BUFFER_VIEW(BufferViewIdx16, uint16_t) - -/// Describes a piece of geometry. -/// -/// Buffer views may point to either already-existing GPU buffers or to data in -/// host memory. -/// -/// If the buffer views do not already point to GPU buffers, GPU buffers are -/// created for the geometry. The 'buffer_usage' field specifies the usage for -/// the created buffers. Use BufferStatic for static geometry and BufferDynamic -/// for dynamic geometry. -/// -/// Currently we support only up to 16-bit vertex indices. Might have to change -/// this to support a larger variety of 3D models. -typedef struct GeometryDesc { - BufferView2d positions2d; - BufferView3d positions3d; - BufferView3d normals; - BufferView4d tangents; - BufferView2d texcoords; - struct { - BufferViewU8 u8; - BufferViewU16 u16; - } joints; // uvec4. - struct { - BufferViewFloat floats; - BufferViewU8 u8; - BufferViewU16 u16; - } weights; // vec4 or uvec4. - BufferViewIdx8 indices8; - BufferViewIdx16 indices16; - VertexCount num_verts; - size_t num_indices; - PrimitiveType type; - BufferUsage buffer_usage; - aabb3 aabb; -} GeometryDesc; - -/// Shader compiler define. -typedef struct ShaderCompilerDefine { - sstring name; - sstring value; -} ShaderCompilerDefine; - -/// Shader types. -typedef enum { VertexShader, FragmentShader } ShaderType; - -/// Describes a shader. -typedef struct ShaderDesc { - ShaderType type; - const char* code; - ShaderCompilerDefine defines[GFX_MAX_SHADER_COMPILER_DEFINES]; - size_t num_defines; -} ShaderDesc; - -/// Describes a shader program. -typedef struct ShaderProgramDesc { - const Shader* vertex_shader; - const Shader* fragment_shader; -} ShaderProgramDesc; - -/// Shader uniform type. -typedef enum { - UniformFloat, - UniformMat4, - UniformTexture, - UniformVec3, - UniformVec4, - UniformMat4Array -} UniformType; - -/// Shader uniform. -/// -/// For uniform arrays, the client must ensure that the array is still valid by -/// the time the uniform data is passed to the GPU. -typedef struct ShaderUniform { - sstring name; - UniformType type; - union { - const Texture* texture; - mat4 mat4; - vec3 vec3; - vec4 vec4; - float scalar; - struct { - size_t count; - union { - const mat4* values; - }; - } array; - } value; -} ShaderUniform; - -/// Texture dimension. -typedef enum { Texture2D, TextureCubeMap } TextureDimension; - -/// Texture data format. -typedef enum { - TextureDepth, - TextureRG16, - TextureRG16F, - TextureRGB8, - TextureR11G11B10F, - TextureRGBA8, - TextureSRGB8, - TextureSRGBA8 -} TextureFormat; - -/// Texture filtering. -typedef enum { NearestFiltering, LinearFiltering } TextureFiltering; - -/// Texture wrap mode. -typedef enum { Repeat, ClampToEdge } TextureWrapping; - -/// Cubemap faces. -typedef enum { - CubemapFacePosX, - CubemapFaceNegX, - CubemapFacePosY, - CubemapFaceNegY, - CubemapFacePosZ, - CubemapFaceNegZ -} CubemapFace; - -/// Texture data descriptor. -typedef struct TextureDataDesc { - union { - const void* pixels; - struct { - const void* pixels_pos_x; - const void* pixels_neg_x; - const void* pixels_pos_y; - const void* pixels_neg_y; - const void* pixels_pos_z; - const void* pixels_neg_z; - } cubemap; - }; -} TextureDataDesc; - -/// Describes a texture. -typedef struct TextureDesc { - int width; - int height; - int depth; // Not used until 3D textures are exposed. - TextureDimension dimension; - TextureFormat format; - TextureFiltering filtering; - TextureWrapping wrap; - bool mipmaps; - TextureDataDesc data; -} TextureDesc; - -/// Describes a renderbuffer. -typedef struct RenderBufferDesc { - int width; - int height; - TextureFormat texture_format; -} RenderBufferDesc; - -/// Framebuffer attachment type. -typedef enum FrameBufferAttachmentType { - FrameBufferNoAttachment, - FrameBufferTexture, - FrameBufferCubemapTexture, - FrameBufferRenderBuffer -} FrameBufferAttachmentType; - -/// Describes a framebuffer attachment. -typedef struct FrameBufferAttachment { - FrameBufferAttachmentType type; - union { - struct { - Texture* texture; - int mip_level; - } texture; - struct { - Texture* texture; - int mip_level; - CubemapFace face; - } cubemap; - RenderBuffer* renderbuffer; - }; -} FrameBufferAttachment; - -/// Describes a framebuffer. -typedef struct FrameBufferDesc { - FrameBufferAttachment colour; - FrameBufferAttachment depth; -} FrameBufferDesc; - -// ----------------------------------------------------------------------------- -// Render commands. -// ----------------------------------------------------------------------------- - -/// Start a new frame. -void gfx_start_frame(GfxCore*); - -/// End a frame. -void gfx_end_frame(GfxCore*); - -/// Set the render backend's viewport dimensions. -void gfx_set_viewport(GfxCore*, int x, int y, int width, int height); - -/// Get the render backend's viewport dimensions. -void gfx_get_viewport(GfxCore*, int* x, int* y, int* width, int* height); - -/// Clear the viewport. -void gfx_clear(GfxCore*, vec4 colour); - -/// Set blending state. -void gfx_set_blending(GfxCore*, bool enable); - -/// Set depth mask. -void gfx_set_depth_mask(GfxCore*, bool enable); - -/// Set cull mode. -void gfx_set_culling(GfxCore*, bool enable); - -/// Set polygon offset. -void gfx_set_polygon_offset(GfxCore*, float scale, float bias); - -/// Reset the polygon offset. -void gfx_reset_polygon_offset(GfxCore*); - -// ----------------------------------------------------------------------------- -// Buffers. -// ----------------------------------------------------------------------------- - -/// Create a buffer from raw data. -Buffer* gfx_make_buffer(GfxCore*, const BufferDesc*); - -/// Destroy the buffer. -void gfx_destroy_buffer(GfxCore*, Buffer**); - -/// Update the buffer's data. -void gfx_update_buffer(Buffer*, const BufferDataDesc*); - -// ----------------------------------------------------------------------------- -// Geometry. -// ----------------------------------------------------------------------------- - -/// Create geometry. -Geometry* gfx_make_geometry(GfxCore*, const GeometryDesc*); - -/// Destroy the geometry. -void gfx_destroy_geometry(GfxCore*, Geometry**); - -/// Upload new vertex data for the geometry. -/// -/// This is similar to gfx_make_geometry(), but the geometry need not be -/// entirely specified. -/// -/// Only the vertex attributes, vertex count, and index count set in the -/// descriptor are updated. Index data, primitive type, and other properties of -/// the geometry are not updated. -/// -/// New data must be given as arrays in host memory. That is, the buffer views -/// in the descriptor must point to CPU arrays, not GPU buffers. -/// -/// Note that the descriptor cannot specify a larger vertex or index count than -/// what the geometry was created with. If the geometry size or any other -/// attribute not handled by this update function needs to be changed, then a -/// new geometry must be created. -void gfx_update_geometry(Geometry*, const GeometryDesc*); - -/// Render the geometry. -void gfx_render_geometry(const Geometry*); - -/// Return the geometry's bounding box. -aabb3 gfx_get_geometry_aabb(const Geometry*); - -// ----------------------------------------------------------------------------- -// Textures. -// ----------------------------------------------------------------------------- - -/// Create a texture. -Texture* gfx_make_texture(GfxCore*, const TextureDesc*); - -/// Destroy the texture. -void gfx_destroy_texture(GfxCore*, Texture**); - -/// Update the texture. -void gfx_update_texture(Texture*, const TextureDataDesc*); - -// ----------------------------------------------------------------------------- -// Renderbuffers. -// ----------------------------------------------------------------------------- - -/// Create a renderbuffer. -RenderBuffer* gfx_make_renderbuffer(GfxCore*, const RenderBufferDesc*); - -/// Destroy the renderbuffer. -void gfx_destroy_renderbuffer(GfxCore*, RenderBuffer**); - -// ----------------------------------------------------------------------------- -// Framebuffers. -// ----------------------------------------------------------------------------- - -/// Create a framebuffer. -FrameBuffer* gfx_make_framebuffer(GfxCore*, const FrameBufferDesc*); - -/// Destroy the framebuffer. -void gfx_destroy_framebuffer(GfxCore*, FrameBuffer**); - -/// Attach a colour buffer to the framebuffer. -bool gfx_framebuffer_attach_colour(FrameBuffer*, const FrameBufferAttachment*); - -/// Attach a depth buffer to the framebuffer. -bool gfx_framebuffer_attach_depth(FrameBuffer*, const FrameBufferAttachment*); - -/// Activate the framebuffer. -/// Subsequent draw calls write to this framebuffer. -void gfx_activate_framebuffer(const FrameBuffer*); - -/// Deactivate the framebuffer. -/// Subsequent draw calls write to the default framebuffer. -void gfx_deactivate_framebuffer(const FrameBuffer*); - -/// Set the framebuffer's viewport. -/// This function should be called every time the framebuffer is activated. -void gfx_framebuffer_set_viewport( - FrameBuffer*, int x, int y, int width, int height); - -// ----------------------------------------------------------------------------- -// Shaders. -// ----------------------------------------------------------------------------- - -/// Create a shader. -Shader* gfx_make_shader(GfxCore*, const ShaderDesc*); - -/// Destroy the shader. -void gfx_destroy_shader(GfxCore*, Shader**); - -/// Create a shader program. -ShaderProgram* gfx_make_shader_program(GfxCore*, const ShaderProgramDesc*); - -/// Destroy the shader program. -void gfx_destroy_shader_program(GfxCore*, ShaderProgram**); - -/// Activate the shader program. -void gfx_activate_shader_program(const ShaderProgram*); - -/// Deactivate the shader program. -void gfx_deactivate_shader_program(const ShaderProgram*); - -/// Apply the shader program's uniform variables. -/// -/// Calls to gfx_set_XYZ_uniform save the values of the uniform variables in the -/// graphics library. By calling this function, those values are passed on to -/// the graphics driver for rendering. -/// -/// This function should be called after setting all of the uniform variables -/// and prior to issuing a draw call. -void gfx_apply_uniforms(const ShaderProgram*); - -/// Set the texture uniform. -/// Has no effect if the shader does not contain the given uniform. -void gfx_set_texture_uniform(ShaderProgram*, const char* name, const Texture*); - -/// Set the matrix uniform. -/// Has no effect if the shader does not contain the given uniform. -void gfx_set_mat4_uniform(ShaderProgram*, const char* name, const mat4*); - -/// Set the vec3 uniform. -/// Has no effect if the shader does not contain the given uniform. -void gfx_set_vec3_uniform(ShaderProgram*, const char* name, vec3); - -/// Set the vec4 uniform. -/// Has no effect if the shader does not contain the given uniform. -void gfx_set_vec4_uniform(ShaderProgram*, const char* name, vec4); - -/// Set the float uniform. -/// Has no effect if the shader does not contain the given uniform. -void gfx_set_float_uniform(ShaderProgram*, const char* name, float value); - -/// Set the matrix array uniform. -/// Has no effect if the shader does not contain the given uniform. -void gfx_set_mat4_array_uniform( - ShaderProgram*, const char* name, const mat4*, size_t count); diff --git a/gfx/include/gfx/gfx.h b/gfx/include/gfx/gfx.h deleted file mode 100644 index 7c670a5..0000000 --- a/gfx/include/gfx/gfx.h +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once - -typedef struct AssetCache AssetCache; -typedef struct GfxCore GfxCore; -typedef struct ImmRenderer ImmRenderer; -typedef struct Renderer Renderer; - -typedef struct Gfx Gfx; - -/// Create a new graphics system, -Gfx* gfx_init(void); - -/// Destroy the graphics system. -void gfx_destroy(Gfx**); - -/// Get the render backend. -GfxCore* gfx_get_core(Gfx*); - -/// Get the renderer. -Renderer* gfx_get_renderer(Gfx*); - -/// Get the immediate mode renderer. -ImmRenderer* gfx_get_imm_renderer(Gfx*); - -/// Get the asset cache. -AssetCache* gfx_get_asset_cache(Gfx*); - -/// Remove unused resources from the scene (meshes, materials). -/// TODO: need to think about the interface for scene_purge(). Maybe this -/// should be gfx_purge() and take a list of Scenes? -// void gfx_purge(Scene*); diff --git a/gfx/include/gfx/renderer.h b/gfx/include/gfx/renderer.h deleted file mode 100644 index 2a4ada1..0000000 --- a/gfx/include/gfx/renderer.h +++ /dev/null @@ -1,104 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include - -typedef struct GfxCore GfxCore; -typedef struct Scene Scene; -typedef struct SceneCamera SceneCamera; - -typedef struct ImmRenderer ImmRenderer; -typedef struct Renderer Renderer; - -// ----------------------------------------------------------------------------- -// Main Renderer. -// ----------------------------------------------------------------------------- - -typedef enum RenderSceneMode { - RenderDefault, - RenderDebug, - RenderNormals, - RenderNormalMappedNormals, - RenderTangents -} RenderSceneMode; - -typedef struct RenderSceneParams { - RenderSceneMode mode; - const Scene* scene; - const SceneCamera* camera; -} RenderSceneParams; - -/// Render the scene. -void gfx_render_scene(Renderer*, const RenderSceneParams*); - -/// Update the scene. -void gfx_update(Scene*, const SceneCamera*, R t); - -// ----------------------------------------------------------------------------- -// Immediate Mode Renderer. -// ----------------------------------------------------------------------------- - -/// Prepare the graphics systems for immediate-mode rendering. -/// -/// Call this before issuing any immediate-mode rendering draws. -void gfx_imm_start(ImmRenderer*); - -/// End immediate mode rendering. -/// -/// Call this after issuing immediate-mode rendering draws and before swapping -/// buffers. -void gfx_imm_end(ImmRenderer*); - -/// Draw a set of triangles. -void gfx_imm_draw_triangles(ImmRenderer*, const vec3[], size_t num_triangles); - -/// Draw a triangle. -void gfx_imm_draw_triangle(ImmRenderer*, const vec3[3]); - -/// Draw a bounding box. -void gfx_imm_draw_aabb2(ImmRenderer*, aabb2); - -/// Draw a bounding box. -void gfx_imm_draw_aabb3(ImmRenderer*, aabb3); - -/// Draw a box. -/// -/// The vertices must be given in the following order: -/// -/// 7 ----- 6 -/// / /| -/// 3 ----- 2 | -/// | | | -/// | 4 ----- 5 -/// |/ |/ -/// 0 ----- 1 -void gfx_imm_draw_box3(ImmRenderer* renderer, const vec3 vertices[8]); - -/// Set the camera. -void gfx_imm_set_camera(ImmRenderer*, const Camera*); - -/// Load an identity model matrix. Clears the matrix stack. -void gfx_imm_load_identity(ImmRenderer* renderer); - -/// Push the given matrix to the matrix stack. -void gfx_imm_push_matrix(ImmRenderer* renderer, const mat4* matrix); - -/// Pop the top of the matrix stack. -void gfx_imm_pop_matrix(ImmRenderer* renderer); - -/// Push a translation matrix to the matrix stack. -void gfx_imm_translate(ImmRenderer* renderer, vec3 offset); - -/// Set the model matrix. Clears the matrix stack. -void gfx_imm_set_model_matrix(ImmRenderer*, const mat4*); - -/// Set the view-projection matrix. -void gfx_imm_set_view_projection_matrix(ImmRenderer*, const mat4*); - -/// Set the render colour. -void gfx_imm_set_colour(ImmRenderer*, vec4 colour); diff --git a/gfx/include/gfx/scene.h b/gfx/include/gfx/scene.h deleted file mode 100644 index abcaa70..0000000 --- a/gfx/include/gfx/scene.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include diff --git a/gfx/include/gfx/scene/animation.h b/gfx/include/gfx/scene/animation.h deleted file mode 100644 index d95b895..0000000 --- a/gfx/include/gfx/scene/animation.h +++ /dev/null @@ -1,142 +0,0 @@ -#pragma once - -#include "node.h" -#include "object.h" -#include - -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -typedef struct Buffer Buffer; -typedef struct SceneNode SceneNode; - -typedef struct Anima Anima; -typedef struct Joint Joint; -typedef struct Skeleton Skeleton; - -/// Index type used to store relative indices into arrays. -typedef uint16_t joint_idx; - -/// Index value denoting no index. -static const joint_idx INDEX_NONE = (joint_idx)-1; - -typedef struct Box { - vec3 vertices[8]; -} Box; - -/// Joint descriptor. -typedef struct JointDesc { - joint_idx parent; /// Parent Joint; index into Anima's joints. - mat4 inv_bind_matrix; /// Transforms the mesh into the joint's local space. - aabb3 box; /// Bounding box. -} JointDesc; - -/// Skeleton descriptor. -typedef struct SkeletonDesc { - size_t num_joints; - joint_idx joints[GFX_MAX_NUM_JOINTS]; /// Indices into Anima's joints array. -} SkeletonDesc; - -/// Animation interpolation mode. -typedef enum AnimationInterpolation { - StepInterpolation, - LinearInterpolation, - CubicSplineInterpolation -} AnimationInterpolation; - -/// The kind of transformation applied by a Channel. -typedef enum ChannelType { - RotationChannel, - ScaleChannel, - TranslationChannel, - WeightsChannel -} ChannelType; - -/// Animation keyframe descriptor. -/// -/// The arrays should have as many entries as 'num_joints' in the SkeletonDesc. -typedef struct KeyframeDesc { - R time; // Start time in [0, end animation time] - union { - vec3 translation; - quat rotation; - }; -} KeyframeDesc; - -/// Animation channel descriptor. -typedef struct ChannelDesc { - joint_idx target; /// Index into Anima's joints array. - ChannelType type; - AnimationInterpolation interpolation; - size_t num_keyframes; - KeyframeDesc keyframes[GFX_MAX_NUM_KEYFRAMES]; -} ChannelDesc; - -/// Animation descriptor. -typedef struct AnimationDesc { - // TODO: Store a name hash for faster comparisons. - sstring name; // Animation name. Required for playback. - size_t num_channels; // Number of channels. - ChannelDesc channels[GFX_MAX_NUM_CHANNELS]; -} AnimationDesc; - -/// Anima object descriptor. -/// -/// The last joint of the joints array at index 'num_joints - 1' must be the -/// root of all skeletons; specifically, the root of all joints that otherwise -/// would have no parent (a skeleton need not have its own root and can be a set -/// of disjoint node hierarchies). -typedef struct AnimaDesc { - size_t num_skeletons; - size_t num_animations; - size_t num_joints; - SkeletonDesc skeletons[GFX_MAX_NUM_SKELETONS]; - AnimationDesc animations[GFX_MAX_NUM_ANIMATIONS]; - JointDesc joints[GFX_MAX_NUM_JOINTS]; -} AnimaDesc; - -/// Animation play settings. -typedef struct AnimationPlaySettings { - const char* name; // Animation name. - bool loop; // Whether to loop the animation or just play once. - // TODO: Add animation speed. -} AnimationPlaySettings; - -/// Create an anima object. -Anima* gfx_make_anima(const AnimaDesc*); - -/// Destroy the anima. -void gfx_destroy_anima(Anima**); - -/// Play an animation (sets the current animation). -bool gfx_play_animation(Anima*, const AnimationPlaySettings*); - -/// Update the current animation. -void gfx_update_animation(Anima*, R t); - -/// Stop the current animation. -void gfx_stop_animation(Anima*); - -/// Return the anima's ith skeleton. -const Skeleton* gfx_get_anima_skeleton(const Anima* anima, size_t i); - -/// Return the number of joints in the skeleton. -size_t gfx_get_skeleton_num_joints(const Skeleton*); - -/// Return true if the skeleton's ith joint has a bounding box. -/// -/// IK joints that do not directly transform vertices have no bounding box. -bool gfx_joint_has_box(const Anima*, const Skeleton*, size_t joint); - -/// Return the bounding box of the skeleton's ith joint. -/// -/// IK joints that do not directly transform vertices have no box. -Box gfx_get_joint_box(const Anima*, const Skeleton*, size_t joint); diff --git a/gfx/include/gfx/scene/camera.h b/gfx/include/gfx/scene/camera.h deleted file mode 100644 index 99d83fe..0000000 --- a/gfx/include/gfx/scene/camera.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once - -#include - -typedef struct SceneNode SceneNode; - -typedef struct SceneCamera SceneCamera; - -/// Create a new camera. -SceneCamera* gfx_make_camera(); - -/// Destroy the camera. -/// -/// The camera is conveniently removed from the scene graph and its parent scene -/// node is destroyed. -void gfx_destroy_camera(SceneCamera**); - -/// Set the scene camera's math camera. -void gfx_set_camera_camera(SceneCamera* scene_camera, Camera* camera); - -/// Get the scene camera's math camera. -Camera* gfx_get_camera_camera(SceneCamera*); diff --git a/gfx/include/gfx/scene/light.h b/gfx/include/gfx/scene/light.h deleted file mode 100644 index 132e344..0000000 --- a/gfx/include/gfx/scene/light.h +++ /dev/null @@ -1,30 +0,0 @@ -#pragma once - -typedef struct Texture Texture; - -typedef struct Light Light; - -/// Light type. -typedef enum LightType { EnvironmentLightType } LightType; - -/// Describes an environment light. -typedef struct EnvironmentLightDesc { - const Texture* environment_map; -} EnvironmentLightDesc; - -/// Describes a light. -typedef struct LightDesc { - LightType type; - union { - EnvironmentLightDesc environment; - } light; -} LightDesc; - -/// Create a light. -Light* gfx_make_light(const LightDesc*); - -/// Destroy the light. -/// -/// The light is conveniently removed from the scene graph and its parent scene -/// node is destroyed. -void gfx_destroy_light(Light**); diff --git a/gfx/include/gfx/scene/material.h b/gfx/include/gfx/scene/material.h deleted file mode 100644 index bca664e..0000000 --- a/gfx/include/gfx/scene/material.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once - -#include -#include - -typedef struct Material Material; - -/// Describes a material. -/// -/// A material holds a shader program and a set of shader-specific uniform -/// variables. Two materials can share the same shader, but shader parameters -/// generally give two materials a different appearance. -typedef struct MaterialDesc { - ShaderUniform uniforms[GFX_MAX_UNIFORMS_PER_MATERIAL]; - int num_uniforms; -} MaterialDesc; - -/// Create a material. -Material* gfx_make_material(const MaterialDesc*); - -/// Destroy the material. -/// -/// The caller must make sure that no Mesh points to the given Material. -/// For a safe purge of unused resources, see scene_purge(). -void gfx_destroy_material(Material**); diff --git a/gfx/include/gfx/scene/mesh.h b/gfx/include/gfx/scene/mesh.h deleted file mode 100644 index 0d3b4d4..0000000 --- a/gfx/include/gfx/scene/mesh.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once - -typedef struct Geometry Geometry; -typedef struct Material Material; -typedef struct ShaderProgram ShaderProgram; - -typedef struct Mesh Mesh; - -/// Describes a mesh. -typedef struct MeshDesc { - const Geometry* geometry; - const Material* material; - ShaderProgram* shader; -} MeshDesc; - -/// Create a mesh. -Mesh* gfx_make_mesh(const MeshDesc*); - -/// Destroy the mesh. -/// -/// The caller must make sure that no SceneObject points to the given Mesh. -/// For a safe purge of unused resources, see scene_purge(). -void gfx_destroy_mesh(Mesh**); diff --git a/gfx/include/gfx/scene/model.h b/gfx/include/gfx/scene/model.h deleted file mode 100644 index 42f85d4..0000000 --- a/gfx/include/gfx/scene/model.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -typedef struct Anima Anima; -typedef struct Model Model; -typedef struct SceneNode SceneNode; - -/// Return the model's anima, or null if the model is not animated. -Anima* gfx_get_model_anima(Model*); - -/// Return the model's root node. -const SceneNode* gfx_get_model_root(const Model*); -SceneNode* gfx_get_model_root_mut(Model*); diff --git a/gfx/include/gfx/scene/node.h b/gfx/include/gfx/scene/node.h deleted file mode 100644 index a2c2836..0000000 --- a/gfx/include/gfx/scene/node.h +++ /dev/null @@ -1,156 +0,0 @@ -#pragma once - -#include "animation.h" - -#include -#include - -#include - -typedef struct Anima Anima; -typedef struct Light Light; -typedef struct Model Model; -typedef struct SceneCamera SceneCamera; -typedef struct SceneObject SceneObject; - -/// Scene node type. -typedef enum NodeType { - LogicalNode, - AnimaNode, - CameraNode, - LightNode, - ModelNode, - ObjectNode, -} NodeType; - -/// A node in the scene graph. -/// -/// Scene nodes take ownership of the object they are associated with (Camera, -/// Light, SceneObject, etc), as well as of child nodes. -typedef struct SceneNode SceneNode; - -// ----------------------------------------------------------------------------- -// Constructors and destructor. -// ----------------------------------------------------------------------------- - -/// Create a new scene node. -/// -/// This node does not contain any camera, light, object, etc. and exists simply -/// as a logical and spatial construct. -SceneNode* gfx_make_node(); - -/// Create an anima node. -SceneNode* gfx_make_anima_node(Anima*); - -/// Create a new camera node. -SceneNode* gfx_make_camera_node(SceneCamera*); - -/// Create a new light node. -SceneNode* gfx_make_light_node(Light*); - -/// Create a new model node. -SceneNode* gfx_make_model_node(Model*); - -/// Create a new object node. -SceneNode* gfx_make_object_node(SceneObject*); - -/// Make the node an anima node. -void gfx_construct_anima_node(SceneNode*, Anima*); - -/// Make the node a camera node. -void gfx_construct_camera_node(SceneNode*, SceneCamera*); - -/// Make the node a light node. -void gfx_construct_light_node(SceneNode*, Light*); - -/// Make the node a model node. -void gfx_construct_model_node(SceneNode*, Model*); - -/// Make the node an object node. -void gfx_construct_object_node(SceneNode*, SceneObject*); - -/// Recursively destroy the scene node and its children. -/// -/// The scene node and its children are removed from the scene graph. -/// -/// Node resources -- cameras, lights, objects, etc. -- are also destroyed. -void gfx_destroy_node(SceneNode**); - -// ----------------------------------------------------------------------------- -// Getters. -// ----------------------------------------------------------------------------- - -/// Get the node's type. -NodeType gfx_get_node_type(const SceneNode*); - -/// Get the node's anima. -/// -/// The node must be of type AnimaNode. -const Anima* gfx_get_node_anima(const SceneNode*); -Anima* gfx_get_node_anima_mut(SceneNode*); - -/// Get the node's camera. -/// -/// The node must be of type CameraNode. -const SceneCamera* gfx_get_node_camera(const SceneNode* node); -SceneCamera* gfx_get_node_camera_mut(SceneNode* node); - -/// Get the node's light. -/// -/// The node must be of type LightNode. -const Light* gfx_get_node_light(const SceneNode*); -Light* gfx_get_node_light_mut(SceneNode*); - -/// Get the node's model. -/// -/// The node must be of type ModelNode. -const Model* gfx_get_node_model(const SceneNode*); -Model* gfx_get_node_model_mut(SceneNode*); - -/// Get the node's scene object. -/// -/// The node must be of type ObjectNode. -const SceneObject* gfx_get_node_object(const SceneNode*); -SceneObject* gfx_get_node_object_mut(SceneNode*); - -/// Get the node's parent. -const SceneNode* gfx_get_node_parent(const SceneNode*); -SceneNode* gfx_get_node_parent_mut(SceneNode*); - -/// Get the node's first child. -const SceneNode* gfx_get_node_child(const SceneNode*); -SceneNode* gfx_get_node_child_mut(SceneNode*); - -/// Get the node's immediate sibling. -const SceneNode* gfx_get_node_sibling(const SceneNode*); -SceneNode* gfx_get_node_sibling_mut(SceneNode*); - -/// Get the node's (local) transform. -mat4 gfx_get_node_transform(const SceneNode*); - -/// Get the node's global transform. -mat4 gfx_get_node_global_transform(const SceneNode*); - -// ----------------------------------------------------------------------------- -// Setters. -// ----------------------------------------------------------------------------- - -/// Set the node's parent. -/// -/// Pass in null to unwire from the existing parent, if one exists. -void gfx_set_node_parent(SceneNode*, SceneNode* parent_node); - -/// Set the node's (local) transform. -void gfx_set_node_transform(SceneNode*, const mat4* transform); - -/// Set the node's position. -void gfx_set_node_position(SceneNode*, const vec3* position); - -/// Set the node's rotation. -void gfx_set_node_rotation(SceneNode*, const quat* rotation); - -/// Set the node's rotation. -void gfx_set_node_rotation_mat(SceneNode*, const mat4* rotation); - -/// Log the node's hierarchy. -void gfx_log_node_hierarchy(const SceneNode*); diff --git a/gfx/include/gfx/scene/object.h b/gfx/include/gfx/scene/object.h deleted file mode 100644 index 7579d29..0000000 --- a/gfx/include/gfx/scene/object.h +++ /dev/null @@ -1,39 +0,0 @@ -#pragma once - -#include - -#include - -#include - -typedef struct Mesh Mesh; -typedef struct SceneNode SceneNode; -typedef struct Skeleton Skeleton; - -typedef struct SceneObject SceneObject; - -typedef struct ObjectDesc { - size_t num_meshes; - Mesh* meshes[GFX_MAX_NUM_MESHES]; -} ObjectDesc; - -/// Create a new object. -SceneObject* gfx_make_object(const ObjectDesc*); - -/// Destroy the object. -/// -/// The object is conveniently removed from the scene graph and its parent scene -/// node is destroyed. -void gfx_destroy_object(SceneObject**); - -/// Set the object's skeleton. -void gfx_set_object_skeleton(SceneObject*, const Skeleton*); - -/// Get the object's skeleton. -/// Return null if the object has no skeleton. -const Skeleton* gfx_get_object_skeleton(const SceneObject*); - -/// Gets the object's bounding box. -/// -/// The object's bounding box is the bounding box of its mesh geometries. -aabb3 gfx_get_object_aabb(const SceneObject*); diff --git a/gfx/include/gfx/scene/scene.h b/gfx/include/gfx/scene/scene.h deleted file mode 100644 index 0d96210..0000000 --- a/gfx/include/gfx/scene/scene.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once - -#include -#include - -typedef struct SceneNode SceneNode; - -typedef struct Scene Scene; - -/// Create a new scene. -Scene* gfx_make_scene(void); - -/// Destroy the scene. -/// -/// This function destroys the scene and all objects that it owns (scene -/// objects, cameras, lights, etc), but not objects that could be shared with -/// other scenes (meshes, materials, etc). -void gfx_destroy_scene(Scene**); - -/// Get the scene's root node. -SceneNode* gfx_get_scene_root(Scene*); diff --git a/gfx/include/gfx/sizes.h b/gfx/include/gfx/sizes.h deleted file mode 100644 index 076113c..0000000 --- a/gfx/include/gfx/sizes.h +++ /dev/null @@ -1,95 +0,0 @@ -/// Size constants used throughout the library. -#pragma once - -// Scene. - -/// Maximum number of cameras per scene. -#define GFX_MAX_NUM_CAMERAS 16 - -/// Maximum number of lights. -#define GFX_MAX_NUM_LIGHTS 1024 - -/// Maximum number of materials. -#define GFX_MAX_NUM_MATERIALS 1024 - -/// Maximum number of meshes. -#define GFX_MAX_NUM_MESHES 1024 - -/// Maximum number of mesh links. -#define GFX_MAX_NUM_MESH_LINKS 1024 - -/// Maximum number of models. -#define GFX_MAX_NUM_MODELS 64 - -/// Maximum number of joints per skeleton. -#define GFX_MAX_NUM_JOINTS 96 - -/// Maximum number of keyframes per channel. -#define GFX_MAX_NUM_KEYFRAMES 32 - -/// Maximum number of channels per animation. -#define GFX_MAX_NUM_CHANNELS 128 - -/// Maximum number of skeletons. -#define GFX_MAX_NUM_SKELETONS 128 - -/// Maximum number of animations. -#define GFX_MAX_NUM_ANIMATIONS 128 - -/// Maximum number of animas. -#define GFX_MAX_NUM_ANIMAS 128 - -/// Maximum number of nodes per scene. -#define GFX_MAX_NUM_NODES 1024 - -/// Maximum number of objects per scene. -#define GFX_MAX_NUM_OBJECTS 1024 - -/// Maximum number of uniforms in a Material. -#define GFX_MAX_UNIFORMS_PER_MATERIAL 18 - -// Render. - -/// Maximum number of buffers per renderer. -#define GFX_MAX_NUM_BUFFERS 1024 - -/// Maximum number of framebuffers per renderer. -#define GFX_MAX_NUM_FRAMEBUFFERS 32 - -/// Maximum number of geometries per renderer. -#define GFX_MAX_NUM_GEOMETRIES 1024 - -/// Maximum number of renderbuffers per renderer. -#define GFX_MAX_NUM_RENDERBUFFERS (GFX_MAX_NUM_FRAMEBUFFERS * 2) - -/// Maximum number of shader programs per renderer. -#define GFX_MAX_NUM_SHADER_PROGRAMS 128 - -/// Maximum number of shaders per renderer. -#define GFX_MAX_NUM_SHADERS (GFX_MAX_NUM_SHADER_PROGRAMS * 2) - -/// Maximum number of textures per renderer. -#define GFX_MAX_NUM_TEXTURES 1024 - -/// Maximum number of uniforms in a ShaderProgram. -#define GFX_MAX_UNIFORMS_PER_SHADER (GFX_MAX_UNIFORMS_PER_MATERIAL + 8) - -/// Maximum number of compiler defines in a Shader. -#define GFX_MAX_SHADER_COMPILER_DEFINES 16 - -// Renderer. - -/// Maximum number of triangles that the immediate-mode renderer can draw in a -/// frame. -#define IMM_MAX_NUM_TRIANGLES 1024 - -/// Maximum number of matrices in the immediate-mode renderer's matrix stack. -#define IMM_MAX_NUM_MATRICES 32 - -// Asset Manager. - -#define GFX_MAX_NUM_ASSETS 1024 - -// Gfx. - -#define GFX_MAX_NUM_SCENES 4 diff --git a/gfx/include/gfx/util/geometry.h b/gfx/include/gfx/util/geometry.h deleted file mode 100644 index a962291..0000000 --- a/gfx/include/gfx/util/geometry.h +++ /dev/null @@ -1,13 +0,0 @@ -/// Functions to construct geometry procedurally. -#pragma once - -#include - -#include -#include - -/// Construct a quad with positions in the range [-1, 1]^2. -Geometry* gfx_make_quad_11(GfxCore*); - -/// Construct a quad with positions in the range [0, 1]^2. -Geometry* gfx_make_quad_01(GfxCore*); diff --git a/gfx/include/gfx/util/ibl.h b/gfx/include/gfx/util/ibl.h deleted file mode 100644 index 6e39180..0000000 --- a/gfx/include/gfx/util/ibl.h +++ /dev/null @@ -1,25 +0,0 @@ -/// Functions for image-based lighting. -#pragma once - -typedef struct IBL IBL; - -typedef struct GfxCore GfxCore; -typedef struct Texture Texture; - -/// Create an environment map filterer for IBL. -IBL* gfx_make_ibl(GfxCore*); - -/// Destroy the environment map filterer. -void gfx_destroy_ibl(GfxCore*, IBL**); - -/// Create a BRDF integration map for IBL. -Texture* gfx_make_brdf_integration_map(IBL*, GfxCore*, int width, int height); - -/// Create an irradiance map (cubemap) from an environment map for IBL. -Texture* gfx_make_irradiance_map( - IBL*, GfxCore*, const Texture* environment_map, int width, int height); - -/// Create a prefiltered environment map (cubemap) for IBL. -Texture* gfx_make_prefiltered_environment_map( - IBL*, GfxCore*, const Texture* environment_map, int width, int height, - int* max_mip_level); diff --git a/gfx/include/gfx/util/shader.h b/gfx/include/gfx/util/shader.h deleted file mode 100644 index bd058f4..0000000 --- a/gfx/include/gfx/util/shader.h +++ /dev/null @@ -1,46 +0,0 @@ -/// A variety of shaders included for convenience. -#pragma once - -#include - -typedef struct GfxCore GfxCore; -typedef struct ShaderCompilerDefine ShaderCompilerDefine; -typedef struct ShaderProgram ShaderProgram; - -/// Create a BRDF integration map shader. -ShaderProgram* gfx_make_brdf_integration_map_shader(GfxCore*); - -/// Create a Cook-Torrance shader. -ShaderProgram* gfx_make_cook_torrance_shader(GfxCore*); - -/// Create a Cook-Torrance shader with additional shader compiler defines. -/// This function can be used to create shader permutations. -ShaderProgram* gfx_make_cook_torrance_shader_perm( - GfxCore*, const ShaderCompilerDefine*, size_t num_defines); - -/// Create a 3D debugging shader. -ShaderProgram* gfx_make_debug3d_shader(GfxCore*); - -/// Create a shader for drawing in immediate mode. -ShaderProgram* gfx_make_immediate_mode_shader(GfxCore*); - -/// Create a shader for computing irradiance maps from cube maps. -ShaderProgram* gfx_make_irradiance_map_shader(GfxCore*); - -/// Create a shader for computing prefiltered environment maps from cube maps. -ShaderProgram* gfx_make_prefiltered_environment_map_shader(GfxCore*); - -/// Create a skyquad shader. -ShaderProgram* gfx_make_skyquad_shader(GfxCore*); - -/// Create a shader to view normal-mapped normals. -ShaderProgram* gfx_make_view_normal_mapped_normals_shader(GfxCore*); - -/// Create a shader to view vertex normals. -ShaderProgram* gfx_make_view_normals_shader(GfxCore*); - -/// Create a shader to view vertex tangents. -ShaderProgram* gfx_make_view_tangents_shader(GfxCore*); - -/// Create a shader to view textures. -ShaderProgram* gfx_make_view_texture_shader(GfxCore*); diff --git a/gfx/include/gfx/util/skyquad.h b/gfx/include/gfx/util/skyquad.h deleted file mode 100644 index 2b3fe17..0000000 --- a/gfx/include/gfx/util/skyquad.h +++ /dev/null @@ -1,22 +0,0 @@ -/// A skyquad is like a skybox but with a single quad. -#pragma once - -typedef struct GfxCore GfxCore; -typedef struct Scene Scene; -typedef struct SceneNode SceneNode; -typedef struct SceneObject SceneObject; -typedef struct Texture Texture; - -/// Create a skyquad. -SceneObject* gfx_make_skyquad(GfxCore*, const Texture*); - -/// Set up a skyquad in the scene. -/// -/// This function adds two scene nodes under the given root node: -/// - An object node to render the skyquad in the background. -/// - A light node to light up other objects with the skyquad. -/// -/// Return the light node under which objects affected by the light can be -/// rooted. -SceneNode* gfx_setup_skyquad( - GfxCore*, SceneNode* root, const Texture* environment_map); diff --git a/gfx/shaders/brdf_integration_map.frag b/gfx/shaders/brdf_integration_map.frag deleted file mode 100644 index bb2cebd..0000000 --- a/gfx/shaders/brdf_integration_map.frag +++ /dev/null @@ -1,93 +0,0 @@ -precision highp float; - -#define PI 3.1415926535897932384626433832795 -#define NUM_SAMPLES 1024 - -in vec2 Texcoord; - -layout (location = 0) out vec2 Color; - -float radical_inverse_VdC(uint bits) { - bits = (bits << 16u) | (bits >> 16u); - bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); - bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); - bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); - bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); - return float(bits) * 2.3283064365386963e-10; // / 0x100000000 -} - -vec2 hammersley(uint i, uint N) { - return vec2(float(i)/float(N), radical_inverse_VdC(i)); -} - -vec3 importance_sample_GGX(vec2 sample_box, vec3 N, float roughness) { - float r2 = roughness * roughness; - - // Spherical coordinates. - float phi = 2.0 * PI * sample_box.x; - float cos_theta = sqrt((1.0 - sample_box.y) / (1.0 + (r2*r2 - 1.0) * sample_box.y)); - float sin_theta = sqrt(1.0 - cos_theta * cos_theta); - - // Map spherical coordinates to Cartesian coordinates in tangent space. - vec3 H = vec3(cos(phi) * sin_theta, sin(phi) * sin_theta, cos_theta); - - // Map from tangent space to world space. - // - // Tangent space: - // - // N - // | - // | - // | - // |_ _ _ _ _ B - // / - // / - // T - vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); - vec3 T = normalize(cross(up,N)); - vec3 B = cross(N,T); - vec3 H_ws = H.x*T + H.y*B + H.z*N; - return H_ws; -} - -float geometry_schlick_GGX(float k, float NdotV) { - return NdotV / (NdotV * (1.0 - k) + k); -} - -float geometry_smith(float roughness, float NdotL, float NdotV) { - float k = roughness * roughness / 2.0; // IBL - return geometry_schlick_GGX(k, NdotV) * geometry_schlick_GGX(k, NdotL); -} - -vec2 integrate_brdf(float NdotV, float roughness) -{ - vec3 V = vec3(sqrt(1.0 - NdotV * NdotV), 0.0, NdotV); - vec3 N = vec3(0.0, 0.0, 1.0); - - float scale = 0.0; - float bias = 0.0; - for (int i = 0; i < NUM_SAMPLES; ++i) { - vec2 sample_box = hammersley(i, NUM_SAMPLES); - vec3 H = importance_sample_GGX(sample_box, N, roughness); - vec3 L = reflect(-V,H); - float NdotL = max(0.0, L.z); - - if (NdotL > 0.0) { - float NdotH = max(0.0, H.z); - float VdotH = max(0.0, dot(V,H)); - float G = geometry_smith(roughness, NdotL, NdotV); - float G_vis = (G * VdotH) / (NdotH * NdotV); - float Fc = pow(1.0 - VdotH, 5.0); - scale += (1.0 - Fc) * G_vis; - bias += Fc * G_vis; - } - } - scale /= float(NUM_SAMPLES); - bias /= float(NUM_SAMPLES); - return vec2(scale, bias); -} - -void main() -{ - Color = integrate_brdf(Texcoord.x, Texcoord.y); -} diff --git a/gfx/shaders/cook_torrance.frag b/gfx/shaders/cook_torrance.frag deleted file mode 100644 index 1975491..0000000 --- a/gfx/shaders/cook_torrance.frag +++ /dev/null @@ -1,255 +0,0 @@ -precision highp float; - -uniform vec4 BaseColorFactor; -uniform float MetallicFactor; -uniform float RoughnessFactor; -uniform vec3 EmissiveFactor; - -#ifdef HAS_ALBEDO_MAP -uniform sampler2D BaseColorTexture; -#endif -#ifdef HAS_METALLIC_ROUGHNESS_MAP -uniform sampler2D MetallicRoughnessTexture; -#endif -#ifdef HAS_EMISSIVE_MAP -uniform sampler2D EmissiveTexture; -#endif -#ifdef HAS_OCCLUSION_MAP -uniform sampler2D AmbientOcclusionTexture; -#endif -#ifdef HAS_NORMAL_MAP -uniform sampler2D NormalMap; -#endif - -// TODO: Handle case in which there is no sky. Pass a boolean. -uniform samplerCube Sky; -uniform samplerCube IrradianceMap; -uniform samplerCube PrefilteredEnvironmentMap; -uniform sampler2D BRDFIntegrationMap; -uniform float MaxReflectionLOD; - -uniform vec3 CameraPosition; // World space. - -// World-space position, normal and tangent. -in vec3 Position; -#ifdef HAS_NORMALS -in vec3 Normal; -#endif -#ifdef HAS_TANGENTS -in vec4 Tangent; -#endif -#ifdef HAS_TEXCOORDS -in vec2 Texcoord; -#endif - -layout (location = 0) out vec4 Colour; - -#define PI 3.1415926535897932384626433832795 -#define INV_PI 0.3183098861837907 - -/// Transform a normal map sample into world space. -/// -/// |normalWs| is the surface normal in world space. -/// |normalMapSample| is the normal map sample, not necessarily normalized. -/// -/// TODO: Move to "normal.h" -#if defined(HAS_NORMAL_MAP) && (defined(HAS_TANGENTS) || defined(HAS_TEXCOORDS)) -vec3 get_ws_normal(vec3 normalWs, vec3 normalMapSample) { - vec3 N = normalize(Normal); -#ifdef HAS_TANGENTS - //vec3 T = normalize(tangent.xyz - dot(tangent.xyz, N) * N); - vec3 T = Tangent.xyz; - vec3 B = Tangent.w * cross(N, T); -#elif HAS_TEXCOORDS // No tangents, but must have texcoords. - vec3 pos_dx = dFdx(Position); - vec3 pos_dy = dFdy(Position); - // vec3 uv_dx = vec3(dFdx(Texcoord), 0.0); - // vec3 uv_dy = vec3(dFdy(Texcoord), 0.0); - vec3 uv_dx = dFdx(vec3(Texcoord, 0.0)); - vec3 uv_dy = dFdy(vec3(Texcoord, 0.0)); - vec3 T = (uv_dy.t * pos_dx - uv_dx.t * pos_dy) / - (uv_dx.s * uv_dy.t - uv_dy.s * uv_dx.t); - // vec3 T = pos_dx * uv_dy.t - pos_dy * uv_dx.t; - T = normalize(T - dot(T, N) * N); - vec3 B = normalize(cross(N, T)); -#endif - - if (gl_FrontFacing == false) { - T = -T; - B = -B; - N = -N; - } - - vec3 s = normalMapSample; - //return normalize(s.x * T + s.y * B + s.z * N); - return normalize(mat3(T,B,N) * s); -} -#endif // HAS_TANGENTS || HAS_TEXCOORDS - -float trowbridge_reitz_GGX(float roughness, float NdotH) { - float a = roughness * roughness; - float a2 = a * a; - float d = NdotH * NdotH * (a2 - 1.0) + 1.0; - return a2 / (PI * d * d); -} - -float geometry_schlick_GGX(float k, float NdotV) { - return NdotV / (NdotV * (1.0 - k) + k); -} - -float geometry_smith(float roughness, float NdotL, float NdotV) { - float k = roughness * roughness / 2.0; // IBL - return geometry_schlick_GGX(k, NdotV) * geometry_schlick_GGX(k, NdotL); -} - -vec3 fresnel_schlick(vec3 F0, float HdotV) { - return F0 + (1.0 - F0) * pow(clamp(1.0 - HdotV, 0.0, 1.0), 5.0); -} - -vec3 fresnel_schlick_roughness(vec3 F0, float NdotV, float roughness) { - return F0 - + (max(vec3(1.0 - roughness), F0) - F0) - * pow(clamp(1.0 - NdotV, 0.0, 1.0), 5.0); -} - -// Cook-Torrance BRDF for a single light direction. -vec3 cook_torrance( - vec3 albedo, float metallic, float roughness, - float NdotL, float NdotV, float NdotH, float HdotV) { - vec3 F0 = mix(vec3(0.04), albedo, metallic); - float D = trowbridge_reitz_GGX(roughness, NdotH); - vec3 F = fresnel_schlick(F0, HdotV); - float G = geometry_smith(roughness, NdotL, NdotV); - vec3 Kd = mix(vec3(1.0) - F, vec3(0.0), metallic); - vec3 diffuse = Kd*albedo*INV_PI; - // Take a max to prevent division by 0 when either dot product is 0. - vec3 specular = (D*F*G) / max(4.0 * NdotV * NdotL, 0.0001); - return diffuse + specular; -} - -// Cook-Torrance BRDF for IBL. -vec3 cook_torrance_IBL( - vec3 albedo, float metallic, float roughness, float occlusion, - float NdotV, - vec3 irradiance, vec3 prefiltered_env, vec2 BRDF_env) { - vec3 F0 = mix(vec3(0.04), albedo, metallic); - vec3 F = fresnel_schlick_roughness(F0, NdotV, roughness); - vec3 Kd = mix(vec3(1.0) - F, vec3(0.0), metallic); - vec3 diffuse = Kd * albedo * INV_PI * irradiance; - vec3 specular = prefiltered_env * (F * BRDF_env.x + BRDF_env.y); - return occlusion * (diffuse + specular); -} - -void main() -{ - // TODO: Also use the specular F0 map from the model, and emissive. Make sure - // to use all maps. - // https://sketchfab.com/models/b81008d513954189a063ff901f7abfe4 -#ifdef HAS_NORMAL_MAP - vec3 normalMapSample = texture(NormalMap, Texcoord).xyz * 2.0 - 1.0; - vec3 N = get_ws_normal(Normal, normalMapSample); -#elif HAS_NORMALS - vec3 N = normalize(Normal); -#endif - vec3 V = normalize(CameraPosition - Position); - vec3 R = reflect(-V, N); - // Not needed for IBL. - //vec3 L = N; - //vec3 H = normalize(L + V); - - float NdotV = max(0.0, dot(N, V)); - // Not needed for IBL. - //float NdotL = max(0.0, dot(N,L)); - //float NdotH = max(0.0, dot(N,H)); - //float HdotV = clamp(dot(H,V), 0.0, 1.0); // Clamp to prevent black spots. - - // TODO: BaseColorFactor and BaseColorTexture are vec4/rgba quantities - // respectively. Handle the alpha channel. - // TODO: Other factors. -#ifdef HAS_ALBEDO_MAP - vec3 albedo = vec3(BaseColorFactor) * texture(BaseColorTexture, Texcoord).rgb; -#else - vec3 albedo = vec3(BaseColorFactor); -#endif -#ifdef HAS_METALLIC_ROUGHNESS_MAP - // Spec: "Its green channel contains roughness values and its blue channel - // contains metalness values." - vec2 metal_roughness - = vec2(MetallicFactor, RoughnessFactor) - * texture(MetallicRoughnessTexture, Texcoord).bg; -#else - vec2 metal_roughness = vec2(MetallicFactor, RoughnessFactor); -#endif -#ifdef HAS_EMISSIVE_MAP - vec3 emissive = EmissiveFactor * texture(EmissiveTexture, Texcoord).rgb; -#else - vec3 emissive = EmissiveFactor; -#endif -#ifdef HAS_OCCLUSION_MAP - float occlusion = texture(AmbientOcclusionTexture, Texcoord).r; -#else - float occlusion = 1.0; -#endif - float metallic = metal_roughness.x; - float roughness = metal_roughness.y; - - // For a single light direction: - // vec3 brdf = cook_torrance(albedo, metallic, roughness, NdotL, NdotV, NdotH, HdotV); - // vec3 Li = texture(Sky, N).rgb; - // vec3 colour = brdf * Li * NdotL; - - // For IBL: - vec3 irradiance = texture(IrradianceMap, N).rgb; - vec3 prefiltered_env = textureLod(PrefilteredEnvironmentMap, R, roughness * MaxReflectionLOD).rgb; - vec2 BRDF_env = texture(BRDFIntegrationMap, vec2(NdotV, roughness)).rg; - vec3 colour = cook_torrance_IBL( - albedo, metallic, roughness, occlusion, NdotV, irradiance, prefiltered_env, BRDF_env); - - colour += emissive; - - // Reinhard tone mapping. - colour = colour / (colour + vec3(1.0)); - - // Gamma correction. - colour = pow(colour, vec3(1.0 / 2.2)); - - // Debugging. - // - // Normal texture. - //colour = normalMapSample * 0.5 + 0.5; - // - // Geometry normal. - //colour = normalize(Normal) * 0.5 + 0.5; - // - // Shading normal. - //colour = N * 0.5 + 0.5; - // - // Tangent and bitangent. - // { - // vec3 pos_dx = dFdx(Position); - // vec3 pos_dy = dFdy(Position); - // // vec3 uv_dx = vec3(dFdx(Texcoord), 0.0); - // // vec3 uv_dy = vec3(dFdy(Texcoord), 0.0); - // vec3 uv_dx = dFdx(vec3(Texcoord, 0.0)); - // vec3 uv_dy = dFdy(vec3(Texcoord, 0.0)); - // vec3 T = (uv_dy.t * pos_dx - uv_dx.t * pos_dy) / - // (uv_dx.s * uv_dy.t - uv_dy.s * uv_dx.t); - // // vec3 T = pos_dx * uv_dy.t - pos_dy * uv_dx.t; - // vec3 N = normalize(Normal); - // T = normalize(T - dot(T, N) * N); - // vec3 B = normalize(cross(N, T)); - - // if (gl_FrontFacing == false) { - // T = -T; - // B = -B; - // N = -N; - // } - - // // Tangent. - // //colour = T * 0.5 + 0.5; - // // Bitangent. - // //colour = B * 0.5 + 0.5; - // } - - Colour = vec4(colour, 1.0); -} diff --git a/gfx/shaders/cook_torrance.vert b/gfx/shaders/cook_torrance.vert deleted file mode 100644 index 5f126c0..0000000 --- a/gfx/shaders/cook_torrance.vert +++ /dev/null @@ -1,75 +0,0 @@ -precision highp float; - -uniform mat4 ModelMatrix; -// uniform mat4 Modelview; -uniform mat4 View; -uniform mat4 Projection; -//uniform mat4 MVP; -#ifdef HAS_JOINTS -// The client should pass in an appropriate value for MAX_JOINTS. -// #define MAX_JOINTS 96 -// -// matnxm -- n columns and m rows, different convention from math. -// We don't need the last row of [0, 0, 0, 1], so drop it to pack the matrices -// as tightly as possible. -// 256 joints * 4x4 matrix * 4 bytes/float = 16.0KB -// 256 joints * 4x3 matrix * 4 bytes/float = 12.0KB -// 96 joints * 4x4 matrix * 4 bytes/float = 6.0KB -// 96 joints * 4x3 matrix * 4 bytes/float = 4.5KB -//uniform mat4x3 Joints[MAX_JOINTS]; -uniform mat4 JointMatrices[MAX_JOINTS]; // Use 4x4 for now to keep it simple. -#endif - -layout (location = 0) in vec3 vPosition; -#ifdef HAS_NORMALS -layout (location = 1) in vec3 vNormal; -#endif -#ifdef HAS_TANGENTS -layout (location = 2) in vec4 vTangent; -#endif -#ifdef HAS_TEXCOORDS -layout (location = 3) in vec2 vTexcoord; -#endif -#ifdef HAS_JOINTS -layout (location = 4) in uvec4 vJoint; -layout (location = 5) in vec4 vWeight; -#endif - -// World-space position, normal and tangent. -out vec3 Position; -#ifdef HAS_NORMALS -out vec3 Normal; -#endif -#ifdef HAS_TANGENTS -out vec4 Tangent; -#endif -#ifdef HAS_TEXCOORDS -out vec2 Texcoord; -#endif - -void main() -{ -#ifdef HAS_JOINTS - mat4 skinMatrix = - vWeight.x * JointMatrices[vJoint.x] + - vWeight.y * JointMatrices[vJoint.y] + - vWeight.z * JointMatrices[vJoint.z] + - vWeight.w * JointMatrices[vJoint.w]; - Position = vec3(ModelMatrix * skinMatrix * vec4(vPosition, 1.0)); -#else - Position = vec3(ModelMatrix * vec4(vPosition, 1.0)); -#endif -#ifdef HAS_NORMALS - Normal = mat3(ModelMatrix) * vNormal; - //Normal = normalize(ModelMatrix * vec4(vNormal, 0.0)).xyz; -#endif -#ifdef HAS_TANGENTS - Tangent = vec4(mat3(ModelMatrix) * vTangent.xyz, vTangent.w); -#endif -#ifdef HAS_TEXCOORDS - Texcoord = vTexcoord; -#endif - gl_Position = Projection * View * vec4(Position, 1.0); - //gl_Position = Projection * vec4(Position, 1.0); - //gl_Position = MVP * vec4(vPosition, 1.0); -} diff --git a/gfx/shaders/cubemap_filtering.vert b/gfx/shaders/cubemap_filtering.vert deleted file mode 100644 index d0cf73f..0000000 --- a/gfx/shaders/cubemap_filtering.vert +++ /dev/null @@ -1,39 +0,0 @@ -precision highp float; - -#define PI 3.1415926535897932384626433832795 -#define FOVY (90.0 * PI / 180.0) - -uniform mat4 CameraRotation; // From camera space to world space. -uniform float Flip; - -layout (location = 0) in vec2 vPosition; - -out vec3 Ray; - -// DEBUG -// out vec2 Texcoord; - -// This is very similar to the skyquad vertex shader. -// -// The ray is not normalized because it isn't necessary for cubemap sampling. -// -// We also use a fixed fovy = 90 degrees because we want the frustum to pass -// exactly through each face of the cube. The aspect ratio is also just 1. -vec3 sky_ray(vec2 FilmPosition) -{ - float d = 0.5 / tan(FOVY/2.0); - return vec3(FilmPosition, -d); -} - -void main() -{ - vec2 FilmPosition = vPosition * 0.5; // map [-1,1] -> [-1/2, +1/2] - FilmPosition *= Flip; - Ray = mat3(CameraRotation) * sky_ray(FilmPosition); - // TODO: Should disable depth test when rendering. - gl_Position = vec4(vPosition, 0.99999, 1.0); // z=1 -> send to background - - // DEBUG - // Texcoord = FilmPosition + 0.5; - // Texcoord.y = 1.0 - Texcoord.y; -} diff --git a/gfx/shaders/debug3d.frag b/gfx/shaders/debug3d.frag deleted file mode 100644 index 54568d4..0000000 --- a/gfx/shaders/debug3d.frag +++ /dev/null @@ -1,21 +0,0 @@ -precision highp float; - -const vec3 Colour = vec3(0.97, 0.948, 0.91); - -const vec3 ToLight = vec3(1, 0.7, 1); - -in vec3 Normal; - -out vec4 FragColour; - -void main() -{ - vec3 N = normalize(Normal); - vec3 L = normalize(ToLight); - - vec3 a = vec3(0.7); - vec3 d = vec3(0.3 * (0.7*max(0.0, dot(L,N)) + 0.3*max(0.0, dot(-L,N)))); - vec3 c = Colour * (a+d); - - FragColour = vec4(pow(c, vec3(1.0 / 2.2)), 1.0); -} diff --git a/gfx/shaders/debug3d.vert b/gfx/shaders/debug3d.vert deleted file mode 100644 index d51684f..0000000 --- a/gfx/shaders/debug3d.vert +++ /dev/null @@ -1,15 +0,0 @@ -precision highp float; - -uniform mat4 Modelview; -uniform mat4 Projection; - -layout (location = 0) in vec3 vPosition; -layout (location = 1) in vec3 vNormal; - -out vec3 Normal; - -void main() -{ - Normal = mat3(Modelview) * vNormal; - gl_Position = Projection * Modelview * vec4(vPosition, 1.0); -} diff --git a/gfx/shaders/immediate_mode.frag b/gfx/shaders/immediate_mode.frag deleted file mode 100644 index ac23b5c..0000000 --- a/gfx/shaders/immediate_mode.frag +++ /dev/null @@ -1,10 +0,0 @@ -precision highp float; - -uniform vec4 Colour; - -out vec4 FragColour; - -void main() -{ - FragColour = vec4(pow(Colour.rgb, vec3(1.0/2.2)), Colour.a); -} diff --git a/gfx/shaders/immediate_mode.vert b/gfx/shaders/immediate_mode.vert deleted file mode 100644 index 65070bb..0000000 --- a/gfx/shaders/immediate_mode.vert +++ /dev/null @@ -1,11 +0,0 @@ -precision highp float; - -uniform mat4 Model; -uniform mat4 ViewProjection; - -layout (location = 0) in vec3 vPosition; - -void main() -{ - gl_Position = ViewProjection * Model * vec4(vPosition, 1.0); -} diff --git a/gfx/shaders/irradiance_map.frag b/gfx/shaders/irradiance_map.frag deleted file mode 100644 index 8200e73..0000000 --- a/gfx/shaders/irradiance_map.frag +++ /dev/null @@ -1,65 +0,0 @@ -precision highp float; - -#define PI 3.1415926535897932384626433832795 -#define EPS 0.001 -#define NUM_SAMPLES_AZIMUTH 250 -#define NUM_SAMPLES_ZENITH 50 -#define MAX_AZIMUTH (2*PI) -#define MAX_ZENITH (PI/2.0) -#define AZIMUTH_DELTA (MAX_AZIMUTH / float(NUM_SAMPLES_AZIMUTH)) -#define ZENITH_DELTA (MAX_ZENITH / float(NUM_SAMPLES_ZENITH)) - -uniform samplerCube Sky; - -in vec3 Ray; - -// DEBUG -// in vec2 Texcoord; - -layout (location = 0) out vec4 Color; - -void main() -{ - // Tangent space: - // - // N - // | - // | - // | - // |_ _ _ _ _ B - // / - // / - // T - vec3 N = normalize(Ray); - vec3 B = (abs(N.x) - 1.0 <= EPS) ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); - vec3 T = normalize(cross(B, N)); - B = normalize(cross(N, T)); - - int num_samples = 0; - vec3 irradiance = vec3(0.0); - for (float theta = 0.0; theta < MAX_AZIMUTH; theta += AZIMUTH_DELTA) { - for (float phi = 0.0; phi < MAX_ZENITH; phi += ZENITH_DELTA) { - // Spherical to Cartesian. - vec3 sample_tangent_space = vec3( - sin(phi) * cos(theta), - sin(phi) * sin(theta), - cos(phi)); - // Tangent space to world space. - vec3 sample_world_space = - sample_tangent_space.x * B + - sample_tangent_space.y * T + - sample_tangent_space.z * N; - - irradiance += texture(Sky, sample_world_space).rgb * sin(phi) * cos(phi); - num_samples += 1; - } - } - irradiance = PI * irradiance / float(num_samples); - - // For debugging in trace. - //irradiance = texture(Sky, Ray).rgb; - // irradiance = vec3(Texcoord, 0.0); - //irradiance = pow(irradiance, vec3(1.0/2.2)); - - Color = vec4(irradiance, 1.0); -} diff --git a/gfx/shaders/prefiltered_environment_map.frag b/gfx/shaders/prefiltered_environment_map.frag deleted file mode 100644 index 8327950..0000000 --- a/gfx/shaders/prefiltered_environment_map.frag +++ /dev/null @@ -1,78 +0,0 @@ -precision highp float; - -#define PI 3.1415926535897932384626433832795 -#define NUM_SAMPLES 4096 - -uniform samplerCube Sky; -uniform float Roughness; - -in vec3 Ray; - -layout (location = 0) out vec4 Color; - -float radical_inverse_VdC(uint bits) { - bits = (bits << 16u) | (bits >> 16u); - bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); - bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); - bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); - bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); - return float(bits) * 2.3283064365386963e-10; // / 0x100000000 -} - -vec2 hammersley(uint i, uint N) { - return vec2(float(i)/float(N), radical_inverse_VdC(i)); -} - -vec3 importance_sample_GGX(vec2 sample_box, vec3 N, float roughness) { - float r2 = roughness * roughness; - - // Spherical coordinates. - float phi = 2.0 * PI * sample_box.x; - float cos_theta = sqrt((1.0 - sample_box.y) / (1.0 + (r2*r2 - 1.0) * sample_box.y)); - float sin_theta = sqrt(1.0 - cos_theta * cos_theta); - - // Map spherical coordinates to Cartesian coordinates in tangent space. - vec3 H = vec3(cos(phi) * sin_theta, sin(phi) * sin_theta, cos_theta); - - // Map from tangent space to world space. - // - // Tangent space: - // - // N - // | - // | - // | - // |_ _ _ _ _ B - // / - // / - // T - vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); - vec3 T = normalize(cross(up,N)); - vec3 B = cross(N,T); - vec3 H_ws = H.x*T + H.y*B + H.z*N; - return H_ws; -} - -void main() -{ - vec3 N = normalize(Ray); - vec3 R = N; - vec3 V = R; - - vec3 irradiance = vec3(0.0); - float total_weight = 0.0; - for (uint i = 0; i < NUM_SAMPLES; ++i) { - vec2 sample_box = hammersley(i, NUM_SAMPLES); - vec3 H = importance_sample_GGX(sample_box, N, Roughness); - vec3 L = reflect(-V,H); - - float NdotL = max(dot(N,L), 0.0); - if (NdotL > 0.0) { - irradiance += texture(Sky, H).rgb * NdotL; - total_weight += NdotL; - } - } - irradiance /= total_weight; - - Color = vec4(irradiance, 1.0); -} diff --git a/gfx/shaders/quad.vert b/gfx/shaders/quad.vert deleted file mode 100644 index ef1834c..0000000 --- a/gfx/shaders/quad.vert +++ /dev/null @@ -1,9 +0,0 @@ -layout (location = 0) in vec2 Position; // Assuming Position in [-1,1]. - -out vec2 Texcoord; - -void main() -{ - Texcoord = Position * 0.5 + 0.5; - gl_Position = vec4(Position, 0.0, 1.0); -} diff --git a/gfx/shaders/skyquad.frag b/gfx/shaders/skyquad.frag deleted file mode 100644 index 9b44bfd..0000000 --- a/gfx/shaders/skyquad.frag +++ /dev/null @@ -1,13 +0,0 @@ -uniform samplerCube Skyquad; - -in vec3 Ray; - -layout (location = 0) out vec4 Colour; - -void main() -{ - vec3 R = normalize(Ray); - Colour = vec4(pow(texture(Skyquad, R).rgb, vec3(1.0/2.2)), 1.0); - // Debug. - //Colour = vec4(pow(R*0.5 + 0.5, vec3(1.0 / 2.2)), 1.0); -} diff --git a/gfx/shaders/skyquad.vert b/gfx/shaders/skyquad.vert deleted file mode 100644 index c0c46e6..0000000 --- a/gfx/shaders/skyquad.vert +++ /dev/null @@ -1,27 +0,0 @@ -uniform mat4 CameraRotation; // From camera space to world space. -uniform float Fovy; -uniform float Aspect; - -layout (location = 0) in vec2 Position; - -out vec3 Ray; - -// We would typically normalize the vector, but there is no need to do so when -// sampling a cube map. -vec3 sky_ray(vec2 FilmPosition) -{ - //float d = 0.5 / tan(Fovy/2.0); - // return vec3((FilmPosition.x - 0.5) * Aspect, - // FilmPosition.y - 0.5, - // -d); - float d = 0.5 / tan(Fovy/2.0); - return vec3(FilmPosition, -d); -} - -void main() -{ - vec2 FilmPosition = Position * 0.5; // map [-1,1] -> [-1/2, +1/2] - Ray = mat3(CameraRotation) * sky_ray(FilmPosition); - // Set z to the background. - gl_Position = vec4(Position, 0.99999, 1.0); // z=1 -> send to background -} diff --git a/gfx/shaders/view_normal_mapped_normals.frag b/gfx/shaders/view_normal_mapped_normals.frag deleted file mode 100644 index a372c02..0000000 --- a/gfx/shaders/view_normal_mapped_normals.frag +++ /dev/null @@ -1,28 +0,0 @@ -precision highp float; - -uniform sampler2D NormalMap; - -in vec3 Normal; -in vec4 Tangent; -in vec3 Bitangent; // TODO: Compute here or in PS? -in vec2 Texcoord; - -out vec4 FragColour; - -// TODO: Move to "normal.h" -vec3 get_vs_normal(vec3 normal, vec4 tangent, vec3 normalMapSample) { - vec3 N = normal; - // vec3 T = normalize(interpTangent - dot(tangent, N)*N); - // vec3 B = normalize(interpBitangent - dot(interpTangent, N)*N - dot(interpTangent, T)*T); - vec3 T = tangent.xyz; - //vec3 B = tangent.w * cross(N,T); - vec3 B = Bitangent; - vec3 n = normalMapSample; - return normalize(n.x*T + n.y*B + n.z*N); -} - -void main() { - vec3 normalMapSample = texture(NormalMap, Texcoord).xyz * 2.0 - 1.0; - vec3 N = get_vs_normal(Normal, Tangent, normalMapSample); - FragColour = vec4(pow(N, vec3(1.0 / 2.2)), 1.0); -} diff --git a/gfx/shaders/view_normal_mapped_normals.vert b/gfx/shaders/view_normal_mapped_normals.vert deleted file mode 100644 index 004ed9a..0000000 --- a/gfx/shaders/view_normal_mapped_normals.vert +++ /dev/null @@ -1,22 +0,0 @@ -precision highp float; - -uniform mat4 Modelview; -uniform mat4 Projection; - -layout (location = 0) in vec3 vPosition; -layout (location = 1) in vec3 vNormal; -layout (location = 2) in vec4 vTangent; -layout (location = 3) in vec2 vTexcoord; - -out vec3 Normal; -out vec4 Tangent; -out vec3 Bitangent; // TODO: Compute here or in PS? -out vec2 Texcoord; - -void main() { - Texcoord = vTexcoord; - Normal = mat3(Modelview) * vNormal; - Tangent = vec4(mat3(Modelview) * vTangent.xyz, vTangent.w); - Bitangent = cross(Normal, Tangent.xyz) * vTangent.w; - gl_Position = Projection * Modelview * vec4(vPosition, 1.0); -} diff --git a/gfx/shaders/view_normals.frag b/gfx/shaders/view_normals.frag deleted file mode 100644 index e90189c..0000000 --- a/gfx/shaders/view_normals.frag +++ /dev/null @@ -1,11 +0,0 @@ -precision highp float; - -in vec3 Normal; - -out vec4 FragColour; - -void main() -{ - vec3 N = normalize(Normal); - FragColour = vec4(pow(N, vec3(1.0 / 2.2)), 1.0); -} diff --git a/gfx/shaders/view_normals.vert b/gfx/shaders/view_normals.vert deleted file mode 100644 index d51684f..0000000 --- a/gfx/shaders/view_normals.vert +++ /dev/null @@ -1,15 +0,0 @@ -precision highp float; - -uniform mat4 Modelview; -uniform mat4 Projection; - -layout (location = 0) in vec3 vPosition; -layout (location = 1) in vec3 vNormal; - -out vec3 Normal; - -void main() -{ - Normal = mat3(Modelview) * vNormal; - gl_Position = Projection * Modelview * vec4(vPosition, 1.0); -} diff --git a/gfx/shaders/view_tangents.frag b/gfx/shaders/view_tangents.frag deleted file mode 100644 index 11d1455..0000000 --- a/gfx/shaders/view_tangents.frag +++ /dev/null @@ -1,17 +0,0 @@ -precision highp float; - -in vec4 Tangent; - -out vec4 FragColour; - -void main() { - vec3 T = normalize(Tangent.xyz); - FragColour = vec4(pow(T, vec3(1.0 / 2.2)), 1.0);FragColour = vec4(pow(T, vec3(1.0 / 2.2)), 1.0); - - // View sign. - // float sign = Tangent.w; - // float R = sign > 0.0 ? 1.0 : 0.0; - // float B = sign < 0.0 ? 1.0 : 0.0; - // vec3 signColour = vec3(R,0.0,B); - // FragColour = vec4(pow(signColour, vec3(1.0 / 2.2)), 1.0); -} diff --git a/gfx/shaders/view_tangents.vert b/gfx/shaders/view_tangents.vert deleted file mode 100644 index 561ad22..0000000 --- a/gfx/shaders/view_tangents.vert +++ /dev/null @@ -1,14 +0,0 @@ -precision highp float; - -uniform mat4 Modelview; -uniform mat4 Projection; - -layout (location = 0) in vec3 vPosition; -layout (location = 2) in vec4 vTangent; - -out vec4 Tangent; - -void main() { - Tangent = vec4(Tangent.xyz = mat3(Modelview) * vTangent.xyz, vTangent.w); - gl_Position = Projection * Modelview * vec4(vPosition, 1.0); -} diff --git a/gfx/shaders/view_texture.frag b/gfx/shaders/view_texture.frag deleted file mode 100644 index 12fa367..0000000 --- a/gfx/shaders/view_texture.frag +++ /dev/null @@ -1,15 +0,0 @@ -uniform sampler2D Texture; - -in vec2 Texcoord; - -layout (location = 0) out vec4 Colour; - -void main() -{ - // There is a question here whether we want to view the texture through the - // sampler or unfiltered. Prefer the latter for now. - //vec3 colour = texture(Texture, Texcoord).rgb; - ivec2 st = ivec2(Texcoord * vec2(textureSize(Texture, 0))); - vec3 colour = texelFetch(Texture, st, 0).rgb; - Colour = vec4(pow(colour, vec3(1.0 / 2.2)), 1.0); -} diff --git a/gfx/shaders/view_texture.vert b/gfx/shaders/view_texture.vert deleted file mode 100644 index 4e3c7d7..0000000 --- a/gfx/shaders/view_texture.vert +++ /dev/null @@ -1,13 +0,0 @@ -layout (location = 0) in vec2 Position; - -out vec2 Texcoord; - -void main() -{ - Texcoord = Position * vec2(0.5) + vec2(0.5);// Map from [-1, +1] to [0, 1]. - // The Gfx library is written to work with the glTF sample models, which - // seem to want the textures loaded "as is" without flipping. Flip the - // y-coordinate here so that the texture appears as expected. - Texcoord.y = 1.0 - Texcoord.y; - gl_Position = vec4(Position, 0.0, 1.0); -} diff --git a/gfx/src/asset/asset_cache.c b/gfx/src/asset/asset_cache.c deleted file mode 100644 index 16c4d5c..0000000 --- a/gfx/src/asset/asset_cache.c +++ /dev/null @@ -1,252 +0,0 @@ -#include "asset_cache.h" - -#include "model.h" -#include "scene/animation_impl.h" -#include "scene/model_impl.h" -#include "scene/node_impl.h" -#include "scene/scene_memory.h" -#include "texture.h" - -#include -#include -#include -#include - -#include -#include -#include - -static void log_model_load_failure(const LoadModelCmd* cmd) { - assert(cmd); - - switch (cmd->origin) { - case AssetFromFile: - log_error("Failed to load model: %s", mstring_cstr(&cmd->filepath)); - break; - case AssetFromMemory: - log_error("Failed to load model: %p", cmd->data); - break; - } -} - -static void log_texture_load_failure(const LoadTextureCmd* cmd) { - assert(cmd); - - switch (cmd->origin) { - case AssetFromFile: - switch (cmd->type) { - case LoadTexture: - log_error( - "Failed to load texture: %s", - mstring_cstr(&cmd->data.texture.filepath)); - break; - case LoadCubemap: - log_error( - "Failed to load cubemap texture: %s", - mstring_cstr(&cmd->data.cubemap.filepaths.filepath_pos_x)); - break; - } - break; - case AssetFromMemory: - switch (cmd->type) { - case LoadTexture: - log_error("Failed to load texture: %p", cmd->data.texture.data); - break; - case LoadCubemap: - log_error( - "Failed to load texture: %p", cmd->data.cubemap.buffers.data_pos_x); - break; - } - break; - } -} - -static Hash calc_model_hash(const LoadModelCmd* cmd) { - assert(cmd); - switch (cmd->origin) { - case AssetFromFile: - return cstring_hash(mstring_cstr(&cmd->filepath)); - case AssetFromMemory: - return (Hash)cmd->data; - } - FAIL("Unhandled model asset origin"); - return 0; -} - -static Hash calc_texture_hash(const LoadTextureCmd* cmd) { - assert(cmd); - switch (cmd->origin) { - case AssetFromFile: - switch (cmd->type) { - case LoadTexture: - return cstring_hash(mstring_cstr(&cmd->data.texture.filepath)); - case LoadCubemap: - return cstring_hash( - mstring_cstr(&cmd->data.cubemap.filepaths.filepath_pos_x)) ^ - cstring_hash( - mstring_cstr(&cmd->data.cubemap.filepaths.filepath_neg_x)) ^ - cstring_hash( - mstring_cstr(&cmd->data.cubemap.filepaths.filepath_pos_y)) ^ - cstring_hash( - mstring_cstr(&cmd->data.cubemap.filepaths.filepath_neg_y)) ^ - cstring_hash( - mstring_cstr(&cmd->data.cubemap.filepaths.filepath_pos_z)) ^ - cstring_hash( - mstring_cstr(&cmd->data.cubemap.filepaths.filepath_neg_z)); - } - break; - case AssetFromMemory: - switch (cmd->type) { - case LoadTexture: - return (Hash)cmd->data.texture.data; - case LoadCubemap: - return (Hash)cmd->data.cubemap.buffers.data_pos_x ^ - (Hash)cmd->data.cubemap.buffers.data_neg_x ^ - (Hash)cmd->data.cubemap.buffers.data_pos_y ^ - (Hash)cmd->data.cubemap.buffers.data_neg_y ^ - (Hash)cmd->data.cubemap.buffers.data_pos_z ^ - (Hash)cmd->data.cubemap.buffers.data_neg_z; - } - break; - } - FAIL("Unhandled texture asset origin"); - return 0; -} - -static Asset* lookup_cache(AssetCache* cache, Hash hash) { - assert(cache); - mempool_foreach(&cache->assets, asset, { - if (asset->hash == hash) { - return asset; - } - }); - return 0; -} - -static void log_model_cache_hit(const LoadModelCmd* cmd, Hash hash) { - assert(cmd); - switch (cmd->origin) { - case AssetFromFile: - LOGD( - "Found asset [%s] in cache with hash [%lu]", - mstring_cstr(&cmd->filepath), hash); - break; - case AssetFromMemory: - LOGD("Found asset [%p] in cache with hash [%lu]", cmd->data, hash); - break; - } -} - -static void log_model_loaded(const LoadModelCmd* cmd) { - assert(cmd); - switch (cmd->origin) { - case AssetFromFile: - LOGD("Loaded asset from file: [%s]", mstring_cstr(&cmd->filepath)); - break; - case AssetFromMemory: - LOGD("Loaded asset from memory: [%p]", cmd->data); - break; - } -} - -static Model* clone_model(const Model* model) { - assert(model); - - // Only the Anima needs to be cloned since everything else in the model is - // static. - // - // The Anima can be partially shallow-cloned. Skeletons and animations are - // static and can be shared with the original Anima. Other members are - // deep-cloned. Skeletons in particular point back to their Anima, so need to - // be deep-cloned. - const SceneNode* root = mem_get_node(model->root); - if (gfx_get_node_type(root) == AnimaNode) { - const Anima* anima = gfx_get_node_anima(root); - Anima* anima_copy = mem_alloc_anima(); - *anima_copy = *anima; // Shallow copy. - - SceneNode* root_copy = gfx_clone_scene_shallow(root); - root_copy->anima = mem_get_anima_index(anima_copy); - anima_copy->parent = mem_get_node_index(root_copy); - - Model* copy = mem_alloc_model(); - copy->root = mem_get_node_index(root_copy); - return copy; - } else { - return (Model*)model; // Static model, can't be mutated. - } -} - -void gfx_init_asset_cache(AssetCache* cache) { - assert(cache); - mempool_make(&cache->assets); - - // Allocate a dummy asset at index 0 to guarantee that no assets allocated by - // the caller map to index 0. - const Asset* dummy = mempool_alloc(&cache->assets); - assert(mempool_get_block_index(&cache->assets, dummy) == 0); -} - -void gfx_destroy_asset_cache(AssetCache* cache) { - assert(cache); - mempool_del(&cache->assets); -} - -Model* gfx_load_model(Gfx* gfx, const LoadModelCmd* cmd) { - assert(gfx); - - AssetCache* cache = gfx_get_asset_cache(gfx); - - // First search for the asset in the cache. - const uint64_t hash = calc_model_hash(cmd); - Asset* asset = lookup_cache(cache, hash); - if (asset) { - log_model_cache_hit(cmd, hash); - return clone_model(asset->model); - } - - // Asset not found in the cache. - // Load it, insert it into the cache, and return it. - Model* model = gfx_model_load(gfx, cmd); - if (model) { - *(Asset*)mempool_alloc(&cache->assets) = (Asset){ - .type = ModelAsset, - .hash = hash, - .model = model, - }; - log_model_loaded(cmd); - return clone_model(model); - } else { - log_model_load_failure(cmd); - return 0; - } -} - -const Texture* gfx_load_texture(Gfx* gfx, const LoadTextureCmd* cmd) { - assert(gfx); - assert(cmd); - - AssetCache* cache = gfx_get_asset_cache(gfx); - - // First search for the asset in the cache. - const uint64_t hash = calc_texture_hash(cmd); - Asset* asset = lookup_cache(cache, hash); - if (asset) { - return asset->texture; - } - - // Asset not found in the cache. - // Load it, insert it into the cache, and return it. - GfxCore* gfxcore = gfx_get_core(gfx); - const Texture* texture = gfx_texture_load(gfxcore, cmd); - if (texture) { - *(Asset*)mempool_alloc(&cache->assets) = (Asset){ - .type = TextureAsset, - .hash = hash, - .texture = texture, - }; - } else { - log_texture_load_failure(cmd); - } - return texture; -} diff --git a/gfx/src/asset/asset_cache.h b/gfx/src/asset/asset_cache.h deleted file mode 100644 index b2a35ed..0000000 --- a/gfx/src/asset/asset_cache.h +++ /dev/null @@ -1,37 +0,0 @@ -#pragma once - -#include - -#include -#include - -typedef struct Model Model; -typedef struct Texture Texture; - -typedef uint64_t Hash; - -typedef enum AssetType { - ModelAsset, - TextureAsset, -} AssetType; - -typedef struct Asset { - AssetType type; - Hash hash; - union { - Model* model; - const Texture* texture; - }; -} Asset; - -DEF_MEMPOOL(asset_pool, Asset, GFX_MAX_NUM_ASSETS) - -typedef struct AssetCache { - asset_pool assets; -} AssetCache; - -/// Create a new asset cache. -void gfx_init_asset_cache(AssetCache*); - -/// Destroy the asset cache. -void gfx_destroy_asset_cache(AssetCache*); diff --git a/gfx/src/asset/model.c b/gfx/src/asset/model.c deleted file mode 100644 index 25f2780..0000000 --- a/gfx/src/asset/model.c +++ /dev/null @@ -1,1968 +0,0 @@ -/// Loads scenes from memory and files. -/// -/// Only the GLTF scene format is current supported. -/// -/// ---------------------------------------------------------------------------- -/// glTF File Format Documentation -/// ---------------------------------------------------------------------------- -/// -/// cgltf: -/// https://github.com/jkuhlmann/cgltf -/// -/// gltf overview: -/// https://raw.githubusercontent.com/KhronosGroup/glTF/master/specification/2.0/figures/gltfOverview-2.0.0b.png -/// -/// gltf spec: -/// https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md -/// -/// Sample models: -/// https://github.com/KhronosGroup/glTF-Sample-Models/tree/master/2.0 -/// https://github.com/KhronosGroup/glTF-Sample-Models/blob/master/2.0/Sponza/glTF/Sponza.gltf -/// https://github.com/KhronosGroup/glTF-Sample-Models/blob/master/2.0/AlphaBlendModeTest/glTF/AlphaBlendModeTest.gltf -/// https://github.com/KhronosGroup/glTF-Sample-Models/blob/master/2.0/Buggy/glTF/Buggy.gltf -/// https://github.com/KhronosGroup/glTF-Sample-Models/blob/master/2.0/AntiqueCamera/glTF/AntiqueCamera.gltf -/// https://github.com/KhronosGroup/glTF-Sample-Models/blob/master/2.0/DamagedHelmet/glTF/DamagedHelmet.gltf -/// -/// ---------------------------------------------------------------------------- -/// Implementation Notes -/// ---------------------------------------------------------------------------- -/// -/// # glTF and the gfx library -/// -/// glTF has concepts that are similar to those in the gfx library, but there -/// isn't an exact 1-1 mapping. Concepts map as follows: -/// -/// glTF gfx -/// ---- --- -/// buffer Buffer -/// accessor + buffer view BufferView -/// mesh primitive (geom + mat) Mesh (also geom + mat) -/// mesh SceneObject -/// node SceneNode -/// -/// glTF buffers map 1-1 with gfx Buffers. glTF scenes make heavy re-use of -/// buffers across views/accessors/meshes, so it is important to make that same -/// re-use in the gfx library to use the data effectively and without -/// duplication. The Sponza scene, for example, has all of its data in one giant -/// buffer. -/// -/// glTF accessors and buffer views are combined and mapped to gfx BufferViews. -/// The glTF buffer view's offset/length/stride are combined with the accessor's -/// offset, and together with the remaining information of both data structures -/// baked into a BufferView. Internally, this information is fed into -/// glVertexAttribPointer() calls, wrapped in a VAO (index view/accessor -/// information is fed into glDrawElements()). This baking should not hurt -/// re-use, at least in the OpenGL world. -/// -/// A glTF mesh primitive contains a piece of geometry and a material. This maps -/// directly to a gfx Mesh. -/// -/// A glTF mesh is a list of mesh primitives. This maps nicely to a gfx -/// SceneObject, with the only inconvenience that terminology gets a little -/// confusing. -/// -/// Finally, glTF nodes map directly to gfx SceneNodes. Both enforce a strict -/// tree hierarchy; DAGs are not supported. -/// -/// # Materials -/// -/// glTF uses the metallic-roughness material model. However, an extension -/// allows a scene to use the specular-glossiness model as well and cgltf -/// supports it: -/// -/// https://kcoley.github.io/glTF/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness/ -/// -/// From the docs, the specular-glossiness model can represent more materials -/// than the metallic-roughness model, but it is also more computationally -/// expensive. Furthermore, a material in glTF can specify parameters for both -/// models, leaving it up to the implementation to decide which one to use. -/// In our case, we use the specular-glosiness model if parameters for it are -/// provided, otherwise we use the metallic-roughness model. - -#include "asset/model.h" - -#include "asset/texture.h" -#include "gfx/core.h" -#include "gfx/gfx.h" -#include "gfx/scene/animation.h" -#include "gfx/scene/camera.h" -#include "gfx/scene/material.h" -#include "gfx/scene/mesh.h" -#include "gfx/scene/node.h" -#include "gfx/scene/object.h" -#include "gfx/scene/scene.h" -#include "gfx/sizes.h" -#include "gfx/util/shader.h" - -#include "gfx_assert.h" -#include "scene/model_impl.h" - -#include "cstring.h" -#include "error.h" -#include "log/log.h" -#include "math/camera.h" -#include "math/defs.h" -#include "math/mat4.h" -#include "math/quat.h" -#include "math/vec2.h" -#include "math/vec3.h" - -#include "cgltf_tangents.h" -#define CGLTF_IMPLEMENTATION -#include "cgltf.h" - -#include -#include - -// Taken from the GL header file. -#define GL_NEAREST 0x2600 -#define GL_LINEAR 0x2601 -#define GL_NEAREST_MIPMAP_NEAREST 0x2700 -#define GL_LINEAR_MIPMAP_NEAREST 0x2701 -#define GL_NEAREST_MIPMAP_LINEAR 0x2702 -#define GL_LINEAR_MIPMAP_LINEAR 0x2703 - -// Uniforms names. Must match the names in shaders. -#define UNIFORM_BASE_COLOR_FACTOR "BaseColorFactor" -#define UNIFORM_METALLIC_FACTOR "MetallicFactor" -#define UNIFORM_ROUGHNESS_FACTOR "RoughnessFactor" -#define UNIFORM_EMISSIVE_FACTOR "EmissiveFactor" -#define UNIFORM_BASE_COLOR_TEXTURE "BaseColorTexture" -#define UNIFORM_METALLIC_ROUGHNESS_TEXTURE "MetallicRoughnessTexture" -#define UNIFORM_EMISSIVE_TEXTURE "EmissiveTexture" -#define UNIFORM_AMBIENT_OCCLUSION_TEXTURE "AmbientOcclusionTexture" -#define UNIFORM_NORMAL_MAP "NormalMap" - -// Shader compiler defines. Must match the names in shaders. -#define DEFINE_HAS_TEXCOORDS "HAS_TEXCOORDS" -#define DEFINE_HAS_NORMALS "HAS_NORMALS" -#define DEFINE_HAS_TANGENTS "HAS_TANGENTS" -#define DEFINE_HAS_ALBEDO_MAP "HAS_ALBEDO_MAP" -#define DEFINE_HAS_METALLIC_ROUGHNESS_MAP "HAS_METALLIC_ROUGHNESS_MAP" -#define DEFINE_HAS_NORMAL_MAP "HAS_NORMAL_MAP" -#define DEFINE_HAS_OCCLUSION_MAP "HAS_OCCLUSION_MAP" -#define DEFINE_HAS_EMISSIVE_MAP "HAS_EMISSIVE_MAP" -#define DEFINE_HAS_JOINTS "HAS_JOINTS" -#define DEFINE_MAX_JOINTS "MAX_JOINTS" - -typedef enum TextureType { - BaseColorTexture, - MetallicRoughnessTexture, - EmissiveTexture, - AmbientOcclusionTexture, - NormalMap, -} TextureType; - -/// Describes the properties of a mesh. -/// This is used to create shader permutations. -typedef struct MeshPermutation { - union { - struct { - // Vertex attributes. - bool has_texcoords : 1; - bool has_normals : 1; - bool has_tangents : 1; - bool has_joints : 1; - bool has_weights : 1; - // Textures. - bool has_albedo_map : 1; - bool has_metallic_roughness_map : 1; - bool has_normal_map : 1; - bool has_occlusion_map : 1; - bool has_emissive_map : 1; - }; - int32_t all; - }; -} MeshPermutation; - -/// Build shader compiler defines from a mesh permutation. -static size_t make_defines( - MeshPermutation perm, ShaderCompilerDefine* defines) { - static const char* str_true = "1"; - size_t next = 0; - -#define check(field, define) \ - if (perm.field) { \ - defines[next].name = sstring_make(define); \ - defines[next].value = sstring_make(str_true); \ - next++; \ - } - check(has_texcoords, DEFINE_HAS_TEXCOORDS); - check(has_normals, DEFINE_HAS_NORMALS); - check(has_tangents, DEFINE_HAS_TANGENTS); - check(has_joints, DEFINE_HAS_JOINTS); - check(has_albedo_map, DEFINE_HAS_ALBEDO_MAP); - check(has_metallic_roughness_map, DEFINE_HAS_METALLIC_ROUGHNESS_MAP); - check(has_normal_map, DEFINE_HAS_NORMAL_MAP); - check(has_occlusion_map, DEFINE_HAS_OCCLUSION_MAP); - check(has_emissive_map, DEFINE_HAS_EMISSIVE_MAP); - - if (perm.has_joints) { - defines[next].name = sstring_make(DEFINE_MAX_JOINTS); - defines[next].value = sstring_itoa(GFX_MAX_NUM_JOINTS); - next++; - } - - return next; -} - -/// Compile a shader permutation. -static ShaderProgram* make_shader_permutation( - GfxCore* gfxcore, MeshPermutation perm) { - LOGD( - "Compiling Cook-Torrance shader permutation: texcoords: %d, normals: " - "%d, tangents: %d, joints: %d, weights: %d, albedo map: %d, " - "metallic-roughness map: " - "%d, normal " - "map: %d, AO map: %d, emissive map: %d", - perm.has_texcoords, perm.has_normals, perm.has_tangents, perm.has_joints, - perm.has_weights, perm.has_albedo_map, perm.has_metallic_roughness_map, - perm.has_normal_map, perm.has_occlusion_map, perm.has_emissive_map); - - ShaderCompilerDefine defines[GFX_MAX_SHADER_COMPILER_DEFINES]; - const size_t num_defines = make_defines(perm, defines); - return gfx_make_cook_torrance_shader_perm(gfxcore, defines, num_defines); -} - -/// Map a texture type to the name of the shader uniform used to access the -/// texture. -static const char* get_texture_uniform_name(TextureType type) { - switch (type) { - case BaseColorTexture: - return UNIFORM_BASE_COLOR_TEXTURE; - case MetallicRoughnessTexture: - return UNIFORM_METALLIC_ROUGHNESS_TEXTURE; - case EmissiveTexture: - return UNIFORM_EMISSIVE_TEXTURE; - case AmbientOcclusionTexture: - return UNIFORM_AMBIENT_OCCLUSION_TEXTURE; - case NormalMap: - return UNIFORM_NORMAL_MAP; - } - assert(false); - return 0; -} - -/// Map a glTF primitive type to a gfx primitive type. -static PrimitiveType from_gltf_primitive_type(cgltf_primitive_type type) { - switch (type) { - case cgltf_primitive_type_triangles: - return Triangles; - case cgltf_primitive_type_triangle_fan: - return TriangleFan; - case cgltf_primitive_type_triangle_strip: - return TriangleStrip; - // Not yet implemented. - case cgltf_primitive_type_lines: - case cgltf_primitive_type_line_loop: - case cgltf_primitive_type_line_strip: - case cgltf_primitive_type_points: - break; - } - LOGE("Unsupported primitive type: %d", type); - assert(false); - return 0; -} - -/// Map a glTF animation path type to its Gfx equivalent. -static ChannelType from_gltf_animation_path_type( - cgltf_animation_path_type type) { - switch (type) { - case cgltf_animation_path_type_translation: - return TranslationChannel; - case cgltf_animation_path_type_rotation: - return RotationChannel; - case cgltf_animation_path_type_scale: - return ScaleChannel; - case cgltf_animation_path_type_weights: - return WeightsChannel; - case cgltf_animation_path_type_invalid: - assert(false); - break; - } - assert(false); - return 0; -} - -/// Map a glTF interpolation to its Gfx equivalent. -static AnimationInterpolation from_gltf_interpolation_type( - cgltf_interpolation_type type) { - switch (type) { - case cgltf_interpolation_type_linear: - return LinearInterpolation; - case cgltf_interpolation_type_step: - return StepInterpolation; - case cgltf_interpolation_type_cubic_spline: - return CubicSplineInterpolation; - } - assert(false); - return 0; -} - -/// Return the component's size in bytes. -static cgltf_size get_component_size(cgltf_component_type type) { - switch (type) { - case cgltf_component_type_r_8: - return 1; - case cgltf_component_type_r_8u: - return 1; - case cgltf_component_type_r_16: - return 2; - case cgltf_component_type_r_16u: - return 2; - case cgltf_component_type_r_32u: - return 4; - case cgltf_component_type_r_32f: - return 4; - case cgltf_component_type_invalid: - assert(false); - break; - } - assert(false); - return 0; -} - -/// Return the number dimensionality of the given data type. -int get_num_dimensions(cgltf_type type) { - switch (type) { - case cgltf_type_scalar: - return 1; - case cgltf_type_vec2: - return 2; - case cgltf_type_vec3: - return 3; - case cgltf_type_vec4: - return 4; - case cgltf_type_mat2: - return 4; // 2x2 - case cgltf_type_mat3: - return 9; // 3x3 - case cgltf_type_mat4: - return 16; // 4x4 - case cgltf_type_invalid: - FAIL(); - break; - } - FAIL(); - return 0; -} - -/// Read an int64 from the given data pointer and accessor. -/// The largest integer in glTF is u32, so we can fit all integers in an int64. -static int64_t read_int(const void* component, const cgltf_accessor* accessor) { - assert(component); - assert(accessor); - - switch (accessor->component_type) { - case cgltf_component_type_r_8: { - const int8_t c = *((int8_t*)component); - return c; - } - case cgltf_component_type_r_8u: { - const uint8_t c = *((uint8_t*)component); - return c; - } - case cgltf_component_type_r_16: { - const int16_t c = *((int16_t*)component); - return c; - } - case cgltf_component_type_r_16u: { - const uint16_t c = *((uint16_t*)component); - return c; - } - case cgltf_component_type_r_32u: { - const uint32_t c = *((uint32_t*)component); - return c; - } - case cgltf_component_type_r_32f: { - const float c = *((float*)component); - return (int64_t)c; - } - case cgltf_component_type_invalid: - FAIL(); - break; - } - FAIL(); - return 0; -} - -/// Read a float from the given data pointer and accessor. -/// -/// This function uses the normalization equations from the spec. See the -/// animation section: -/// -/// https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#animations -static float read_float(const void* component, const cgltf_accessor* accessor) { - assert(component); - assert(accessor); - - switch (accessor->component_type) { - case cgltf_component_type_r_8: { - // assert(accessor->normalized); - const int8_t c = *((int8_t*)component); - return max((float)c / 127.0, -1.0); - } - case cgltf_component_type_r_8u: { - // assert(accessor->normalized); - const uint8_t c = *((uint8_t*)component); - return (float)c / 255.0; - } - case cgltf_component_type_r_16: { - // assert(accessor->normalized); - const int16_t c = *((int16_t*)component); - return max((float)c / 32767.0, -1.0); - } - case cgltf_component_type_r_16u: { - // assert(accessor->normalized); - const uint16_t c = *((uint16_t*)component); - return (float)c / 65535.0; - } - case cgltf_component_type_r_32u: { - // assert(accessor->normalized); - const uint32_t c = *((uint32_t*)component); - return (float)c / 4294967295.0; - } - case cgltf_component_type_r_32f: { - const float c = *((float*)component); - return c; - } - case cgltf_component_type_invalid: - FAIL(); - break; - } - FAIL(); - return 0; -} - -typedef struct AccessorIter { - const cgltf_accessor* accessor; - const uint8_t* next_element; - cgltf_size comp_size; // Component size in bytes. - cgltf_size stride; // ELement stride in bytes. - cgltf_size index; // Index of the next element. - bool is_matrix; -} AccessorIter; - -typedef struct AccessorData { - union { - struct { - float x, y, z, w; // Possibly normalized. - int64_t xi, yi, zi, wi; // Always unnormalized. - }; - const float* floats; - }; -} AccessorData; - -bool accessor_iter_next(AccessorIter* iter, AccessorData* data) { - assert(iter); - assert(data); - - if (iter->index < iter->accessor->count) { - const int dimensions = get_num_dimensions(iter->accessor->type); - const uint8_t* component = iter->next_element; - - // So that the caller can access the element's components as an array. - data->floats = (const float*)component; - - if (!iter->is_matrix) { // Scalar or vector. - // x - data->x = read_float(component, iter->accessor); - data->xi = read_int(component, iter->accessor); - component += iter->comp_size; - // y - if (dimensions > 1) { - data->y = read_float(component, iter->accessor); - data->yi = read_int(component, iter->accessor); - component += iter->comp_size; - } - // z - if (dimensions > 2) { - data->z = read_float(component, iter->accessor); - data->zi = read_int(component, iter->accessor); - component += iter->comp_size; - } - // w - if (dimensions > 3) { - data->w = read_float(component, iter->accessor); - data->wi = read_int(component, iter->accessor); - component += iter->comp_size; - } - } - - iter->next_element += iter->stride; - iter->index++; - return true; - } - - return false; -} - -AccessorIter make_accessor_iter(const cgltf_accessor* accessor) { - assert(accessor); - - const bool is_matrix = (accessor->type == cgltf_type_mat2) || - (accessor->type == cgltf_type_mat3) || - (accessor->type == cgltf_type_mat4); - - const int dimensions = get_num_dimensions(accessor->type); - assert( - ((dimensions == 1) && (accessor->type == cgltf_type_scalar)) || - ((dimensions == 2) && (accessor->type == cgltf_type_vec2)) || - ((dimensions == 3) && (accessor->type == cgltf_type_vec3)) || - ((dimensions == 4) && (accessor->type == cgltf_type_vec4)) || - ((dimensions == 4) && (accessor->type == cgltf_type_mat2)) || - ((dimensions == 9) && (accessor->type == cgltf_type_mat3)) || - ((dimensions == 16) && (accessor->type == cgltf_type_mat4))); - - const cgltf_buffer_view* view = accessor->buffer_view; - const cgltf_buffer* buffer = view->buffer; - const cgltf_size offset = accessor->offset + view->offset; - const uint8_t* bytes = (const uint8_t*)buffer->data + offset; - // Component size in bytes. - const cgltf_size comp_size = get_component_size(accessor->component_type); - // Element size in bytes. - const cgltf_size elem_size = dimensions * comp_size; - // Stride in bytes. If the view stride is 0, then the elements are tightly - // packed. - const cgltf_size stride = view->stride != 0 ? view->stride : elem_size; - - // There isn't an accessor stride in the spec, but cgltf still specifies one. - assert(accessor->stride == elem_size); - - // Accessor data must fit inside the view. - assert(accessor->offset + (accessor->count * accessor->stride) <= view->size); - - // Accessor data must fit inside the buffer. - assert( - (offset + (accessor->count * elem_size) + - ((accessor->count - 1) * view->stride)) <= buffer->size); - - return (AccessorIter){ - .accessor = accessor, - .next_element = bytes, - .comp_size = comp_size, - .stride = stride, - .index = 0, - .is_matrix = is_matrix, - }; -} - -/// Return the total number of primitives in the scene. Each mesh may contain -/// multiple primitives. -/// -/// Note that this function scans all of the scenes in the glTF data. -static size_t get_total_primitives(const cgltf_data* data) { - size_t total = 0; - for (cgltf_size i = 0; i < data->meshes_count; ++i) { - total += data->meshes[i].primitives_count; - } - return total; -} - -/// Load all buffers from the glTF scene. -/// -/// If buffer data is loaded from memory, set filepath = null. -/// -/// Return an array of Buffers such that the index of each glTF buffer in the -/// original array matches the same Buffer in the resulting array. -/// -/// TODO: There is no need to load the inverse bind matrices buffer into the -/// GPU. Might need to lazily load buffers. -static bool load_buffers( - const cgltf_data* data, GfxCore* gfxcore, Buffer** buffers) { - assert(data); - assert(gfxcore); - assert(buffers); - - for (cgltf_size i = 0; i < data->buffers_count; ++i) { - const cgltf_buffer* buffer = &data->buffers[i]; - assert(buffer->data); - buffers[i] = gfx_make_buffer( - gfxcore, &(BufferDesc){ - .usage = BufferStatic, - .type = BufferUntyped, - .data.data = buffer->data, - .data.count = buffer->size}); - if (!buffers[i]) { - return false; - } - } - - return true; -} - -/// Load tangent buffers. -static bool load_tangent_buffers( - const cgltfTangentBuffer* cgltf_tangent_buffers, - cgltf_size num_tangent_buffers, GfxCore* gfxcore, - Buffer** tangent_buffers) { - assert(cgltf_tangent_buffers); - assert(gfxcore); - assert(tangent_buffers); - - for (cgltf_size i = 0; i < num_tangent_buffers; ++i) { - const cgltfTangentBuffer* buffer = &cgltf_tangent_buffers[i]; - assert(buffer->data); - tangent_buffers[i] = gfx_make_buffer( - gfxcore, &(BufferDesc){ - .usage = BufferStatic, - .type = BufferUntyped, - .data.data = buffer->data, - .data.count = buffer->size_bytes}); - if (!tangent_buffers[i]) { - return false; - } - } - - return true; -} - -/// Lazily load all textures from the glTF scene. -/// -/// Colour textures like albedo are in sRGB colour space. Non-colour textures -/// like normal maps are in linear space (e.g. DamagedHelmet sample). Since we -/// don't know how the texture is going to be used at this point, we can't tell -/// what colour space it should be loaded in (ideally this would be part of the -/// image file format, but not all formats specify colour space.) Therefore, we -/// load the textures lazily and don't actually commit them to GPU memory until -/// we know their colour space when loading glTF materials. -/// -/// Return an array of LoadTextureCmds such that the index of each cmd matches -/// the index of each glTF texture in the scene. -static void load_textures_lazy( - const cgltf_data* data, GfxCore* gfxcore, const char* directory, - LoadTextureCmd* load_texture_cmds) { - assert(data); - assert(gfxcore); - assert(load_texture_cmds); - - for (cgltf_size i = 0; i < data->textures_count; ++i) { - const cgltf_texture* texture = &data->textures[i]; - const cgltf_image* image = texture->image; - const cgltf_sampler* sampler = texture->sampler; - - // glTF models might not specify a sampler. In such case, the client can - // pick its own defaults. - // https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#samplers - bool mipmaps = true; - TextureFiltering filtering = LinearFiltering; - TextureWrapping wrap = Repeat; - - if (sampler) { - // The gfx library does not distinguish between sampling the texture and - // combining the mipmap levels. - const cgltf_int filter = - sampler->min_filter == 0 ? sampler->mag_filter : sampler->min_filter; - - switch (filter) { - case GL_NEAREST_MIPMAP_NEAREST: - mipmaps = true; - filtering = NearestFiltering; - break; - case GL_NEAREST_MIPMAP_LINEAR: - case GL_LINEAR_MIPMAP_NEAREST: - case GL_LINEAR_MIPMAP_LINEAR: - mipmaps = true; - filtering = LinearFiltering; - break; - case GL_NEAREST: - filtering = NearestFiltering; - break; - case GL_LINEAR: - filtering = LinearFiltering; - break; - default: - break; - } - } - - // Currently only supporting loading textures from files. - assert(image->uri); - assert(directory); - mstring fullpath = - mstring_concat_path(mstring_make(directory), mstring_make(image->uri)); - - load_texture_cmds[i] = (LoadTextureCmd){ - .origin = AssetFromFile, - .type = LoadTexture, - .colour_space = sRGB, - .filtering = filtering, - .wrap = wrap, - .mipmaps = mipmaps, - .data.texture.filepath = fullpath}; - } -} - -/// Load a texture uniform. -/// -/// This determines a texture's colour space based on its intended use, loads -/// the texture, and then defines the sampler shader uniform. -static bool load_texture_and_uniform( - const cgltf_data* data, Gfx* gfx, const cgltf_texture_view* texture_view, - TextureType texture_type, const Texture** textures, - LoadTextureCmd* load_texture_cmds, int* next_uniform, MaterialDesc* desc) { - assert(data); - assert(gfx); - assert(texture_view); - assert(textures); - assert(next_uniform); - assert(desc); - assert(*next_uniform < GFX_MAX_UNIFORMS_PER_MATERIAL); - - const size_t texture_index = texture_view->texture - data->textures; - assert(texture_index < data->textures_count); - - // Here we are assuming that if a texture is re-used, it is re-used with the - // same texture view. This should be fine because, e.g., a normal map would - // not be used as albedo and vice versa. - if (!textures[texture_index]) { - LoadTextureCmd* cmd = &load_texture_cmds[texture_index]; - // TODO: Check for colour textures and default to LinearColourSpace instead. - if (texture_type == NormalMap) { - cmd->colour_space = LinearColourSpace; - } - - LOGD( - "Load texture: %s (mipmaps: %d, filtering: %d)", - mstring_cstr(&cmd->data.texture.filepath), cmd->mipmaps, - cmd->filtering); - - textures[texture_index] = gfx_load_texture(gfx, cmd); - if (!textures[texture_index]) { - log_error( - "Failed to load texture: %s", - mstring_cstr(&cmd->data.texture.filepath)); - return false; - } - } - - assert(*next_uniform < GFX_MAX_UNIFORMS_PER_MATERIAL); - desc->uniforms[(*next_uniform)++] = (ShaderUniform){ - .name = sstring_make(get_texture_uniform_name(texture_type)), - .type = UniformTexture, - .value.texture = textures[texture_index]}; - - return true; -} - -/// Load all materials from the glTF scene. -/// -/// Return an array of Materials such that the index of each descriptor matches -/// the index of each glTF material in the scene. Also return the number of -/// materials and the textures used by them. -static bool load_materials( - const cgltf_data* data, Gfx* gfx, LoadTextureCmd* load_texture_cmds, - const Texture** textures, Material** materials) { - assert(data); - assert(gfx); - assert(materials); - if (data->textures_count > 0) { - assert(load_texture_cmds); - assert(textures); - } - - for (cgltf_size i = 0; i < data->materials_count; ++i) { - const cgltf_material* mat = &data->materials[i]; - - int next_uniform = 0; - MaterialDesc desc = {0}; - - // TODO: specular/glossiness and other material parameters. - if (mat->has_pbr_metallic_roughness) { - const cgltf_pbr_metallic_roughness* pbr = &mat->pbr_metallic_roughness; - - assert(next_uniform < GFX_MAX_UNIFORMS_PER_MATERIAL); - desc.uniforms[next_uniform++] = (ShaderUniform){ - .name = sstring_make(UNIFORM_BASE_COLOR_FACTOR), - .type = UniformVec4, - .value.vec4 = vec4_from_array(pbr->base_color_factor)}; - - assert(next_uniform < GFX_MAX_UNIFORMS_PER_MATERIAL); - desc.uniforms[next_uniform++] = (ShaderUniform){ - .name = sstring_make(UNIFORM_METALLIC_FACTOR), - .type = UniformFloat, - .value.scalar = pbr->metallic_factor}; - - assert(next_uniform < GFX_MAX_UNIFORMS_PER_MATERIAL); - desc.uniforms[next_uniform++] = (ShaderUniform){ - .name = sstring_make(UNIFORM_ROUGHNESS_FACTOR), - .type = UniformFloat, - .value.scalar = pbr->roughness_factor}; - - assert(next_uniform < GFX_MAX_UNIFORMS_PER_MATERIAL); - desc.uniforms[next_uniform++] = (ShaderUniform){ - .name = sstring_make(UNIFORM_EMISSIVE_FACTOR), - .type = UniformVec3, - .value.vec3 = vec3_from_array(mat->emissive_factor)}; - - if (pbr->base_color_texture.texture) { - if (!load_texture_and_uniform( - data, gfx, &pbr->base_color_texture, BaseColorTexture, textures, - load_texture_cmds, &next_uniform, &desc)) { - return false; - } - } - - if (pbr->metallic_roughness_texture.texture) { - if (!load_texture_and_uniform( - data, gfx, &pbr->metallic_roughness_texture, - MetallicRoughnessTexture, textures, load_texture_cmds, - &next_uniform, &desc)) { - return false; - } - } - } - - if (mat->emissive_texture.texture) { - if (!load_texture_and_uniform( - data, gfx, &mat->emissive_texture, EmissiveTexture, textures, - load_texture_cmds, &next_uniform, &desc)) { - return false; - } - } - - if (mat->occlusion_texture.texture) { - if (!load_texture_and_uniform( - data, gfx, &mat->occlusion_texture, AmbientOcclusionTexture, - textures, load_texture_cmds, &next_uniform, &desc)) { - return false; - } - } - - if (mat->normal_texture.texture) { - if (!load_texture_and_uniform( - data, gfx, &mat->normal_texture, NormalMap, textures, - load_texture_cmds, &next_uniform, &desc)) { - return false; - } - } - - assert(next_uniform < GFX_MAX_UNIFORMS_PER_MATERIAL); - desc.num_uniforms = next_uniform; - - materials[i] = gfx_make_material(&desc); - if (!materials[i]) { - return false; - } - } - - return true; -} - -/// Create a default material for meshes that do not have a material. -static Material* make_default_material() { - MaterialDesc desc = (MaterialDesc){0}; - - assert(desc.num_uniforms < GFX_MAX_UNIFORMS_PER_MATERIAL); - desc.uniforms[desc.num_uniforms++] = (ShaderUniform){ - .name = sstring_make(UNIFORM_BASE_COLOR_FACTOR), - .type = UniformVec4, - .value.vec4 = vec4_make(1, 1, 1, 1)}; - - assert(desc.num_uniforms < GFX_MAX_UNIFORMS_PER_MATERIAL); - desc.uniforms[desc.num_uniforms++] = (ShaderUniform){ - .name = sstring_make(UNIFORM_METALLIC_FACTOR), - .type = UniformFloat, - .value.scalar = 0}; - - assert(desc.num_uniforms < GFX_MAX_UNIFORMS_PER_MATERIAL); - desc.uniforms[desc.num_uniforms++] = (ShaderUniform){ - .name = sstring_make(UNIFORM_ROUGHNESS_FACTOR), - .type = UniformFloat, - .value.scalar = 1}; - - assert(desc.num_uniforms < GFX_MAX_UNIFORMS_PER_MATERIAL); - desc.uniforms[desc.num_uniforms++] = (ShaderUniform){ - .name = sstring_make(UNIFORM_EMISSIVE_FACTOR), - .type = UniformVec3, - .value.vec3 = vec3_make(0, 0, 0)}; - - return gfx_make_material(&desc); -} - -/// Compute the bounding box of the vertices pointed to by the accessor. -/// 'dim' is the dimension of the vertices (2D or 3D). -aabb3 compute_aabb(const cgltf_accessor* accessor) { - aabb3 box = {0}; - if (accessor->has_min && accessor->has_max) { - box = aabb3_make( - vec3_from_array(accessor->min), vec3_from_array(accessor->max)); - } else { - AccessorIter iter = make_accessor_iter(accessor); - AccessorData vertex = {0}; - cgltf_size i = 0; - - while (accessor_iter_next(&iter, &vertex)) { - const vec3 p = vec3_make(vertex.x, vertex.y, vertex.z); - if (i == 0) { - box = aabb3_make(p, p); - } else { - box = aabb3_add(box, p); - } - ++i; - } - } - return box; -} - -/// Load all meshes from the glTF scene. -static bool load_meshes( - const cgltf_data* data, GfxCore* gfxcore, Buffer** buffers, - Buffer** tangent_buffers, const cgltfTangentBuffer* cgltf_tangent_buffers, - cgltf_size num_tangent_buffers, Material** materials, - ShaderProgram* const shader, size_t primitive_count, Geometry** geometries, - Mesh** meshes, SceneObject** scene_objects) { - // Walk through the mesh primitives to create Meshes. A GLTF mesh primitive - // has a material (Mesh) and vertex data (Geometry). A GLTF mesh maps to - // a SceneObject. - // - // glTF gfx - // ---- --- - // Mesh SceneObject - // Mesh primitive Mesh / Geometry - // Accessor + buffer view BufferView - // Buffer Buffer - assert(data); - assert(gfxcore); - assert(buffers); - assert(materials); - assert(geometries); - assert(meshes); - assert(scene_objects); - if (num_tangent_buffers > 0) { - assert(tangent_buffers); - assert(cgltf_tangent_buffers); - } - - // Points to the next available Mesh and also the next available Geometry. - // There is one (Mesh, Geometry) pair per glTF mesh primitive. - size_t next_mesh = 0; - - for (cgltf_size m = 0; m < data->meshes_count; ++m) { - const cgltf_mesh* mesh = &data->meshes[m]; - - ObjectDesc object_desc = {0}; - - for (cgltf_size p = 0; p < mesh->primitives_count; ++p) { - assert(next_mesh < primitive_count); - const cgltf_primitive* prim = &mesh->primitives[p]; - const cgltf_material* mat = prim->material; - - MeshPermutation perm = {0}; - if (mat) { - perm.has_normal_map = mat->normal_texture.texture != 0; - perm.has_occlusion_map = mat->occlusion_texture.texture != 0; - perm.has_emissive_map = mat->emissive_texture.texture != 0; - - if (mat->has_pbr_metallic_roughness) { - const cgltf_pbr_metallic_roughness* pbr = - &mat->pbr_metallic_roughness; - perm.has_albedo_map = pbr->base_color_texture.texture != 0; - perm.has_metallic_roughness_map = - pbr->metallic_roughness_texture.texture != 0; - } else { - // TODO: specular/glossiness and other material parameters. - } - } - - GeometryDesc geometry_desc = { - .type = from_gltf_primitive_type(prim->type), - .buffer_usage = BufferStatic}; - - // Vertex indices. - if (prim->indices) { - const cgltf_accessor* accessor = prim->indices; - const cgltf_buffer_view* view = prim->indices->buffer_view; - const cgltf_size buffer_index = view->buffer - data->buffers; - - assert(buffer_index < data->buffers_count); - Buffer* buffer = buffers[buffer_index]; - - const cgltf_size component_size = - get_component_size(accessor->component_type); - switch (component_size) { - case 1: { - BufferViewIdx8* indices = &geometry_desc.indices8; - // TODO: discards const qualifier. - indices->buffer = buffer; - indices->offset_bytes = accessor->offset + view->offset; - indices->size_bytes = view->size; - indices->stride_bytes = view->stride; - geometry_desc.num_indices = prim->indices->count; - break; - } - case 2: { - BufferViewIdx16* indices = &geometry_desc.indices16; - indices->buffer = buffer; - indices->offset_bytes = accessor->offset + view->offset; - indices->size_bytes = view->size; - indices->stride_bytes = view->stride; - geometry_desc.num_indices = prim->indices->count; - break; - } - default: - // TODO: Handle 32-bit indices. - assert(false); - break; - } - } - - // Vertex attributes. - for (cgltf_size a = 0; a < prim->attributes_count; ++a) { - const cgltf_attribute* attrib = &prim->attributes[a]; - const cgltf_accessor* accessor = attrib->data; - const cgltf_buffer_view* view = accessor->buffer_view; - const cgltf_size offset = accessor->offset + view->offset; - const cgltf_size buffer_index = view->buffer - data->buffers; - - assert(buffer_index < data->buffers_count); - Buffer* buffer = buffers[buffer_index]; - - BufferView2d* buffer_view_2d = 0; - BufferView3d* buffer_view_3d = 0; - BufferView4d* buffer_view_4d = 0; - BufferViewFloat* buffer_view_float = 0; - BufferViewU8* buffer_view_u8 = 0; - BufferViewU16* buffer_view_u16 = 0; - - switch (attrib->type) { - case cgltf_attribute_type_position: { - switch (accessor->type) { - case cgltf_type_vec2: - assert(geometry_desc.positions3d.buffer == 0); - buffer_view_2d = &geometry_desc.positions2d; - geometry_desc.aabb = compute_aabb(accessor); - break; - case cgltf_type_vec3: - assert(geometry_desc.positions2d.buffer == 0); - buffer_view_3d = &geometry_desc.positions3d; - geometry_desc.aabb = compute_aabb(accessor); - break; - default: - FAIL( - "Unhandled accessor type %d in vertex positions", - accessor->type); - assert(false); - return false; - } - // It is assumed that meshes have positions, so there is nothing to - // do for the mesh permutation in this case. - break; - } - case cgltf_attribute_type_normal: - buffer_view_3d = &geometry_desc.normals; - perm.has_normals = true; - break; - case cgltf_attribute_type_tangent: - buffer_view_4d = &geometry_desc.tangents; - perm.has_tangents = true; - break; - case cgltf_attribute_type_texcoord: - buffer_view_2d = &geometry_desc.texcoords; - perm.has_texcoords = true; - break; - case cgltf_attribute_type_color: - // TODO: Add support for color. - break; - case cgltf_attribute_type_joints: - // Joints can be either u8 or u16. - switch (accessor->component_type) { - case cgltf_component_type_r_8u: - buffer_view_u8 = &geometry_desc.joints.u8; - break; - case cgltf_component_type_r_16u: - buffer_view_u16 = &geometry_desc.joints.u16; - break; - default: - assert(false); - return false; - } - perm.has_joints = true; - break; - case cgltf_attribute_type_weights: - // Weights can be either u8, u16, or float. - switch (accessor->component_type) { - case cgltf_component_type_r_8u: - buffer_view_u8 = &geometry_desc.weights.u8; - break; - case cgltf_component_type_r_16u: - buffer_view_u16 = &geometry_desc.weights.u16; - break; - case cgltf_component_type_r_32f: - buffer_view_float = &geometry_desc.weights.floats; - break; - default: - assert(false); - return false; - } - perm.has_weights = true; - break; - case cgltf_attribute_type_invalid: - assert(false); - break; - } - -#define CONFIGURE_BUFFER(buf) \ - if (buf) { \ - buf->buffer = buffer; \ - buf->offset_bytes = offset; \ - buf->size_bytes = view->size; \ - buf->stride_bytes = view->stride; \ - } - CONFIGURE_BUFFER(buffer_view_2d); - CONFIGURE_BUFFER(buffer_view_3d); - CONFIGURE_BUFFER(buffer_view_4d); - CONFIGURE_BUFFER(buffer_view_u8); - CONFIGURE_BUFFER(buffer_view_u16); - CONFIGURE_BUFFER(buffer_view_float); - } // Vertex attributes. - - assert( - (perm.has_joints && perm.has_weights) || - (!perm.has_joints && !perm.has_weights)); - - // If the mesh primitive has no tangents, see if they were computed - // separately. - if (!geometry_desc.tangents.buffer) { - for (cgltf_size t = 0; t < num_tangent_buffers; ++t) { - const cgltfTangentBuffer* cgltf_buffer = &cgltf_tangent_buffers[t]; - - if (cgltf_buffer->primitive == prim) { - BufferView4d* view = &geometry_desc.tangents; - view->buffer = tangent_buffers[t]; - view->offset_bytes = 0; - view->size_bytes = cgltf_buffer->size_bytes; - view->stride_bytes = 0; // Tightly packed. - break; - } - } - } - - // Set the number of vertices in the geometry. Since a geometry can have - // either 2d or 3d positions but not both, here we can perform addition - // to compute the total number of vertices. - geometry_desc.num_verts = - (geometry_desc.positions2d.size_bytes / sizeof(vec2)) + - (geometry_desc.positions3d.size_bytes / sizeof(vec3)); - -#define CHECK_COUNT(buffer_view, type, num_components) \ - if (geometry_desc.buffer_view.buffer) { \ - assert( \ - (geometry_desc.buffer_view.size_bytes / \ - (num_components * sizeof(type))) == geometry_desc.num_verts); \ - } - - // Check that the number of vertices is consistent across all vertex - // attributes. - CHECK_COUNT(normals, vec3, 1); - CHECK_COUNT(tangents, vec4, 1); - CHECK_COUNT(texcoords, vec2, 1); - CHECK_COUNT(joints.u8, uint8_t, 4); - CHECK_COUNT(joints.u16, uint16_t, 4); - CHECK_COUNT(weights.u8, uint8_t, 4); - CHECK_COUNT(weights.u16, uint16_t, 4); - CHECK_COUNT(weights.floats, float, 4); - - Material* material = 0; - if (mat) { - const cgltf_size material_index = mat - data->materials; - assert(material_index < data->materials_count); - material = materials[material_index]; - } else { - // Create a default material for meshes that do not specify one. - material = make_default_material(); - } - assert(material); - - geometries[next_mesh] = gfx_make_geometry(gfxcore, &geometry_desc); - if (!geometries[next_mesh]) { - return false; - } - - // If the user specifies a custom shader, use that instead. Otherwise - // compile a shader based on the mesh's permutation. - // - // Note that Gfx takes care of caching shaders and shader programs. - // - // Caching materials could be useful, but, provided they can share - // shaders, the renderer can check later whether uniforms have the same - // values. Also, changing uniforms is much faster than swapping shaders, - // so shader caching is the most important thing here. - ShaderProgram* mesh_shader = - shader ? shader : make_shader_permutation(gfxcore, perm); - assert(mesh_shader); - - meshes[next_mesh] = gfx_make_mesh(&(MeshDesc){ - .geometry = geometries[next_mesh], - .material = material, - .shader = mesh_shader}); - - if (!meshes[next_mesh]) { - return false; - } - - assert(object_desc.num_meshes < GFX_MAX_NUM_MESHES); - object_desc.meshes[object_desc.num_meshes] = meshes[next_mesh]; - object_desc.num_meshes++; - - ++next_mesh; - } // glTF mesh primitive / gfx Mesh. - - scene_objects[m] = gfx_make_object(&object_desc); - if (!scene_objects[m]) { - return false; - } - } // glTF mesh / gfx SceneObject. - - return true; -} - -/// Compute bounding boxes for the joints in the model. -static void compute_joint_bounding_boxes( - const cgltf_data* data, size_t num_joints, JointDesc* joint_descs) { - assert(data); - assert(joint_descs); - assert(num_joints <= GFX_MAX_NUM_JOINTS); - - // Initialize bounding boxes so that we can compute unions below. - for (size_t i = 0; i < num_joints; ++i) { - joint_descs[i].box = aabb3_make_empty(); - } - - // Iterate over the meshes -> primitives -> vertices -> joint indices, and add - // the vertex to the joint's bounding box. - for (cgltf_size n = 0; n < data->nodes_count; ++n) { - const cgltf_node* node = &data->nodes[n]; - - if (node->skin) { - if (node->mesh) { - const cgltf_mesh* mesh = node->mesh; - - for (cgltf_size pr = 0; pr < mesh->primitives_count; ++pr) { - const cgltf_primitive* prim = &mesh->primitives[pr]; - - // Find the indices of the positions and joints arrays in the - // primitive's attributes. - int positions_index = -1; - int joints_index = -1; - for (int a = 0; a < (int)prim->attributes_count; ++a) { - const cgltf_attribute* attrib = &prim->attributes[a]; - - if (attrib->type == cgltf_attribute_type_position) { - positions_index = a; - } else if (attrib->type == cgltf_attribute_type_joints) { - joints_index = a; - } - } - - if ((positions_index != -1) && (joints_index != -1)) { - const cgltf_accessor* positions = - prim->attributes[positions_index].data; - const cgltf_accessor* joints = prim->attributes[joints_index].data; - - assert(positions->count == joints->count); - - AccessorIter positions_iter = make_accessor_iter(positions); - AccessorIter joints_iter = make_accessor_iter(joints); - AccessorData position = {0}, joint = {0}; - - while (accessor_iter_next(&positions_iter, &position)) { - const bool advance = accessor_iter_next(&joints_iter, &joint); - assert(advance); // Counts should match. - - const vec3 p = vec3_make(position.x, position.y, position.z); - const int64_t j[4] = {joint.xi, joint.yi, joint.wi, joint.zi}; - - for (int i = 0; i < 4; ++i) { - const size_t joint_index = j[i]; - assert((size_t)joint_index < num_joints); - - joint_descs[joint_index].box = - aabb3_add(joint_descs[joint_index].box, p); - } - } - } - } - } - } - } -} - -/// Find the joint node with the smallest index across all skeletons. -/// -/// The channels in glTF may target arbitrary nodes in the scene (those nodes -/// are the joints). However, we want to map the "base joint" (the joint/node -/// with the smallest index) to 0 in the AnimaDesc's joint array. We can do this -/// by subtracting the "base node index" from every joint index or channel -/// target. -/// -/// There is an assumption in the animation library that joints are contiguous -/// anyway, so this "base joint index" works provided the joint nodes are also -/// contiguous in the glTF. The glTF does not guarantee this, but I think it's -/// a reasonable assumption that exporters write glTF files in such a way, and -/// Blender does appear to do so. -cgltf_size find_base_joint_index(const cgltf_data* data) { - assert(data); - - cgltf_size base_joint_index = (cgltf_size)-1; - - for (cgltf_size s = 0; s < data->skins_count; ++s) { - const cgltf_skin* skin = &data->skins[s]; - for (cgltf_size j = 0; j < skin->joints_count; ++j) { - // Joint is an index/pointer into the nodes array. - const cgltf_size node_index = skin->joints[j] - data->nodes; - assert(node_index < data->nodes_count); - // Min. - if (node_index < base_joint_index) { - base_joint_index = node_index; - } - } - } - - return base_joint_index; -} - -/// Load all skins (Gfx skeletons) from the glTF scene. -/// Return the total number of joints. -static size_t load_skins( - const cgltf_data* data, Buffer* const* buffers, cgltf_size base_joint_index, - AnimaDesc* anima_desc) { - assert(data); - assert(buffers); - assert(anima_desc); - assert(base_joint_index < data->nodes_count); - - // Determines whether the ith joint in the node hierarchy is a joint node. - // This is then used to determine whether a joint is a root of the joint - // hierarchy. - bool is_joint_node[GFX_MAX_NUM_JOINTS] = {false}; - - size_t num_joints = 0; - - for (cgltf_size s = 0; s < data->skins_count; ++s) { - const cgltf_skin* skin = &data->skins[s]; - const cgltf_accessor* matrices_accessor = skin->inverse_bind_matrices; - assert(matrices_accessor->count == skin->joints_count); - - num_joints += skin->joints_count; - assert(num_joints < GFX_MAX_NUM_JOINTS); - - SkeletonDesc* skeleton_desc = &anima_desc->skeletons[s]; - *skeleton_desc = (SkeletonDesc){.num_joints = skin->joints_count}; - - // for (cgltf_size j = 0; j < skin->joints_count; ++j) { - AccessorIter iter = make_accessor_iter(matrices_accessor); - AccessorData matrix = {0}; - for (cgltf_size i = 0; accessor_iter_next(&iter, &matrix); ++i) { - const mat4 inv_bind_matrix = mat4_from_array(matrix.floats); - - // Joint is an index/pointer into the nodes array. - const cgltf_size node_index = skin->joints[i] - data->nodes; - assert(node_index < data->nodes_count); - - const cgltf_size parent_node_index = - skin->joints[i]->parent - data->nodes; - assert(parent_node_index < data->nodes_count); - - // Subtract the base index to pack the joints as tightly as possible in - // the AnimaDesc. - assert(node_index >= base_joint_index); - const cgltf_size joint_index = node_index - base_joint_index; - - assert(parent_node_index >= base_joint_index); - const cgltf_size parent_index = parent_node_index - base_joint_index; - - skeleton_desc->joints[i] = joint_index; - - JointDesc* joint_desc = &anima_desc->joints[joint_index]; - joint_desc->parent = parent_index; - joint_desc->inv_bind_matrix = inv_bind_matrix; - - is_joint_node[joint_index] = true; - }; - - // glTF may specify a "skeleton", which is the root of the skin's - // (skeleton's) node hierarchy. - // if (skin->skeleton) { - // // cgltf_size root_index = skin->skeleton - data->nodes; - // // assert(root_index <= data->nodes_count); - // // root_node = nodes[root_index]; - // assert(false); - //} - } - - // Animation library assumes that joints are contiguous. - for (size_t i = 0; i < num_joints; ++i) { - assert(is_joint_node[i]); - } - - // Insert the root joint. - // This is the root of all skeletons. It is, specifically, the root of all - // joints that do not have a parent; skins (skeletons) in glTF are not - // guaranteed to have a common parent, but are generally a set of disjoint - // trees. - const size_t root_index = num_joints; - assert(root_index < GFX_MAX_NUM_JOINTS); - anima_desc->joints[root_index] = (JointDesc){.parent = INDEX_NONE}; - num_joints++; - - // Make root joints point to the root joint at index N. - // The root joints are the ones that have a non-joint node in the glTF as a - // parent. - for (size_t i = 0; i < root_index; ++i) { - JointDesc* joint = &anima_desc->joints[i]; - if ((joint->parent >= root_index) || !is_joint_node[joint->parent]) { - joint->parent = root_index; - } - } - - return num_joints; -} - -/// Load all animations from the glTF scene. -static void load_animations( - const cgltf_data* data, cgltf_size base_joint_index, - AnimaDesc* anima_desc) { - assert(data); - assert(anima_desc); - assert(base_joint_index < data->nodes_count); - assert(data->animations_count <= GFX_MAX_NUM_ANIMATIONS); - - for (cgltf_size a = 0; a < data->animations_count; ++a) { - const cgltf_animation* animation = &data->animations[a]; - AnimationDesc* animation_desc = &anima_desc->animations[a]; - - *animation_desc = (AnimationDesc){ - .name = sstring_make(animation->name), - .num_channels = animation->channels_count}; - - assert(animation->channels_count <= GFX_MAX_NUM_CHANNELS); - for (cgltf_size c = 0; c < animation->channels_count; ++c) { - const cgltf_animation_channel* channel = &animation->channels[c]; - ChannelDesc* channel_desc = &animation_desc->channels[c]; - const cgltf_animation_sampler* sampler = channel->sampler; - - const size_t target_index = channel->target_node - data->nodes; - assert(target_index < data->nodes_count); - - assert(target_index >= base_joint_index); - const size_t tight_target_index = target_index - base_joint_index; - assert(tight_target_index < anima_desc->num_joints); - - *channel_desc = (ChannelDesc){ - .target = tight_target_index, - .type = from_gltf_animation_path_type(channel->target_path), - .interpolation = from_gltf_interpolation_type(sampler->interpolation), - .num_keyframes = 0}; - - // Read time inputs. - AccessorIter iter = make_accessor_iter(sampler->input); - AccessorData input = {0}; - for (cgltf_size i = 0; accessor_iter_next(&iter, &input); ++i) { - channel_desc->keyframes[i].time = input.x; - channel_desc->num_keyframes++; - } - - // Read transform outputs. - AccessorData output = {0}; - switch (channel->target_path) { - case cgltf_animation_path_type_translation: { - iter = make_accessor_iter(sampler->output); - for (cgltf_size i = 0; accessor_iter_next(&iter, &output); ++i) { - channel_desc->keyframes[i].translation = - vec3_make(output.x, output.y, output.z); - } - break; - } - case cgltf_animation_path_type_rotation: { - iter = make_accessor_iter(sampler->output); - for (cgltf_size i = 0; accessor_iter_next(&iter, &output); ++i) { - channel_desc->keyframes[i].rotation = - qmake(output.x, output.y, output.z, output.w); - } - break; - } - default: - // TODO: Handle other channel transformations. - break; - } - } - } -} - -/// Load all nodes from the glTF scene. -/// -/// This function ignores the many scenes and default scene of the glTF spec -/// and instead just loads all nodes into a single gfx Scene. -static void load_nodes( - const cgltf_data* data, SceneNode* root_node, SceneObject** objects, - SceneCamera** cameras, const Anima* anima, SceneNode** nodes) { - // Note that with glTF 2.0, nodes do not form a DAG / scene graph but a - // disjount union of strict trees: - // - // "For Version 2.0 conformance, the glTF node hierarchy is not a directed - // acyclic graph (DAG) or scene graph, but a disjoint union of strict trees. - // That is, no node may be a direct descendant of more than one node. This - // restriction is meant to simplify implementation and facilitate - // conformance." - // - // This matches the gfx library implementation, where every node can have at - // most one parent. - assert(data); - assert(root_node); - assert(objects); - assert(cameras); - assert(nodes); - - cgltf_size next_camera = 0; - - for (cgltf_size n = 0; n < data->nodes_count; ++n) { - const cgltf_node* node = &data->nodes[n]; - - // Add SceneObject, SceneCamera or Lights. - // TODO: Handle lights once they are implemented in the gfx library. - if (node->mesh) { - const cgltf_size mesh_index = node->mesh - data->meshes; - assert(mesh_index < data->meshes_count); - SceneObject* object = objects[mesh_index]; - gfx_construct_object_node(nodes[n], object); - - if (node->skin) { - assert(anima); - - const cgltf_size skin_index = node->skin - data->skins; - assert(skin_index < data->skins_count); - const Skeleton* skeleton = gfx_get_anima_skeleton(anima, skin_index); - gfx_set_object_skeleton(object, skeleton); - } - } else if (node->camera) { - assert(next_camera < data->cameras_count); - - Camera camera; - const cgltf_camera* cam = node->camera; - - // TODO: We could define a function load_cameras() the same way we load - // every mesh and then remove this ad-hoc loading of cameras here, as well - // as remove 'next_camera'. - switch (cam->type) { - case cgltf_camera_type_orthographic: - camera = camera_orthographic( - 0, cam->data.orthographic.xmag, 0, cam->data.orthographic.ymag, - cam->data.orthographic.znear, cam->data.orthographic.zfar); - break; - case cgltf_camera_type_perspective: - camera = camera_perspective( - cam->data.perspective.yfov, cam->data.perspective.aspect_ratio, - cam->data.perspective.znear, cam->data.perspective.zfar); - break; - case cgltf_camera_type_invalid: - break; - } - - gfx_set_camera_camera(cameras[next_camera], &camera); - gfx_construct_camera_node(nodes[n], cameras[next_camera]); - ++next_camera; - } else { - // TODO: implementation for missing node types. - // These nodes currently default to logical nodes. - } - assert(nodes[n]); - - // Set transform. - mat4 transform; - if (node->has_matrix) { - transform = mat4_from_array(node->matrix); - } else { - transform = mat4_id(); - if (node->has_scale) { - const mat4 scale = mat4_scale(vec3_from_array(node->scale)); - transform = mat4_mul(transform, scale); - } - if (node->has_rotation) { - const quat q = quat_from_array(node->rotation); - const mat4 rotate = mat4_from_quat(q); - transform = mat4_mul(transform, rotate); - } - if (node->has_translation) { - const mat4 translate = - mat4_translate(vec3_from_array(node->translation)); - transform = mat4_mul(translate, transform); - } - } - gfx_set_node_transform(nodes[n], &transform); - - // If this is a top-level node in the glTF scene, set its parent to the - // given root node. - if (!node->parent) { - gfx_set_node_parent(nodes[n], root_node); - } else { - const cgltf_size parent_index = node->parent - data->nodes; - assert(parent_index < data->nodes_count); - SceneNode* parent = nodes[parent_index]; - assert(parent); - gfx_set_node_parent(nodes[n], parent); - } - } // SceneNode. -} - -/// Remove joint nodes from the Gfx Scene. -/// -/// Joint nodes are not needed because joints are packed into the Anima. -static void remove_joint_nodes( - const cgltf_data* data, SceneNode** scene_nodes) { - assert(data); - assert(scene_nodes); - - // This works assuming the joint nodes are contiguous. Contiguity is checked - // when loading skins. See load_skins(). - size_t min_joint_index = (size_t)-1; - size_t max_joint_index = 0; - - // First get the minimum and maximum indices of all joint nodes. - for (cgltf_size s = 0; s < data->skins_count; ++s) { - const cgltf_skin* skin = &data->skins[s]; - - for (cgltf_size j = 0; j < skin->joints_count; ++j) { - // Joint is an index/pointer into the nodes array. - const cgltf_size joint_index = skin->joints[j] - data->nodes; - assert(joint_index < data->nodes_count); - - if (joint_index < min_joint_index) { - min_joint_index = joint_index; - } - if (joint_index > max_joint_index) { - max_joint_index = joint_index; - } - } - } - - assert(min_joint_index < data->nodes_count); - assert(max_joint_index < data->nodes_count); - - // Now walk over the joint nodes. If a joint's parent is itself not a joint - // node, then that joint is a root of a joint hierarchy (skins in glTF may - // have multiple roots). In such case, delete the root joint recursively. - for (cgltf_size s = 0; s < data->skins_count; ++s) { - const cgltf_skin* skin = &data->skins[s]; - - for (cgltf_size j = 0; j < skin->joints_count; ++j) { - // Joint is an index/pointer into the nodes array. - const cgltf_size joint_index = skin->joints[j] - data->nodes; - assert(joint_index < data->nodes_count); - - const cgltf_node* joint = &data->nodes[joint_index]; - - // Parent node index. - const cgltf_size parent_index = joint->parent - data->nodes; - assert(parent_index < data->nodes_count); - - // If the parent is not a joint node, recursively delete this joint node. - if ((parent_index < min_joint_index) || - (parent_index > max_joint_index)) { - gfx_destroy_node(&scene_nodes[joint_index]); - } - } - } -} - -/// Load all scenes from the glTF file. -/// -/// If the scene is loaded from memory, set filepath = null. -/// -/// This function ignores the many scenes and default scene of the glTF spec -/// and instead just loads all scenes into a single Gfx Scene. -static Model* load_scene( - cgltf_data* data, Gfx* gfx, const mstring* filepath, ShaderProgram* shader, - const cgltfTangentBuffer* cgltf_tangent_buffers, - cgltf_size num_tangent_buffers) { - // In a GLTF scene, buffers can be shared among meshes, meshes among nodes, - // etc. Each object is referenced by its index in the relevant array. Here we - // do a button-up construction, first allocating our own graphics objects in - // the same quantities and then re-using the GLTF indices to index these - // arrays. - // - // For simplicity, this function also handles all of the cleanup. Arrays are - // allocated up front, and the helper functions construct their elements. If - // an error is encountered, the helper functions can simply return and this - // function cleans up any intermediate objects that had been created up until - // the point of failure. - // - // Loading animation data: - // - Buffers with animation sampler data need to stay on the CPU, not - // uploaded to the GPU. We could try to implement GPU animation at a later - // stage. - assert(data); - assert(gfx); - assert(filepath); - assert((num_tangent_buffers == 0) || (cgltf_tangent_buffers != 0)); - - bool success = false; - - GfxCore* gfxcore = gfx_get_core(gfx); - const size_t primitive_count = get_total_primitives(data); - - const mstring directory = mstring_dirname(*filepath); - LOGD("Filepath: %s", mstring_cstr(filepath)); - LOGD("Directory: %s", mstring_cstr(&directory)); - - Buffer** tangent_buffers = 0; - Buffer** buffers = 0; - LoadTextureCmd* load_texture_cmds = 0; - const Texture** textures = 0; // Textures are owned by asset cache. - Material** materials = 0; - Geometry** geometries = 0; - Mesh** meshes = 0; - AnimaDesc* anima_desc = 0; - SceneObject** scene_objects = 0; - SceneCamera** scene_cameras = 0; - SceneNode** scene_nodes = 0; - Anima* anima = 0; - SceneNode* root_node = 0; - Model* model = 0; - - tangent_buffers = calloc(num_tangent_buffers, sizeof(Buffer*)); - buffers = calloc(data->buffers_count, sizeof(Buffer*)); - textures = calloc(data->textures_count, sizeof(Texture*)); - materials = calloc(data->materials_count, sizeof(Material*)); - geometries = calloc(primitive_count, sizeof(Geometry*)); - meshes = calloc(primitive_count, sizeof(Mesh*)); - scene_objects = calloc(data->meshes_count, sizeof(SceneObject*)); - scene_cameras = calloc(data->cameras_count, sizeof(SceneCamera**)); - scene_nodes = calloc(data->nodes_count, sizeof(SceneNode**)); - // A glTF scene does not necessarily have textures. Materials can be given - // as constants, for example. - if (data->textures_count > 0) { - load_texture_cmds = calloc(data->textures_count, sizeof(LoadTextureCmd)); - } - - if (!buffers || !tangent_buffers || - ((data->textures_count > 0) && !load_texture_cmds) || !textures || - !materials || !geometries || !meshes || !scene_objects || - !scene_cameras || !scene_nodes) { - goto cleanup; - } - - if ((num_tangent_buffers > 0) && - !load_tangent_buffers( - cgltf_tangent_buffers, num_tangent_buffers, gfxcore, - tangent_buffers)) { - goto cleanup; - } - - if (!load_buffers(data, gfxcore, buffers)) { - goto cleanup; - } - - if (data->textures_count > 0) { - load_textures_lazy( - data, gfxcore, mstring_cstr(&directory), load_texture_cmds); - } - - if (!load_materials(data, gfx, load_texture_cmds, textures, materials)) { - goto cleanup; - } - - if (!load_meshes( - data, gfxcore, buffers, tangent_buffers, cgltf_tangent_buffers, - num_tangent_buffers, materials, shader, primitive_count, geometries, - meshes, scene_objects)) { - goto cleanup; - } - - // Skins refer to nodes, and nodes may refer to skins. To break this circular - // dependency, glTF defines skins in terms of node indices. We could do the - // same if Gfx allowed allocating nodes contiguously in memory. For now, - // create the nodes up front and use the indices of the array to map to the - // node_idx. - for (cgltf_size i = 0; i < data->nodes_count; ++i) { - scene_nodes[i] = gfx_make_node(); - } - - // Create the scene's root node. - // This is an anima node if the scene has skins; otherwise it is a logical - // node. - root_node = gfx_make_node(); - if (data->skins_count > 0) { - anima_desc = calloc(1, sizeof(AnimaDesc)); - if (!anima_desc) { - goto cleanup; - } - - const cgltf_size base = find_base_joint_index(data); - - anima_desc->num_skeletons = data->skins_count; - anima_desc->num_animations = data->animations_count; - anima_desc->num_joints = load_skins(data, buffers, base, anima_desc); - load_animations(data, base, anima_desc); - - compute_joint_bounding_boxes( - data, anima_desc->num_joints, anima_desc->joints); - - anima = gfx_make_anima(anima_desc); - gfx_construct_anima_node(root_node, anima); - } - - // The root node becomes the root of all scene nodes. - load_nodes(data, root_node, scene_objects, scene_cameras, anima, scene_nodes); - - // Clean up scene nodes that correspond to joints in the glTF. These are - // not needed anymore. - if (data->skins_count > 0) { - remove_joint_nodes(data, scene_nodes); - } - - model = gfx_make_model(root_node); - - success = true; - -cleanup: - // The arrays of resources are no longer needed. The resources themselves are - // destroyed only if this function fails. - if (tangent_buffers) { - if (!success) { - for (cgltf_size i = 0; i < num_tangent_buffers; ++i) { - if (tangent_buffers[i]) { - gfx_destroy_buffer(gfxcore, &tangent_buffers[i]); - } - } - } - free(tangent_buffers); - } - if (buffers) { - if (!success) { - for (cgltf_size i = 0; i < data->buffers_count; ++i) { - if (buffers[i]) { - gfx_destroy_buffer(gfxcore, &buffers[i]); - } - } - } - free(buffers); - } - if (load_texture_cmds) { - free(load_texture_cmds); - } - if (textures) { - free(textures); - } - if (materials) { - if (!success) { - for (cgltf_size i = 0; i < data->materials_count; ++i) { - if (materials[i]) { - gfx_destroy_material(&materials[i]); - } - } - } - free(materials); - } - if (geometries) { - if (!success) { - for (size_t i = 0; i < primitive_count; ++i) { - if (geometries[i]) { - gfx_destroy_geometry(gfxcore, &geometries[i]); - } - } - } - free(geometries); - } - if (meshes) { - if (!success) { - for (size_t i = 0; i < primitive_count; ++i) { - if (meshes[i]) { - gfx_destroy_mesh(&meshes[i]); - } - } - } - free(meshes); - } - if (anima_desc) { - free(anima_desc); - } - if (scene_objects) { - if (!success) { - for (cgltf_size i = 0; i < data->meshes_count; ++i) { - if (scene_objects[i]) { - gfx_destroy_object(&scene_objects[i]); - } - } - } - free(scene_objects); - } - if (scene_cameras) { - if (!success) { - for (cgltf_size i = 0; i < data->cameras_count; ++i) { - if (scene_cameras[i]) { - gfx_destroy_camera(&scene_cameras[i]); - } - } - } - free(scene_cameras); - } - if (scene_nodes) { - if (!success) { - for (cgltf_size i = 0; i < data->nodes_count; ++i) { - if (scene_nodes[i]) { - gfx_destroy_node(&scene_nodes[i]); - } - } - } - free(scene_nodes); - } - if (!success) { - if (root_node) { - gfx_destroy_node(&root_node); // Node owns the anima. - } else if (anima) { - gfx_destroy_anima(&anima); - } - } - return model; -} - -Model* gfx_model_load(Gfx* gfx, const LoadModelCmd* cmd) { - assert(gfx); - assert(cmd); - - Model* model = 0; - - cgltf_options options = {0}; - cgltf_data* data = NULL; - cgltfTangentBuffer* tangent_buffers = 0; - - cgltf_result result; - switch (cmd->origin) { - case AssetFromFile: - result = cgltf_parse_file(&options, mstring_cstr(&cmd->filepath), &data); - break; - case AssetFromMemory: - result = cgltf_parse(&options, cmd->data, cmd->size_bytes, &data); - break; - } - if (result != cgltf_result_success) { - goto cleanup; - } - - if (cmd->origin == AssetFromFile) { - // Must call cgltf_load_buffers() to load buffer data. - result = cgltf_load_buffers(&options, data, mstring_cstr(&cmd->filepath)); - if (result != cgltf_result_success) { - goto cleanup; - } - } - - // Compute tangents for normal-mapped models that are missing them. - cgltf_size num_tangent_buffers = 0; - cgltf_compute_tangents( - &options, data, &tangent_buffers, &num_tangent_buffers); - - model = load_scene( - data, gfx, &cmd->filepath, cmd->shader, tangent_buffers, - num_tangent_buffers); - -cleanup: - if (data) { - cgltf_free(data); - } - if (tangent_buffers) { - free(tangent_buffers); - } - return model; -} diff --git a/gfx/src/asset/model.h b/gfx/src/asset/model.h deleted file mode 100644 index d6399b1..0000000 --- a/gfx/src/asset/model.h +++ /dev/null @@ -1,12 +0,0 @@ -/// Load scene files. -#pragma once - -#include - -typedef struct Gfx Gfx; -typedef struct Model Model; - -/// Load a model. -/// -/// Currently only supports the GLTF format. -Model* gfx_model_load(Gfx*, const LoadModelCmd*); diff --git a/gfx/src/asset/texture.c b/gfx/src/asset/texture.c deleted file mode 100644 index c790394..0000000 --- a/gfx/src/asset/texture.c +++ /dev/null @@ -1,177 +0,0 @@ -#include "texture.h" - -#include "gfx/core.h" - -#include "error.h" - -#define STB_IMAGE_IMPLEMENTATION -#include "stb_image.h" - -#include - -static void flip_horizontally( - unsigned char* pixels, int width, int height, int components) { - assert(pixels); - - for (int y = 0; y < height; ++y) { - for (int x = 0; x < width / 2; ++x) { - unsigned char* p1 = &pixels[(y * width + x) * components]; - unsigned char* p2 = &pixels[(y * width + (width - x - 1)) * components]; - - for (int c = 0; c < components; ++c) { - unsigned char tmp = *p1; - *p1 = *p2; - *p2 = tmp; - p1++; - p2++; - } - } - } -} - -// Note that the cubemap coordinate system uses the one in RenderMan: -// -// https://www.khronos.org/opengl/wiki/Cubemap_Texture -// -// This is what happens: -// -// - Cubemaps follow a left-handed coordinate system. Say, +X is right, +Y is -// up, and +Z is forward. -// - The texture coordinate system follow's DirectX's, so +V goes down, not up -// like it does in OpenGL. -// -// For this reason, we do X and Y flips when doing cubemap textures so that we -// can sample cubemaps as if they were given in the usual OpenGL coordinate -// system. -Texture* gfx_texture_load(GfxCore* gfxcore, const LoadTextureCmd* cmd) { - assert(gfxcore); - assert(cmd); - assert(cmd->origin == AssetFromFile || cmd->origin == AssetFromMemory); - assert(cmd->type == LoadTexture || cmd->type == LoadCubemap); - - int width, height, components, old_components; - unsigned char* pixels[6] = {0}; - - switch (cmd->origin) { - case AssetFromFile: - switch (cmd->type) { - case LoadTexture: { - const char* filepath = mstring_cstr(&cmd->data.texture.filepath); - stbi_set_flip_vertically_on_load(0); - pixels[0] = stbi_load(filepath, &width, &height, &components, 0); - if (!pixels[0]) { - log_error("Failed to load texture file: %s", filepath); - } - break; - } - case LoadCubemap: - for (int i = 0; i < 6; ++i) { - // Flip +Y and -Y textures vertically. - stbi_set_flip_vertically_on_load(((i == 2) || (i == 3)) ? 1 : 0); - const char* filepath = - mstring_cstr(&cmd->data.cubemap.filepaths.filepath_pos_x + i); - stbi_uc* image_pixels = - stbi_load(filepath, &width, &height, &components, 0); - if (!image_pixels) { - log_error("Failed to load texture file: %s", filepath); - break; - } - if (i > 0 && components != old_components) { - log_error("All textures in a cubemap must have the same number of " - "components"); - break; - } - if ((i != 2) && (i != 3)) { - flip_horizontally(image_pixels, width, height, components); - } - pixels[i] = image_pixels; - old_components = components; - } - break; - } - break; - case AssetFromMemory: - // TODO: Load textures from memory. - log_error("Loading textures from memory is not yet implemented"); - return 0; - } - - // Error out if we failed to load a texture. - if (!pixels[0] || - (cmd->type == LoadCubemap && - (!pixels[1] || !pixels[2] || !pixels[3] || !pixels[4] || !pixels[5]))) { - for (int i = 0; i < 6; ++i) { - if (pixels[i]) { - stbi_image_free(pixels[i]); - } - } - return 0; - } - - TextureDesc desc = (TextureDesc){0}; - desc.width = width; - desc.height = height; - - switch (cmd->type) { - case LoadTexture: - desc.dimension = Texture2D; - break; - case LoadCubemap: - desc.dimension = TextureCubeMap; - break; - } - - switch (components) { - case 3: - switch (cmd->colour_space) { - case LinearColourSpace: - desc.format = TextureRGB8; - break; - case sRGB: - desc.format = TextureSRGB8; - break; - default: - log_error("Unsupported texture colour space: %d", cmd->colour_space); - return 0; - } - break; - case 4: - switch (cmd->colour_space) { - case LinearColourSpace: - desc.format = TextureRGBA8; - break; - case sRGB: - desc.format = TextureSRGBA8; - break; - default: - log_error("Unsupported texture colour space: %d", cmd->colour_space); - return 0; - } - break; - default: - log_error("Unsupported number of texture components: %d", components); - return 0; - } - - desc.filtering = cmd->filtering; - desc.mipmaps = cmd->mipmaps; - - switch (cmd->type) { - case LoadTexture: - desc.data.pixels = pixels[0]; - break; - case LoadCubemap: - for (int i = 0; i < 6; ++i) { - *(&desc.data.cubemap.pixels_pos_x + i) = pixels[i]; - } - break; - } - - Texture* texture = gfx_make_texture(gfxcore, &desc); - for (int i = 0; i < 6; ++i) { - if (pixels[i]) { - stbi_image_free(pixels[i]); - } - } - return texture; -} diff --git a/gfx/src/asset/texture.h b/gfx/src/asset/texture.h deleted file mode 100644 index 0d38bd9..0000000 --- a/gfx/src/asset/texture.h +++ /dev/null @@ -1,7 +0,0 @@ -/// Load textures from images. -#pragma once - -#include - -/// Load a texture. -Texture* gfx_texture_load(GfxCore*, const LoadTextureCmd*); diff --git a/gfx/src/core/buffer.c b/gfx/src/core/buffer.c deleted file mode 100644 index 3b7e4bc..0000000 --- a/gfx/src/core/buffer.c +++ /dev/null @@ -1,85 +0,0 @@ -#include "buffer.h" - -#include -#include - -#include -#include -#include - -static size_t get_buffer_size_bytes( - BufferType type, const BufferDataDesc* desc) { - return desc->count * gfx_get_buffer_type_size_bytes(type); -} - -static GLenum get_buffer_usage(BufferUsage usage) { - switch (usage) { - case BufferStatic: - return GL_STATIC_DRAW; - case BufferDynamic: - return GL_DYNAMIC_DRAW; - } - FAIL("Unhandled buffer usage"); - return GL_STATIC_DRAW; -} - -size_t gfx_get_buffer_type_size_bytes(BufferType type) { - switch (type) { - case BufferUntyped: - return 1; - case Buffer2d: - return sizeof(vec2); - case Buffer3d: - return sizeof(vec3); - case Buffer4d: - return sizeof(vec4); - case BufferFloat: - return sizeof(float); - case BufferU8: - return sizeof(uint8_t); - case BufferU16: - return sizeof(uint16_t); - } - FAIL("Unhandled buffer type"); - return 0; -} - -bool gfx_init_buffer(Buffer* buffer, const BufferDesc* desc) { - assert(buffer); - - buffer->type = desc->type; - buffer->usage = desc->usage; - buffer->size_bytes = get_buffer_size_bytes(desc->type, &desc->data); - const GLenum usage = get_buffer_usage(desc->usage); - - glGenBuffers(1, &buffer->vbo); - glBindBuffer(GL_ARRAY_BUFFER, buffer->vbo); - glBufferData(GL_ARRAY_BUFFER, buffer->size_bytes, desc->data.data, usage); - glBindBuffer(GL_ARRAY_BUFFER, 0); - ASSERT_GL; - - return true; -} - -void gfx_del_buffer(Buffer* buffer) { - assert(buffer); - if (buffer->vbo) { - glDeleteBuffers(1, &buffer->vbo); - buffer->vbo = 0; - } -} - -void gfx_update_buffer(Buffer* buffer, const BufferDataDesc* desc) { - assert(buffer); - assert(desc); - // OpenGL allows updating static buffers, but it is not optimal for - // performance, so we enforce data in static buffers remain static. - assert(buffer->usage == BufferDynamic); - - const size_t update_size_bytes = get_buffer_size_bytes(buffer->type, desc); - assert(update_size_bytes <= buffer->size_bytes); - - glBindBuffer(GL_ARRAY_BUFFER, buffer->vbo); - glBufferSubData(GL_ARRAY_BUFFER, 0, update_size_bytes, desc->data); - glBindBuffer(GL_ARRAY_BUFFER, 0); -} diff --git a/gfx/src/core/buffer.h b/gfx/src/core/buffer.h deleted file mode 100644 index b9080f0..0000000 --- a/gfx/src/core/buffer.h +++ /dev/null @@ -1,26 +0,0 @@ -#pragma once - -#include - -#include "gl_util.h" - -#include - -#include -#include - -typedef struct Buffer { - GLuint vbo; - BufferType type; - BufferUsage usage; - size_t size_bytes; -} Buffer; - -/// Return the buffer type size in bytes. -size_t gfx_get_buffer_type_size_bytes(BufferType); - -/// Create a buffer from raw data. -bool gfx_init_buffer(Buffer*, const BufferDesc*); - -/// Destroy the buffer. -void gfx_del_buffer(Buffer*); diff --git a/gfx/src/core/constants.h b/gfx/src/core/constants.h deleted file mode 100644 index a6a3b94..0000000 --- a/gfx/src/core/constants.h +++ /dev/null @@ -1,9 +0,0 @@ -#pragma once - -// Shaders vertex attribute locations must match the channels here. -#define GFX_POSITION_CHANNEL 0 -#define GFX_NORMAL_CHANNEL 1 -#define GFX_TANGENT_CHANNEL 2 -#define GFX_TEXCOORDS_CHANNEL 3 -#define GFX_JOINTS_CHANNEL 4 -#define GFX_WEIGHTS_CHANNEL 5 diff --git a/gfx/src/core/core.c b/gfx/src/core/core.c deleted file mode 100644 index 90038c6..0000000 --- a/gfx/src/core/core.c +++ /dev/null @@ -1,429 +0,0 @@ -#include "core_impl.h" - -#include "gl_util.h" - -// #include - -#include - -void gfx_init_gfxcore(GfxCore* gfxcore) { - assert(gfxcore); - - mempool_make(&gfxcore->buffers); - mempool_make(&gfxcore->framebuffers); - mempool_make(&gfxcore->geometries); - mempool_make(&gfxcore->renderbuffers); - mempool_make(&gfxcore->shaders); - mempool_make(&gfxcore->shader_programs); - mempool_make(&gfxcore->textures); - - mempool_make(&gfxcore->shader_cache); - mempool_make(&gfxcore->program_cache); - - glEnable(GL_CULL_FACE); - glFrontFace(GL_CCW); - glCullFace(GL_BACK); - - glEnable(GL_DEPTH_TEST); - - // Filter cubemaps across their faces to avoid seams. - // https://www.khronos.org/opengl/wiki/Cubemap_Texture#Seamless_cubemap - glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); -} - -// Conveniently destroy any objects that have not been destroyed by the -// application. -void gfx_del_gfxcore(GfxCore* gfxcore) { - assert(gfxcore); - - mempool_foreach(&gfxcore->buffers, buffer, { gfx_del_buffer(buffer); }); - - mempool_foreach(&gfxcore->framebuffers, framebuffer, { - gfx_del_framebuffer(framebuffer); - }); - - mempool_foreach( - &gfxcore->geometries, geometry, { gfx_del_geometry(geometry); }); - - mempool_foreach(&gfxcore->renderbuffers, renderbuffer, { - gfx_del_renderbuffer(renderbuffer); - }); - - mempool_foreach( - &gfxcore->shader_programs, prog, { gfx_del_shader_program(prog); }); - - mempool_foreach(&gfxcore->shaders, shader, { gfx_del_shader(shader); }); - - mempool_foreach(&gfxcore->textures, texture, { gfx_del_texture(texture); }); -} - -// ----------------------------------------------------------------------------- -// Render commands. -// ----------------------------------------------------------------------------- - -void gfx_start_frame(GfxCore* gfxcore) { - assert(gfxcore); - - glViewport( - gfxcore->viewport.x, gfxcore->viewport.y, gfxcore->viewport.width, - gfxcore->viewport.height); - glClearColor(0, 0, 0, 0); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - - ASSERT_GL; -} - -void gfx_end_frame(GfxCore* gfxcore) { - assert(gfxcore); - ASSERT_GL; -} - -void gfx_set_viewport(GfxCore* gfxcore, int x, int y, int width, int height) { - assert(gfxcore); - gfxcore->viewport = - (Viewport){.x = x, .y = y, .width = width, .height = height}; -} - -void gfx_get_viewport( - GfxCore* gfxcore, int* x, int* y, int* width, int* height) { - assert(gfxcore); - assert(x); - assert(y); - assert(width); - assert(height); - - *x = gfxcore->viewport.x; - *y = gfxcore->viewport.y; - *width = gfxcore->viewport.width; - *height = gfxcore->viewport.height; -} - -void gfx_clear(GfxCore* gfxcore, vec4 colour) { - assert(gfxcore); - - glClearColor(colour.x, colour.y, colour.z, colour.w); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); -} - -void gfx_set_blending(GfxCore* gfxcore, bool enable) { - assert(gfxcore); - if (enable) { - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - } else { - glDisable(GL_BLEND); - } -} - -void gfx_set_depth_mask(GfxCore* gfxcore, bool enable) { - assert(gfxcore); - glDepthMask(enable ? GL_TRUE : GL_FALSE); -} - -void gfx_set_culling(GfxCore* gfxcore, bool enable) { - assert(gfxcore); - if (enable) { - glEnable(GL_CULL_FACE); - } else { - glDisable(GL_CULL_FACE); - } -} - -void gfx_set_polygon_offset(GfxCore* gfxcore, float scale, float bias) { - assert(gfxcore); - if ((scale != 0.0f) || (bias != 0.0f)) { - glEnable(GL_POLYGON_OFFSET_FILL); - } else { - glDisable(GL_POLYGON_OFFSET_FILL); - } - glPolygonOffset(scale, bias); -} - -void gfx_reset_polygon_offset(GfxCore* gfxcore) { - assert(gfxcore); - glPolygonOffset(0, 0); - glDisable(GL_POLYGON_OFFSET_FILL); -} - -// ----------------------------------------------------------------------------- -// Buffers. -// ----------------------------------------------------------------------------- - -Buffer* gfx_make_buffer(GfxCore* gfxcore, const BufferDesc* desc) { - assert(gfxcore); - assert(desc); - - Buffer* buffer = mempool_alloc(&gfxcore->buffers); - if (!gfx_init_buffer(buffer, desc)) { - mempool_free(&gfxcore->buffers, &buffer); - return 0; - } - return buffer; -} - -void gfx_destroy_buffer(GfxCore* gfxcore, Buffer** buffer) { - assert(gfxcore); - assert(buffer); - if (*buffer) { - gfx_del_buffer(*buffer); - mempool_free(&gfxcore->buffers, buffer); - } -} - -// ----------------------------------------------------------------------------- -// Geometry. -// ----------------------------------------------------------------------------- - -Geometry* gfx_make_geometry(GfxCore* gfxcore, const GeometryDesc* desc) { - assert(gfxcore); - assert(desc); - - Geometry* geometry = mempool_alloc(&gfxcore->geometries); - if (!gfx_init_geometry(geometry, gfxcore, desc)) { - mempool_free(&gfxcore->geometries, &geometry); - return 0; - } - return geometry; -} - -void gfx_destroy_geometry(GfxCore* gfxcore, Geometry** geometry) { - assert(gfxcore); - assert(geometry); - - if (*geometry) { - gfx_del_geometry(*geometry); - mempool_free(&gfxcore->geometries, geometry); - } -} - -// ----------------------------------------------------------------------------- -// Textures. -// ----------------------------------------------------------------------------- - -Texture* gfx_make_texture(GfxCore* gfxcore, const TextureDesc* desc) { - assert(gfxcore); - assert(desc); - - Texture* texture = mempool_alloc(&gfxcore->textures); - if (!gfx_init_texture(texture, desc)) { - mempool_free(&gfxcore->textures, &texture); - return 0; - } - return texture; -} - -void gfx_destroy_texture(GfxCore* gfxcore, Texture** texture) { - assert(gfxcore); - assert(texture); - assert(*texture); - - if (*texture) { - gfx_del_texture(*texture); - mempool_free(&gfxcore->textures, texture); - } -} - -// ----------------------------------------------------------------------------- -// Renderbuffers. -// ----------------------------------------------------------------------------- - -RenderBuffer* gfx_make_renderbuffer( - GfxCore* gfxcore, const RenderBufferDesc* desc) { - assert(gfxcore); - assert(desc); - - RenderBuffer* renderbuffer = mempool_alloc(&gfxcore->renderbuffers); - if (!gfx_init_renderbuffer(renderbuffer, desc)) { - mempool_free(&gfxcore->renderbuffers, &renderbuffer); - } - return renderbuffer; -} - -void gfx_destroy_renderbuffer(GfxCore* gfxcore, RenderBuffer** renderbuffer) { - assert(gfxcore); - assert(renderbuffer); - assert(*renderbuffer); - - if (*renderbuffer) { - gfx_del_renderbuffer(*renderbuffer); - mempool_free(&gfxcore->renderbuffers, renderbuffer); - } -} - -// ----------------------------------------------------------------------------- -// Framebuffers. -// ----------------------------------------------------------------------------- - -FrameBuffer* gfx_make_framebuffer( - GfxCore* gfxcore, const FrameBufferDesc* desc) { - assert(gfxcore); - assert(desc); - - FrameBuffer* framebuffer = mempool_alloc(&gfxcore->framebuffers); - if (!gfx_init_framebuffer(framebuffer, desc)) { - mempool_free(&gfxcore->framebuffers, &framebuffer); - return 0; - } - return framebuffer; -} - -void gfx_destroy_framebuffer(GfxCore* gfxcore, FrameBuffer** framebuffer) { - assert(gfxcore); - assert(framebuffer); - assert(*framebuffer); - - if (*framebuffer) { - gfx_del_framebuffer(*framebuffer); - mempool_free(&gfxcore->framebuffers, framebuffer); - } -} - -// ----------------------------------------------------------------------------- -// Shaders. -// ----------------------------------------------------------------------------- - -static uint64_t hash_shader_desc(const ShaderDesc* desc) { - assert(desc); - // Note that defines may affect shader permutations, so we need to hash those - // as well. - uint64_t hash = 0; - for (size_t i = 0; i < desc->num_defines; ++i) { - const ShaderCompilerDefine* define = &desc->defines[i]; - hash = (((hash << 13) + sstring_hash(define->name)) << 7) + - sstring_hash(define->value); - } - return (hash << 17) + cstring_hash(desc->code); -} - -static uint64_t hash_program_desc(const ShaderProgramDesc* desc) { - assert(desc); - return ((uint64_t)desc->vertex_shader->id << 32) | - (uint64_t)desc->fragment_shader->id; -} - -static Shader* find_cached_shader(ShaderCache* cache, uint64_t hash) { - assert(cache); - mempool_foreach(cache, entry, { - if (entry->hash == hash) { - return entry->shader; - } - }); - return 0; -} - -static ShaderProgram* find_cached_program(ProgramCache* cache, uint64_t hash) { - assert(cache); - mempool_foreach(cache, entry, { - if (entry->hash == hash) { - return entry->program; - } - }); - return 0; -} - -static ShaderCacheEntry* find_shader_cache_entry( - ShaderCache* cache, const Shader* shader) { - assert(cache); - assert(shader); - mempool_foreach(cache, entry, { - if (entry->shader == shader) { - return entry; - } - }); - return 0; -} - -static ShaderProgramCacheEntry* find_program_cache_entry( - ProgramCache* cache, const ShaderProgram* prog) { - assert(cache); - assert(prog); - mempool_foreach(cache, entry, { - if (entry->program == prog) { - return entry; - } - }); - return 0; -} - -Shader* gfx_make_shader(GfxCore* gfxcore, const ShaderDesc* desc) { - assert(gfxcore); - assert(desc); - - // Check the shader cache first. - ShaderCache* cache = &gfxcore->shader_cache; - const uint64_t hash = hash_shader_desc(desc); - Shader* shader = find_cached_shader(cache, hash); - if (shader) { - // LOGD("Found cached shader with hash [%lx]", hash); - return shader; - } - - shader = mempool_alloc(&gfxcore->shaders); - if (!shader) { - return 0; - } - if (!gfx_compile_shader(shader, desc)) { - mempool_free(&gfxcore->shaders, &shader); - return 0; - } - ShaderCacheEntry* entry = mempool_alloc(cache); - *entry = (ShaderCacheEntry){.hash = hash, .shader = shader}; - // LOGD("Added shader with hash [%lx] to cache", hash); - return shader; -} - -void gfx_destroy_shader(GfxCore* gfxcore, Shader** shader) { - assert(gfxcore); - assert(shader); - - if (*shader) { - // Remove the shader from the cache. - ShaderCache* cache = &gfxcore->shader_cache; - ShaderCacheEntry* entry = find_shader_cache_entry(cache, *shader); - assert(entry); // Must be there, shaders can't go untracked. - mempool_free(cache, &entry); - - gfx_del_shader(*shader); - mempool_free(&gfxcore->shaders, shader); - } -} - -ShaderProgram* gfx_make_shader_program( - GfxCore* gfxcore, const ShaderProgramDesc* desc) { - assert(gfxcore); - assert(desc); - - // Check the shader program cache first. - ProgramCache* cache = &gfxcore->program_cache; - const uint64_t hash = hash_program_desc(desc); - ShaderProgram* prog = find_cached_program(cache, hash); - if (prog) { - // LOGD("Found cached shader program with hash [%lx]", hash); - return prog; - } - - prog = mempool_alloc(&gfxcore->shader_programs); - if (!gfx_build_shader_program(prog, desc)) { - mempool_free(&gfxcore->shader_programs, &prog); - return 0; - } - ShaderProgramCacheEntry* entry = mempool_alloc(cache); - *entry = (ShaderProgramCacheEntry){.hash = hash, .program = prog}; - // LOGD("Added shader program with hash [%lx] to cache", hash); - return prog; -} - -void gfx_destroy_shader_program(GfxCore* gfxcore, ShaderProgram** prog) { - assert(gfxcore); - assert(prog); - if (*prog) { - // Remove the shader program from the cache. - ProgramCache* cache = &gfxcore->program_cache; - ShaderProgramCacheEntry* entry = find_program_cache_entry(cache, *prog); - assert(entry); // Must be there, shaders can't go untracked. - mempool_free(cache, &entry); - - gfx_del_shader_program(*prog); - mempool_free(&gfxcore->shader_programs, prog); - } -} diff --git a/gfx/src/core/core_impl.h b/gfx/src/core/core_impl.h deleted file mode 100644 index eefdfbe..0000000 --- a/gfx/src/core/core_impl.h +++ /dev/null @@ -1,68 +0,0 @@ -#pragma once - -#include -#include - -#include "buffer.h" -#include "framebuffer.h" -#include "geometry.h" -#include "renderbuffer.h" -#include "shader.h" -#include "shader_program.h" -#include "texture.h" - -#include - -#include - -// TODO: Make a generic (hash, void*) structure and define functions over it. -// Then define a macro that defines type-safe macros given the type of the -// entry. -typedef struct ShaderCacheEntry { - uint64_t hash; - Shader* shader; -} ShaderCacheEntry; - -typedef struct ShaderProgramCacheEntry { - uint64_t hash; - ShaderProgram* program; -} ShaderProgramCacheEntry; - -DEF_MEMPOOL(buffer_pool, Buffer, GFX_MAX_NUM_BUFFERS) -DEF_MEMPOOL(framebuffer_pool, FrameBuffer, GFX_MAX_NUM_FRAMEBUFFERS) -DEF_MEMPOOL(geometry_pool, Geometry, GFX_MAX_NUM_GEOMETRIES) -DEF_MEMPOOL(renderbuffer_pool, RenderBuffer, GFX_MAX_NUM_RENDERBUFFERS) -DEF_MEMPOOL(shader_pool, Shader, GFX_MAX_NUM_SHADERS) -DEF_MEMPOOL(shader_program_pool, ShaderProgram, GFX_MAX_NUM_SHADER_PROGRAMS) -DEF_MEMPOOL(texture_pool, Texture, GFX_MAX_NUM_TEXTURES) - -DEF_MEMPOOL(ShaderCache, ShaderCacheEntry, GFX_MAX_NUM_SHADERS) -DEF_MEMPOOL(ProgramCache, ShaderProgramCacheEntry, GFX_MAX_NUM_SHADER_PROGRAMS) - -typedef struct { - int x; - int y; - int width; - int height; -} Viewport; - -typedef struct GfxCore { - Viewport viewport; - // mempools for render-specific objects: textures, geometry, etc. - buffer_pool buffers; - framebuffer_pool framebuffers; - geometry_pool geometries; - renderbuffer_pool renderbuffers; - shader_pool shaders; - shader_program_pool shader_programs; - texture_pool textures; - // Caches. - ShaderCache shader_cache; - ProgramCache program_cache; -} GfxCore; - -/// Create a new render backend. -void gfx_init_gfxcore(GfxCore*); - -/// Destroy the render backend. -void gfx_del_gfxcore(GfxCore*); diff --git a/gfx/src/core/framebuffer.c b/gfx/src/core/framebuffer.c deleted file mode 100644 index 76d9002..0000000 --- a/gfx/src/core/framebuffer.c +++ /dev/null @@ -1,151 +0,0 @@ -#include "framebuffer.h" - -#include "renderbuffer.h" -#include "texture.h" - -#include - -#include - -static void framebuffer_attach_colour( - FrameBuffer* framebuffer, const FrameBufferAttachment* attachment) { - assert(framebuffer); - assert(attachment); - - switch (attachment->type) { - case FrameBufferNoAttachment: - break; - case FrameBufferTexture: - glFramebufferTexture2D( - GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, - attachment->texture.texture->id, attachment->texture.mip_level); - break; - case FrameBufferCubemapTexture: - glFramebufferTexture2D( - GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, - to_GL_cubemap_face(attachment->cubemap.face), - attachment->cubemap.texture->id, attachment->cubemap.mip_level); - break; - case FrameBufferRenderBuffer: - glFramebufferRenderbuffer( - GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, - attachment->renderbuffer->id); - break; - } - - ASSERT_GL; -} - -static void framebuffer_attach_depth( - FrameBuffer* framebuffer, const FrameBufferAttachment* attachment) { - assert(framebuffer); - assert(attachment); - - switch (attachment->type) { - case FrameBufferNoAttachment: - break; - case FrameBufferTexture: - glFramebufferTexture2D( - GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_DEPTH_COMPONENT, - attachment->texture.texture->id, attachment->texture.mip_level); - break; - // TODO: Could distinguish between colour and depth attachment types to make - // this a compile-time error. - case FrameBufferCubemapTexture: - log_error("Cannot use a cubemap texture as a depth framebuffer attachment"); - break; - case FrameBufferRenderBuffer: - glFramebufferRenderbuffer( - GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, - attachment->renderbuffer->id); - break; - } - - ASSERT_GL; -} - -bool gfx_init_framebuffer( - FrameBuffer* framebuffer, const FrameBufferDesc* desc) { - assert(framebuffer); - assert(desc); - - glGenFramebuffers(1, &framebuffer->id); - if (!framebuffer->id) { - log_error("glGenFramebuffers() failed"); - return false; - } - - // Allow incomplete framebuffers for flexibility. - // Attach buffers and check the framebuffer status only if buffers are given - // up front. - if (desc->colour.type != FrameBufferNoAttachment || - desc->depth.type != FrameBufferNoAttachment) { - // TODO: Could use the "named" API to avoid having to bind the framebuffer. - glBindFramebuffer(GL_FRAMEBUFFER, framebuffer->id); - framebuffer_attach_colour(framebuffer, &desc->colour); - framebuffer_attach_depth(framebuffer, &desc->depth); - if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { - log_error("glCheckFramebufferStatus() failed"); - gfx_del_framebuffer(framebuffer); - return false; - } - glBindFramebuffer(GL_FRAMEBUFFER, 0); - } - - ASSERT_GL; - return true; -} - -bool gfx_framebuffer_attach_colour( - FrameBuffer* framebuffer, const FrameBufferAttachment* attachment) { - assert(framebuffer); - assert(attachment); - - // TODO: Could use the "named" API to avoid having to bind the framebuffer. - glBindFramebuffer(GL_FRAMEBUFFER, framebuffer->id); - framebuffer_attach_colour(framebuffer, attachment); - if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { - log_error("glCheckFramebufferStatus() failed"); - return false; - } - return true; -} - -bool gfx_framebuffer_attach_depth( - FrameBuffer* framebuffer, const FrameBufferAttachment* attachment) { - assert(framebuffer); - assert(attachment); - - // TODO: Could use the "named" API to avoid having to bind the framebuffer. - glBindFramebuffer(GL_FRAMEBUFFER, framebuffer->id); - framebuffer_attach_depth(framebuffer, attachment); - if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { - log_error("glCheckFramebufferStatus() failed"); - return false; - } - return true; -} - -void gfx_del_framebuffer(FrameBuffer* framebuffer) { - assert(framebuffer); - if (framebuffer->id) { - glDeleteFramebuffers(1, &framebuffer->id); - framebuffer->id = 0; - } -} - -void gfx_activate_framebuffer(const FrameBuffer* framebuffer) { - assert(framebuffer); - glBindFramebuffer(GL_FRAMEBUFFER, framebuffer->id); -} - -void gfx_deactivate_framebuffer(const FrameBuffer* framebuffer) { - assert(framebuffer); - glBindFramebuffer(GL_FRAMEBUFFER, 0); -} - -void gfx_framebuffer_set_viewport( - FrameBuffer* framebuffer, int x, int y, int width, int height) { - assert(framebuffer); - glViewport(x, y, width, height); -} diff --git a/gfx/src/core/framebuffer.h b/gfx/src/core/framebuffer.h deleted file mode 100644 index 1a3439c..0000000 --- a/gfx/src/core/framebuffer.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once - -#include - -#include "gl_util.h" - -typedef struct FrameBuffer { - GLuint id; -} FrameBuffer; - -/// Create a new framebuffer. -bool gfx_init_framebuffer(FrameBuffer*, const FrameBufferDesc*); - -/// Destroy the framebuffer. -void gfx_del_framebuffer(FrameBuffer*); diff --git a/gfx/src/core/geometry.c b/gfx/src/core/geometry.c deleted file mode 100644 index cfc749f..0000000 --- a/gfx/src/core/geometry.c +++ /dev/null @@ -1,326 +0,0 @@ -#include "geometry.h" - -#include "buffer.h" -#include "constants.h" - -#include - -#include -#include - -/// Determines whether a view is populated. -/// -/// Note that views are allowed to have no data, in which case a buffer of the -/// specified size is created. -#define view_is_populated(BUFFER_VIEW) (BUFFER_VIEW.size_bytes > 0) - -static GLenum primitive_type_to_gl(PrimitiveType type) { - switch (type) { - case Triangles: - return GL_TRIANGLES; - case TriangleFan: - return GL_TRIANGLE_FAN; - case TriangleStrip: - return GL_TRIANGLE_STRIP; - } - FAIL("primitive_type_to_gl(): missing case"); - return GL_INVALID_ENUM; -} - -/// Create a typed buffer for the buffer view if the view does not already point -/// to a buffer. -void init_view_buffer( - GfxCore* gfxcore, BufferView* view, BufferType buffer_type, - BufferUsage buffer_usage) { - if (!view->buffer) { - view->buffer = gfx_make_buffer( - gfxcore, - &(BufferDesc){ - .usage = buffer_usage, - .type = buffer_type, - .data.data = view->data, - .data.count = view->size_bytes / - gfx_get_buffer_type_size_bytes(buffer_type)}); - } - assert(view->size_bytes <= view->buffer->size_bytes); -} - -/// Configure the buffer in teh VAO. -static void configure_buffer( - GfxCore* gfxcore, const GeometryDesc* desc, BufferView* view, - size_t num_components, size_t component_size_bytes, GLenum component_type, - GLboolean normalized, GLuint channel) { - assert(gfxcore); - assert(desc); - assert(view); - assert(view->buffer); - assert( - desc->num_verts <= - view->size_bytes / (num_components * component_size_bytes)); - assert(view->size_bytes <= view->buffer->size_bytes); - - glBindBuffer(GL_ARRAY_BUFFER, view->buffer->vbo); - glEnableVertexAttribArray(channel); - if ((component_type == GL_FLOAT) || normalized) { - glVertexAttribPointer( - channel, num_components, component_type, normalized, view->stride_bytes, - (const void*)view->offset_bytes); - } else { - assert(!normalized); - assert( - (component_type == GL_BYTE) || (component_type == GL_UNSIGNED_BYTE) || - (component_type == GL_SHORT) || (component_type == GL_UNSIGNED_SHORT) || - (component_type == GL_INT) || component_type == GL_UNSIGNED_INT); - glVertexAttribIPointer( - channel, num_components, component_type, view->stride_bytes, - (const void*)view->offset_bytes); - } - glBindBuffer(GL_ARRAY_BUFFER, 0); -} - -static bool configure_vertex_attributes(GfxCore* gfxcore, GeometryDesc* desc) { - assert(gfxcore); - assert(desc); - - if (view_is_populated(desc->positions3d)) { - init_view_buffer( - gfxcore, (BufferView*)&desc->positions3d, Buffer3d, desc->buffer_usage); - if (!desc->positions3d.buffer) { - return false; - } - configure_buffer( - gfxcore, desc, (BufferView*)&desc->positions3d, 3, sizeof(float), - GL_FLOAT, GL_FALSE, GFX_POSITION_CHANNEL); - } else if (view_is_populated(desc->positions2d)) { - init_view_buffer( - gfxcore, (BufferView*)&desc->positions2d, Buffer2d, desc->buffer_usage); - if (!desc->positions2d.buffer) { - return false; - } - configure_buffer( - gfxcore, desc, (BufferView*)&desc->positions2d, 2, sizeof(float), - GL_FLOAT, GL_FALSE, GFX_POSITION_CHANNEL); - } - if (view_is_populated(desc->normals)) { - init_view_buffer( - gfxcore, (BufferView*)&desc->normals, Buffer3d, desc->buffer_usage); - if (!desc->normals.buffer) { - return false; - } - configure_buffer( - gfxcore, desc, (BufferView*)&desc->normals, 3, sizeof(float), GL_FLOAT, - GL_FALSE, GFX_NORMAL_CHANNEL); - } - if (view_is_populated(desc->tangents)) { - init_view_buffer( - gfxcore, (BufferView*)&desc->tangents, Buffer4d, desc->buffer_usage); - if (!desc->tangents.buffer) { - return false; - } - configure_buffer( - gfxcore, desc, (BufferView*)&desc->tangents, 4, sizeof(float), GL_FLOAT, - GL_FALSE, GFX_TANGENT_CHANNEL); - } - if (view_is_populated(desc->texcoords)) { - init_view_buffer( - gfxcore, (BufferView*)&desc->texcoords, Buffer2d, desc->buffer_usage); - if (!desc->texcoords.buffer) { - return false; - } - configure_buffer( - gfxcore, desc, (BufferView*)&desc->texcoords, 2, sizeof(float), - GL_FLOAT, GL_FALSE, GFX_TEXCOORDS_CHANNEL); - } - if (view_is_populated(desc->joints.u8)) { - init_view_buffer( - gfxcore, (BufferView*)&desc->joints.u8, BufferU8, desc->buffer_usage); - if (!desc->joints.u8.buffer) { - return false; - } - configure_buffer( - gfxcore, desc, (BufferView*)&desc->joints.u8, 4, sizeof(uint8_t), - GL_UNSIGNED_BYTE, GL_FALSE, GFX_JOINTS_CHANNEL); - } else if (view_is_populated(desc->joints.u16)) { - init_view_buffer( - gfxcore, (BufferView*)&desc->joints.u16, BufferU16, desc->buffer_usage); - if (!desc->joints.u16.buffer) { - return false; - } - configure_buffer( - gfxcore, desc, (BufferView*)&desc->joints.u16, 4, sizeof(uint16_t), - GL_UNSIGNED_SHORT, GL_FALSE, GFX_JOINTS_CHANNEL); - } - - // If weights are given as unsigned integers, then they are normalized - // when read by the shader. - if (view_is_populated(desc->weights.u8)) { - init_view_buffer( - gfxcore, (BufferView*)&desc->weights.u8, BufferU8, desc->buffer_usage); - if (!desc->weights.u8.buffer) { - return false; - } - configure_buffer( - gfxcore, desc, (BufferView*)&desc->weights.u8, 4, sizeof(uint8_t), - GL_UNSIGNED_BYTE, GL_TRUE, GFX_WEIGHTS_CHANNEL); - } else if (view_is_populated(desc->weights.u16)) { - init_view_buffer( - gfxcore, (BufferView*)&desc->weights.u16, BufferU16, - desc->buffer_usage); - if (!desc->weights.u16.buffer) { - return false; - } - configure_buffer( - gfxcore, desc, (BufferView*)&desc->weights.u16, 4, sizeof(uint16_t), - GL_UNSIGNED_SHORT, GL_TRUE, GFX_WEIGHTS_CHANNEL); - } else if (view_is_populated(desc->weights.floats)) { - init_view_buffer( - gfxcore, (BufferView*)&desc->weights.floats, BufferFloat, - desc->buffer_usage); - if (!desc->weights.floats.buffer) { - return false; - } - configure_buffer( - gfxcore, desc, (BufferView*)&desc->weights.floats, 4, sizeof(float), - GL_FLOAT, GL_FALSE, GFX_WEIGHTS_CHANNEL); - } - - return true; -} - -static bool configure_indices(GfxCore* gfxcore, GeometryDesc* desc) { - assert(gfxcore); - assert(desc); - - if (view_is_populated(desc->indices8)) { - assert(desc->num_indices > 0); - assert( - desc->num_indices <= desc->indices8.size_bytes / sizeof(VertexIndex8)); - init_view_buffer( - gfxcore, (BufferView*)&desc->indices8, BufferU8, desc->buffer_usage); - if (!desc->indices8.buffer) { - return false; - } - } else if (view_is_populated(desc->indices16)) { - assert(desc->num_indices > 0); - assert( - desc->num_indices <= - desc->indices16.size_bytes / sizeof(VertexIndex16)); - init_view_buffer( - gfxcore, (BufferView*)&desc->indices16, BufferU16, desc->buffer_usage); - if (!desc->indices16.buffer) { - return false; - } - } - - return true; -} - -bool gfx_init_geometry( - Geometry* geometry, GfxCore* gfxcore, const GeometryDesc* input_desc) { - assert(geometry); - assert(gfxcore); - assert(input_desc); - assert( - view_is_populated(input_desc->positions3d) || - view_is_populated(input_desc->positions2d)); - assert(input_desc->num_verts > 0); - - geometry->mode = primitive_type_to_gl(input_desc->type); - geometry->desc = *input_desc; - geometry->num_verts = input_desc->num_verts; - geometry->gfxcore = gfxcore; - - // The geometry's copy of the descriptor is manipulated below. Create a - // shorter name for it. - GeometryDesc* desc = &geometry->desc; - - glGenVertexArrays(1, &geometry->vao); - glBindVertexArray(geometry->vao); - if (!configure_vertex_attributes(gfxcore, desc)) { - goto cleanup; - } - if (!configure_indices(gfxcore, desc)) { - goto cleanup; - } - glBindVertexArray(0); - ASSERT_GL; - - return true; - -cleanup: - gfx_del_geometry(geometry); - return 0; -} - -void gfx_del_geometry(Geometry* geometry) { - assert(geometry); - if (geometry->vao) { - glDeleteVertexArrays(1, &geometry->vao); - geometry->vao = 0; - } -} - -void gfx_update_geometry(Geometry* geometry, const GeometryDesc* desc) { - assert(geometry); - assert(desc); - // New geometry size cannot exceed original size. - assert(desc->positions3d.size_bytes <= geometry->desc.positions3d.size_bytes); - assert(desc->positions2d.size_bytes <= geometry->desc.positions2d.size_bytes); - assert(desc->normals.size_bytes <= geometry->desc.normals.size_bytes); - assert(desc->tangents.size_bytes <= geometry->desc.tangents.size_bytes); - assert(desc->texcoords.size_bytes <= geometry->desc.texcoords.size_bytes); - assert(desc->joints.u8.size_bytes <= geometry->desc.joints.u8.size_bytes); - assert(desc->joints.u16.size_bytes <= geometry->desc.joints.u16.size_bytes); - assert(desc->weights.u8.size_bytes <= geometry->desc.weights.u8.size_bytes); - assert(desc->weights.u16.size_bytes <= geometry->desc.weights.u16.size_bytes); - assert( - desc->weights.floats.size_bytes <= - geometry->desc.weights.floats.size_bytes); - - if (desc->positions3d.data) { - // The geometry must already have an underlying GPU buffer. - assert(geometry->desc.positions3d.buffer); - gfx_update_buffer( - geometry->desc.positions3d.buffer, - &(BufferDataDesc){ - .vec3s = desc->positions3d.data, - .count = desc->positions3d.size_bytes / sizeof(vec3)}); - } - // TODO: more - else { - FAIL("TODO: gfx_update_geometry() - handle other buffer types"); - } - - if (desc->num_verts != 0) { - geometry->num_verts = desc->num_verts; - } -} - -void gfx_render_geometry(const Geometry* geometry) { - assert(geometry); - assert(geometry->vao); - - const GeometryDesc* desc = &geometry->desc; - glBindVertexArray(geometry->vao); - - if (desc->indices8.buffer) { - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, desc->indices8.buffer->vbo); - glDrawElements( - geometry->mode, desc->num_indices, GL_UNSIGNED_BYTE, - (const void*)desc->indices8.offset_bytes); - } else if (desc->indices16.buffer) { - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, desc->indices16.buffer->vbo); - glDrawElements( - geometry->mode, desc->num_indices, GL_UNSIGNED_SHORT, - (const void*)desc->indices16.offset_bytes); - } else { - glDrawArrays(geometry->mode, 0, geometry->num_verts); - } - - glBindVertexArray(0); -} - -aabb3 gfx_get_geometry_aabb(const Geometry* geometry) { - assert(geometry); - return geometry->desc.aabb; -} diff --git a/gfx/src/core/geometry.h b/gfx/src/core/geometry.h deleted file mode 100644 index c37a76f..0000000 --- a/gfx/src/core/geometry.h +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once - -#include - -#include "gl_util.h" - -#include - -/// A piece of renderable geometry. -/// -/// The Geometry does not own its buffers, since buffers are typically shared -/// to reduce the memory footprint and the number of draw calls. More generally, -/// the renderer assumes ownership of all rendering resources, which simplifies -/// their management. -typedef struct Geometry { - GLuint vao; - GLenum mode; - GeometryDesc desc; - size_t num_verts; // May differ from the initial value in the descriptor if - // the geometry is updated. - GfxCore* gfxcore; -} Geometry; - -/// Create new geometry. -bool gfx_init_geometry(Geometry*, GfxCore*, const GeometryDesc*); - -/// Destroy the geometry. -void gfx_del_geometry(Geometry*); diff --git a/gfx/src/core/gl_util.h b/gfx/src/core/gl_util.h deleted file mode 100644 index d2d6e22..0000000 --- a/gfx/src/core/gl_util.h +++ /dev/null @@ -1,45 +0,0 @@ -#pragma once - -#include -#include - -#define GFX_GL_CONTEXT_PC 1 -#define GFX_GL_CONTEXT_ES 2 - -#ifndef GFX_GL_CONTEXT -#define GFX_GL_CONTEXT GFX_GL_CONTEXT_PC -#endif // GFX_GL_CONTEXT - -/// Log an error if an OpenGL has occurred. -#ifndef NDEBUG -#define ASSERT_GL \ - { \ - GLenum e = glGetError(); \ - switch (e) { \ - case GL_NO_ERROR: \ - break; \ - case GL_INVALID_ENUM: \ - LOGE("GL_INVALID_ENUM"); \ - break; \ - case GL_INVALID_VALUE: \ - LOGE("GL_INVALID_VALUE"); \ - break; \ - case GL_INVALID_OPERATION: \ - LOGE("GL_INVALID_OPERATION"); \ - break; \ - case GL_INVALID_FRAMEBUFFER_OPERATION: \ - LOGE("GL_INVALID_FRAMEBUFFER_OPERATION"); \ - break; \ - case GL_OUT_OF_MEMORY: \ - LOGE("GL_OUT_OF_MEMORY"); \ - break; \ - /*case GL_STACK_UNDERFLOW: LOGE("GL_STACK_UNDERFLOW");*/ \ - /*case GL_STACK_OVERFLOW: LOGE("GL_STACK_OVERFLOW");*/ \ - default: \ - LOGE("Unknown OpenGL error"); \ - break; \ - } \ - } -#else // Not NDEBUG. -#define ASSERT_GL -#endif diff --git a/gfx/src/core/renderbuffer.c b/gfx/src/core/renderbuffer.c deleted file mode 100644 index 2753f3b..0000000 --- a/gfx/src/core/renderbuffer.c +++ /dev/null @@ -1,35 +0,0 @@ -#include "renderbuffer.h" - -#include "texture.h" - -#include - -bool gfx_init_renderbuffer( - RenderBuffer* renderbuffer, const RenderBufferDesc* desc) { - assert(renderbuffer); - assert(desc); - - glGenRenderbuffers(1, &renderbuffer->id); - if (!renderbuffer->id) { - log_error("glGenRenderbuffers failed"); - return false; - } - - glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer->id); - glRenderbufferStorage( - GL_RENDERBUFFER, to_GL_internal_format(desc->texture_format), desc->width, - desc->height); - glBindRenderbuffer(GL_RENDERBUFFER, 0); - - ASSERT_GL; - return true; -} - -void gfx_del_renderbuffer(RenderBuffer* renderbuffer) { - assert(renderbuffer); - - if (renderbuffer->id) { - glDeleteRenderbuffers(1, &renderbuffer->id); - renderbuffer->id = 0; - } -} diff --git a/gfx/src/core/renderbuffer.h b/gfx/src/core/renderbuffer.h deleted file mode 100644 index ea11610..0000000 --- a/gfx/src/core/renderbuffer.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once - -#include - -#include "gl_util.h" - -typedef struct RenderBuffer { - GLuint id; -} RenderBuffer; - -/// Create a new renderbuffer. -bool gfx_init_renderbuffer(RenderBuffer*, const RenderBufferDesc*); - -/// Destroy the renderbuffer. -void gfx_del_renderbuffer(RenderBuffer*); diff --git a/gfx/src/core/shader.c b/gfx/src/core/shader.c deleted file mode 100644 index dded084..0000000 --- a/gfx/src/core/shader.c +++ /dev/null @@ -1,92 +0,0 @@ -#include "shader.h" - -#include "gl_util.h" -#include - -#include -#include - -#include -#include - -static GLenum shader_type_to_gl(ShaderType type) { - switch (type) { - case VertexShader: - return GL_VERTEX_SHADER; - case FragmentShader: - return GL_FRAGMENT_SHADER; - } - FAIL("shader_type_to_gl(): missing case"); - return GL_INVALID_ENUM; -} - -static lstring make_defines_string(const ShaderDesc* desc) { - lstring defines = {0}; - for (size_t i = 0; i < desc->num_defines; ++i) { - const ShaderCompilerDefine* define = &desc->defines[i]; - lstring_append_cstr(&defines, "#define "); - lstring_append_cstr(&defines, sstring_cstr(&define->name)); - lstring_append_cstr(&defines, " "); - lstring_append_cstr(&defines, sstring_cstr(&define->value)); - lstring_append_cstr(&defines, "\n"); - } - return defines; -} - -/// Creates an OpenGL shader. -/// Returns non-zero on success, 0 on failure. -static GLuint create_shader(const ShaderDesc* desc) { - const GLuint shader = glCreateShader(shader_type_to_gl(desc->type)); - if (!shader) { - return 0; - } - -#if GFX_GL_CONTEXT == GFX_GL_CONTEXT_ES - const char* header = "#version 300 es\n\nprecision highp float;"; -#else - const char* header = "#version 400 core\n\n"; -#endif - - lstring defines = make_defines_string(desc); - - const char* source_bits[] = {header, lstring_cstr(&defines), desc->code}; - const GLint source_lengths[] = { - strlen(header), lstring_length(&defines), strlen(desc->code)}; - - glShaderSource(shader, 3, source_bits, source_lengths); - glCompileShader(shader); - GLint result; - glGetShaderiv(shader, GL_COMPILE_STATUS, &result); - if (result == GL_FALSE) { - GLint log_len; - glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &log_len); - if (log_len > 0) { - char* log = calloc(log_len, sizeof(char)); - glGetShaderInfoLog(shader, log_len, NULL, log); - static const char* sep = "----------"; - LOGE("Failed loading shader: %s\n%s\n%s\n%s", log, sep, desc->code, sep); - free(log); - } else { - LOGE("Failed loading shader:\n%s", desc->code); - } - glDeleteShader(shader); - return 0; - } - ASSERT_GL; - return shader; -} - -bool gfx_compile_shader(Shader* shader, const ShaderDesc* desc) { - shader->id = create_shader(desc); - return shader->id != 0; -} - -void gfx_del_shader(Shader* shader) { - assert(shader); - - if (shader->id) { - glDeleteShader(shader->id); - shader->id = 0; - } - ASSERT_GL; -} diff --git a/gfx/src/core/shader.h b/gfx/src/core/shader.h deleted file mode 100644 index b9f5679..0000000 --- a/gfx/src/core/shader.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once - -#include - -#include "gl_util.h" - -#include - -typedef struct Shader { - GLuint id; -} Shader; - -/// Compile a new shader. -bool gfx_compile_shader(Shader*, const ShaderDesc*); - -/// Destroy the shader. -void gfx_del_shader(Shader*); diff --git a/gfx/src/core/shader_program.c b/gfx/src/core/shader_program.c deleted file mode 100644 index 3cbe48d..0000000 --- a/gfx/src/core/shader_program.c +++ /dev/null @@ -1,291 +0,0 @@ -#include "shader_program.h" - -#include "gl_util.h" -#include "shader.h" -#include "texture.h" -#include - -#include - -#include -#include - -/// Creates an OpenGL shader program. -/// Returns non-zero on success, 0 on failure. -static GLuint create_program(GLuint vertex_shader, GLuint fragment_shader) { - const GLuint prog = glCreateProgram(); - if (prog == 0) { - LOGE("Failed creating shader program"); - return 0; - } - glAttachShader(prog, vertex_shader); - glAttachShader(prog, fragment_shader); - glLinkProgram(prog); - GLint result; - glGetProgramiv(prog, GL_LINK_STATUS, &result); - if (result == GL_FALSE) { - GLint log_len; - glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &log_len); - if (log_len > 0) { - char* log = calloc(log_len, sizeof(char)); - glGetProgramInfoLog(prog, log_len, NULL, log); - LOGE("Failed creating shader program: %s", log); - free(log); - } else { - LOGE("Failed creating shader program"); - } - glDeleteProgram(prog); - return 0; - } - ASSERT_GL; - return prog; -} - -bool gfx_build_shader_program( - ShaderProgram* prog, const ShaderProgramDesc* desc) { - assert(prog); - assert(desc); - - prog->id = create_program(desc->vertex_shader->id, desc->fragment_shader->id); - return prog->id != 0; -} - -void gfx_del_shader_program(ShaderProgram* prog) { - assert(prog); - - if (prog->id) { - glDeleteProgram(prog->id); - prog->id = 0; - } - ASSERT_GL; -} - -void gfx_activate_shader_program(const ShaderProgram* prog) { - assert(prog); - glUseProgram(prog->id); - ASSERT_GL; -} - -void gfx_deactivate_shader_program(const ShaderProgram* prog) { - assert(prog); - glUseProgram(0); - ASSERT_GL; -} - -static void set_texture_uniform( - GLuint prog, const char* name, int texture_unit, const Texture* texture) { - assert(prog != 0); - assert(name); - assert(texture); - - const GLint location = glGetUniformLocation(prog, name); - if (location >= 0) { - glActiveTexture(GL_TEXTURE0 + texture_unit); - glBindTexture(texture->target, texture->id); - glUniform1i(location, texture_unit); - } -} - -static void set_mat4_uniform( - GLuint prog, const char* name, const mat4* mats, size_t count) { - assert(prog != 0); - assert(name); - assert(mats); - - const GLint location = glGetUniformLocation(prog, name); - if (location >= 0) { - glUniformMatrix4fv(location, count, GL_FALSE, (const float*)mats); - } -} - -static void set_vec3_uniform(GLuint prog, const char* name, vec3 value) { - assert(prog != 0); - assert(name); - - const GLint location = glGetUniformLocation(prog, name); - if (location >= 0) { - glUniform3f(location, value.x, value.y, value.z); - } -} - -static void set_vec4_uniform(GLuint prog, const char* name, vec4 value) { - assert(prog != 0); - assert(name); - - const GLint location = glGetUniformLocation(prog, name); - if (location >= 0) { - glUniform4f(location, value.x, value.y, value.z, value.w); - } -} - -static void set_float_uniform(GLuint prog, const char* name, float value) { - assert(prog != 0); - assert(name); - - const GLint location = glGetUniformLocation(prog, name); - if (location >= 0) { - glUniform1f(location, value); - } -} - -void gfx_apply_uniforms(const ShaderProgram* prog) { - assert(prog); - - int next_texture_unit = 0; - for (int i = 0; i < prog->num_uniforms; ++i) { - const ShaderUniform* uniform = &prog->uniforms[i]; - switch (uniform->type) { - case UniformTexture: - set_texture_uniform( - prog->id, uniform->name.str, next_texture_unit, - uniform->value.texture); - next_texture_unit++; - break; - case UniformMat4: - set_mat4_uniform(prog->id, uniform->name.str, &uniform->value.mat4, 1); - break; - case UniformVec3: - set_vec3_uniform(prog->id, uniform->name.str, uniform->value.vec3); - break; - case UniformVec4: - set_vec4_uniform(prog->id, uniform->name.str, uniform->value.vec4); - break; - case UniformFloat: - set_float_uniform(prog->id, uniform->name.str, uniform->value.scalar); - break; - case UniformMat4Array: - set_mat4_uniform( - prog->id, uniform->name.str, uniform->value.array.values, - uniform->value.array.count); - break; - } - } -} - -// Get the ShaderUniform object by name from the shader program if it already -// exists, or allocate a new one otherwise. -static ShaderUniform* get_or_allocate_uniform( - ShaderProgram* prog, const char* name) { - assert(prog); - assert(name); - - // First search for the uniform in the list. - for (int i = 0; i < prog->num_uniforms; ++i) { - ShaderUniform* uniform = &prog->uniforms[i]; - if (sstring_eq_cstr(uniform->name, name)) { - return uniform; - } - } - - // Create the uniform if it does not exist. - if (prog->num_uniforms == GFX_MAX_UNIFORMS_PER_SHADER) { - FAIL("Exceeded the maximum number of uniforms per shader. Please increase " - "this value."); - return 0; - } - ShaderUniform* uniform = &prog->uniforms[prog->num_uniforms]; - prog->num_uniforms++; - return uniform; -} - -// The functions below save the value of a uniform in the shader program. If the -// uniform does not even exist, then there is no need to store the value. - -void gfx_set_texture_uniform( - ShaderProgram* prog, const char* name, const Texture* texture) { - assert(prog); - assert(name); - assert(texture); - - const GLint location = glGetUniformLocation(prog->id, name); - if (location < 0) { - return; - } - ShaderUniform* uniform = get_or_allocate_uniform(prog, name); - assert(uniform); - uniform->name = sstring_make(name); - uniform->type = UniformTexture; - uniform->value.texture = texture; -} - -void gfx_set_mat4_uniform( - ShaderProgram* prog, const char* name, const mat4* mat) { - assert(prog); - assert(name); - assert(mat); - - const GLint location = glGetUniformLocation(prog->id, name); - if (location < 0) { - return; - } - ShaderUniform* uniform = get_or_allocate_uniform(prog, name); - assert(uniform); - uniform->name = sstring_make(name); - uniform->type = UniformMat4; - uniform->value.mat4 = *mat; -} - -void gfx_set_vec3_uniform(ShaderProgram* prog, const char* name, vec3 value) { - assert(prog); - assert(name); - - const GLint location = glGetUniformLocation(prog->id, name); - if (location < 0) { - return; - } - ShaderUniform* uniform = get_or_allocate_uniform(prog, name); - assert(uniform); - uniform->name = sstring_make(name); - uniform->type = UniformVec3; - uniform->value.vec3 = value; -} - -void gfx_set_vec4_uniform(ShaderProgram* prog, const char* name, vec4 value) { - assert(prog); - assert(name); - - const GLint location = glGetUniformLocation(prog->id, name); - if (location < 0) { - return; - } - ShaderUniform* uniform = get_or_allocate_uniform(prog, name); - assert(uniform); - uniform->name = sstring_make(name); - uniform->type = UniformVec4; - uniform->value.vec4 = value; -} - -void gfx_set_float_uniform(ShaderProgram* prog, const char* name, float value) { - assert(prog); - assert(name); - - // No need to store the uniform on our side if it does not exist in the - // program. - const GLint location = glGetUniformLocation(prog->id, name); - if (location < 0) { - return; - } - ShaderUniform* uniform = get_or_allocate_uniform(prog, name); - assert(uniform); - uniform->name = sstring_make(name); - uniform->type = UniformFloat; - uniform->value.scalar = value; -} - -void gfx_set_mat4_array_uniform( - ShaderProgram* prog, const char* name, const mat4* mats, size_t count) { - assert(prog); - assert(name); - assert(mats); - - const GLint location = glGetUniformLocation(prog->id, name); - if (location < 0) { - return; - } - ShaderUniform* uniform = get_or_allocate_uniform(prog, name); - assert(uniform); - uniform->name = sstring_make(name); - uniform->type = UniformMat4Array; - uniform->value.array.count = count; - uniform->value.array.values = mats; -} diff --git a/gfx/src/core/shader_program.h b/gfx/src/core/shader_program.h deleted file mode 100644 index 1443663..0000000 --- a/gfx/src/core/shader_program.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -#include -#include - -#include "gl_util.h" - -#include - -#include - -typedef struct Texture Texture; - -typedef struct ShaderProgram { - GLuint id; - ShaderUniform uniforms[GFX_MAX_UNIFORMS_PER_SHADER]; - int num_uniforms; -} ShaderProgram; - -/// Create a new shader program. -bool gfx_build_shader_program(ShaderProgram*, const ShaderProgramDesc*); - -/// Destroy the shader program. -void gfx_del_shader_program(ShaderProgram*); diff --git a/gfx/src/core/texture.c b/gfx/src/core/texture.c deleted file mode 100644 index 89f7ec0..0000000 --- a/gfx/src/core/texture.c +++ /dev/null @@ -1,218 +0,0 @@ -#include "texture.h" - -#include - -#include -#include - -#include - -bool gfx_init_texture(Texture* texture, const TextureDesc* desc) { - assert(texture); - assert(desc); - - glGenTextures(1, &texture->id); - if (!texture->id) { - log_error("glGenTextures() failed"); - return false; - } - texture->target = to_GL_dimension(desc->dimension); - glBindTexture(texture->target, texture->id); - - // glTexStorageXD - const int levels = - desc->mipmaps - ? max(max(log2(desc->width), log2(desc->height)), log2(desc->depth)) + - 1 - : 1; - const GLenum internal_format = to_GL_internal_format(desc->format); - switch (texture->target) { - case GL_TEXTURE_2D: - case GL_TEXTURE_CUBE_MAP: - glTexStorage2D( - texture->target, levels, internal_format, desc->width, desc->height); - break; - default: - FAIL("Unhandled texture dimension"); - gfx_del_texture(texture); - return false; - } - - texture->format = to_GL_format(desc->format); - texture->type = to_GL_type(desc->format); - texture->width = desc->width; - texture->height = desc->height; - gfx_update_texture(texture, &desc->data); - - // gfx_update_texture() unbinds the texture at the end, so re-bind it here. - glBindTexture(texture->target, texture->id); - - // Mipmaps. - if (desc->mipmaps) { - glGenerateMipmap(texture->target); - } - - // Texture filtering. - const bool linear = desc->filtering == LinearFiltering; - GLenum min = desc->mipmaps ? (linear ? GL_LINEAR_MIPMAP_LINEAR - : GL_NEAREST_MIPMAP_NEAREST) - : (linear ? GL_LINEAR : GL_NEAREST); - GLenum mag = linear ? GL_LINEAR : GL_NEAREST; - glTexParameteri(texture->target, GL_TEXTURE_MIN_FILTER, min); - glTexParameteri(texture->target, GL_TEXTURE_MAG_FILTER, mag); - - // Texture wrapping. - GLenum wrap = GL_INVALID_ENUM; - switch (desc->wrap) { - case Repeat: - wrap = GL_REPEAT; - break; - case ClampToEdge: - wrap = GL_CLAMP_TO_EDGE; - break; - } - glTexParameteri(texture->target, GL_TEXTURE_WRAP_R, wrap); - glTexParameteri(texture->target, GL_TEXTURE_WRAP_S, wrap); - glTexParameteri(texture->target, GL_TEXTURE_WRAP_T, wrap); - - glBindTexture(texture->target, 0); - return true; -} - -void gfx_del_texture(Texture* texture) { - assert(texture); - - if (texture->id) { - glDeleteTextures(1, &texture->id); - texture->id = 0; - } -} - -void gfx_update_texture(Texture* texture, const TextureDataDesc* desc) { - assert(texture); - assert(desc); - - glBindTexture(texture->target, texture->id); - - // glTexSubImageXD - switch (texture->target) { - case GL_TEXTURE_2D: - if (desc->pixels) { - glTexSubImage2D( - GL_TEXTURE_2D, /*level=*/0, /*xoffset=*/0, - /*yoffset=*/0, texture->width, texture->height, texture->format, - texture->type, desc->pixels); - } - break; - case GL_TEXTURE_CUBE_MAP: - for (int i = 0; i < 6; ++i) { - const void* pixels = *(&desc->cubemap.pixels_pos_x + i); - if (pixels) { - glTexSubImage2D( - GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, /*level=*/0, /*xoffset=*/0, - /*yoffset=*/0, texture->width, texture->height, texture->format, - texture->type, pixels); - } - } - break; - default: - FAIL("Unhandled texture dimension"); - break; - } - - glBindTexture(texture->target, 0); -} - -GLenum to_GL_dimension(TextureDimension dim) { - switch (dim) { - case Texture2D: - return GL_TEXTURE_2D; - case TextureCubeMap: - return GL_TEXTURE_CUBE_MAP; - default: - FAIL("Unhandled TextureDimension"); - return GL_INVALID_ENUM; - } -} - -GLenum to_GL_internal_format(TextureFormat format) { - switch (format) { - case TextureDepth: - return GL_DEPTH_COMPONENT; - case TextureRG16: - return GL_RG16; - case TextureRG16F: - return GL_RG16F; - case TextureRGB8: - return GL_RGB8; - case TextureR11G11B10F: - return GL_R11F_G11F_B10F; - case TextureRGBA8: - return GL_RGBA8; - case TextureSRGB8: - return GL_SRGB8; - case TextureSRGBA8: - return GL_SRGB8_ALPHA8; - default: - FAIL("Unhandled TextureFormat"); - return GL_INVALID_ENUM; - } -} - -GLenum to_GL_format(TextureFormat format) { - switch (format) { - case TextureDepth: - return GL_DEPTH_COMPONENT; - case TextureRG16: - case TextureRG16F: - return GL_RG; - case TextureRGB8: - case TextureR11G11B10F: - case TextureSRGB8: - return GL_RGB; - case TextureRGBA8: - case TextureSRGBA8: - return GL_RGBA; - default: - FAIL("Unhandled TextureFormat"); - return GL_INVALID_ENUM; - } -} - -GLenum to_GL_type(TextureFormat format) { - switch (format) { - case TextureDepth: - case TextureRG16F: - case TextureR11G11B10F: - return GL_FLOAT; - case TextureRG16: - case TextureRGB8: - case TextureRGBA8: - case TextureSRGB8: - case TextureSRGBA8: - return GL_UNSIGNED_BYTE; - default: - FAIL("Unhandled TextureFormat"); - return GL_INVALID_ENUM; - } -} - -GLenum to_GL_cubemap_face(CubemapFace face) { - switch (face) { - case CubemapFacePosX: - return GL_TEXTURE_CUBE_MAP_POSITIVE_X; - case CubemapFaceNegX: - return GL_TEXTURE_CUBE_MAP_NEGATIVE_X; - case CubemapFacePosY: - return GL_TEXTURE_CUBE_MAP_POSITIVE_Y; - case CubemapFaceNegY: - return GL_TEXTURE_CUBE_MAP_NEGATIVE_Y; - case CubemapFacePosZ: - return GL_TEXTURE_CUBE_MAP_POSITIVE_Z; - case CubemapFaceNegZ: - return GL_TEXTURE_CUBE_MAP_NEGATIVE_Z; - default: - FAIL("Unhandled CubemapFace"); - return GL_INVALID_ENUM; - } -} diff --git a/gfx/src/core/texture.h b/gfx/src/core/texture.h deleted file mode 100644 index 4af41e9..0000000 --- a/gfx/src/core/texture.h +++ /dev/null @@ -1,35 +0,0 @@ -#pragma once - -#include - -#include "gl_util.h" - -typedef struct Texture { - GLuint id; - GLenum target; - GLenum format; - GLenum type; - int width; - int height; -} Texture; - -/// Create a new texture. -bool gfx_init_texture(Texture*, const TextureDesc*); - -/// Destroy the texture. -void gfx_del_texture(Texture*); - -/// Converts a TextureDimension into the OpenGL enum equivalent. -GLenum to_GL_dimension(TextureDimension dim); - -/// Converts a texture format into an OpenGL internal format. -GLenum to_GL_internal_format(TextureFormat format); - -/// Converts a texture format into an OpenGL format. -GLenum to_GL_format(TextureFormat format); - -/// Converts a texture format into an OpenGL type. -GLenum to_GL_type(TextureFormat format); - -/// Converts a cubemap face into the OpenGL enum equivalent. -GLenum to_GL_cubemap_face(CubemapFace face); diff --git a/gfx/src/gfx.c b/gfx/src/gfx.c deleted file mode 100644 index cd2ac90..0000000 --- a/gfx/src/gfx.c +++ /dev/null @@ -1,73 +0,0 @@ -#include - -#include "asset/asset_cache.h" -#include "core/core_impl.h" -#include "renderer/imm_renderer_impl.h" -#include "renderer/renderer_impl.h" -#include "scene/scene_memory.h" - -#include - -#include -#include - -typedef struct Gfx { - AssetCache asset_cache; - GfxCore gfxcore; - Renderer renderer; - ImmRenderer imm_renderer; -} Gfx; - -Gfx* gfx_init(void) { - Gfx* gfx = calloc(1, sizeof(Gfx)); - if (!gfx) { - return 0; - } - gfx_init_gfxcore(&gfx->gfxcore); - if (!renderer_make(&gfx->renderer, &gfx->gfxcore)) { - gfx_destroy(&gfx); - return 0; - } - if (!imm_renderer_make(&gfx->imm_renderer, &gfx->gfxcore)) { - // TODO: Add error logs to the initialization failure cases here and inside - // the renderers. - gfx_destroy(&gfx); - return 0; - } - gfx_init_asset_cache(&gfx->asset_cache); - scene_mem_init(); - return gfx; -} - -void gfx_destroy(Gfx** gfx) { - if (!gfx) { - return; - } - scene_mem_destroy(); - gfx_destroy_asset_cache(&(*gfx)->asset_cache); - renderer_destroy(&(*gfx)->renderer); - imm_renderer_destroy(&(*gfx)->imm_renderer); - gfx_del_gfxcore(&(*gfx)->gfxcore); - free(*gfx); - *gfx = 0; -} - -GfxCore* gfx_get_core(Gfx* gfx) { - assert(gfx); - return &gfx->gfxcore; -} - -Renderer* gfx_get_renderer(Gfx* gfx) { - assert(gfx); - return &gfx->renderer; -} - -ImmRenderer* gfx_get_imm_renderer(Gfx* gfx) { - assert(gfx); - return &gfx->imm_renderer; -} - -AssetCache* gfx_get_asset_cache(Gfx* gfx) { - assert(gfx); - return &gfx->asset_cache; -} diff --git a/gfx/src/gfx_assert.h b/gfx/src/gfx_assert.h deleted file mode 100644 index f4b3aa5..0000000 --- a/gfx/src/gfx_assert.h +++ /dev/null @@ -1,5 +0,0 @@ -#pragma once - -#include - -#include // Include after log to use log's LOGE(). diff --git a/gfx/src/renderer/imm_renderer.c b/gfx/src/renderer/imm_renderer.c deleted file mode 100644 index 8cf3a10..0000000 --- a/gfx/src/renderer/imm_renderer.c +++ /dev/null @@ -1,260 +0,0 @@ -#include "imm_renderer_impl.h" - -#include -#include - -#include - -#include -#include // memcpy - -bool imm_renderer_make(ImmRenderer* renderer, GfxCore* gfxcore) { - assert(renderer); - assert(gfxcore); - - const size_t num_triangle_verts = IMM_MAX_NUM_TRIANGLES * 3; - - renderer->gfxcore = gfxcore; - - renderer->triangles = gfx_make_geometry( - gfxcore, &(GeometryDesc){ - .type = Triangles, - .buffer_usage = BufferDynamic, - .num_verts = num_triangle_verts, - .positions3d = (BufferView3d){ - .size_bytes = num_triangle_verts * sizeof(vec3)}}); - if (!renderer->triangles) { - goto cleanup; - } - - renderer->shader = gfx_make_immediate_mode_shader(gfxcore); - if (!renderer->shader) { - goto cleanup; - } - - renderer->matrix_stack[0] = mat4_id(); - renderer->stack_pointer = 0; - - gfx_imm_set_colour(renderer, vec4_make(0.0, 0.0, 0.0, 1.0)); - - return true; - -cleanup: - imm_renderer_destroy(renderer); - return false; -} - -void imm_renderer_destroy(ImmRenderer* renderer) { - assert(renderer); - assert(renderer->gfxcore); - - if (renderer->triangles) { - gfx_destroy_geometry(renderer->gfxcore, &renderer->triangles); - // TODO: Could also destroy the geometry's buffers here. - } - - if (renderer->shader) { - gfx_destroy_shader_program(renderer->gfxcore, &renderer->shader); - } -} - -void imm_renderer_flush(ImmRenderer* renderer) { - assert(renderer); - - if (renderer->num_triangle_verts > 0) { - gfx_update_geometry( - renderer->triangles, - &(GeometryDesc){ - .num_verts = renderer->num_triangle_verts, - .positions3d = (BufferView3d){ - .data = renderer->triangle_verts, - .size_bytes = renderer->num_triangle_verts * sizeof(vec3)} - }); - - gfx_apply_uniforms(renderer->shader); - gfx_render_geometry(renderer->triangles); - - renderer->num_triangle_verts = 0; - } -} - -void gfx_imm_start(ImmRenderer* renderer) { - assert(renderer); - // Shader uniforms are applied lazily. - // TODO: In the event that gfx_activate_shader_program() activates uniforms - // automatically for convenience, call an overload here that doesn't do so. - ShaderProgram* shader = renderer->shader; - gfx_activate_shader_program(shader); -} - -void gfx_imm_end(ImmRenderer* renderer) { - assert(renderer); - imm_renderer_flush(renderer); - gfx_deactivate_shader_program(renderer->shader); -} - -void gfx_imm_draw_triangles( - ImmRenderer* renderer, const vec3 verts[], size_t num_triangles) { - assert(renderer); - assert(verts); - const size_t new_verts = num_triangles * 3; - assert( - renderer->num_triangle_verts + new_verts < (IMM_MAX_NUM_TRIANGLES * 3)); - - memcpy( - renderer->triangle_verts + renderer->num_triangle_verts, verts, - new_verts * sizeof(vec3)); - - renderer->num_triangle_verts += new_verts; -} - -void gfx_imm_draw_triangle(ImmRenderer* renderer, const vec3 verts[3]) { - gfx_imm_draw_triangles(renderer, verts, 1); -} - -void gfx_imm_draw_aabb2(ImmRenderer* renderer, aabb2 box) { - assert(renderer); - - // clang-format off - const vec3 verts[4] = { - vec3_make(box.min.x, box.min.y, 0), // 3 ---- 2 - vec3_make(box.max.x, box.min.y, 0), // | | - vec3_make(box.max.x, box.max.y, 0), // | | - vec3_make(box.min.x, box.max.y, 0)}; // 0 ---- 1 - // clang-format on - -#define tri(i0, i1, i2) verts[i0], verts[i1], verts[i2] - const vec3 tris[6] = {tri(0, 1, 2), tri(0, 2, 3)}; -#undef tri - - gfx_imm_draw_triangles(renderer, tris, 2); -} - -void gfx_imm_draw_aabb3(ImmRenderer* renderer, aabb3 box) { - assert(renderer); - - // clang-format off - const vec3 vertices[8] = { - vec3_make(box.min.x, box.min.y, box.max.z), // 7 ----- 6 - vec3_make(box.max.x, box.min.y, box.max.z), // / /| - vec3_make(box.max.x, box.max.y, box.max.z), // 3 ----- 2 | - vec3_make(box.min.x, box.max.y, box.max.z), // | | | - vec3_make(box.min.x, box.min.y, box.min.z), // | 4 ----- 5 - vec3_make(box.max.x, box.min.y, box.min.z), // |/ |/ - vec3_make(box.max.x, box.max.y, box.min.z), // 0 ----- 1 - vec3_make(box.min.x, box.max.y, box.min.z)}; - // clang-format on - - gfx_imm_draw_box3(renderer, vertices); -} - -void gfx_imm_draw_box3(ImmRenderer* renderer, const vec3 vertices[8]) { - assert(renderer); - assert(vertices); - - // 7 ----- 6 - // / /| - // 3 ----- 2 | - // | | | - // | 4 ----- 5 - // |/ |/ - // 0 ----- 1 - -#define tri(i0, i1, i2) vertices[i0], vertices[i1], vertices[i2] - const vec3 tris[36] = {// Front. - tri(0, 1, 2), tri(0, 2, 3), - // Right. - tri(1, 5, 6), tri(1, 6, 2), - // Back. - tri(5, 4, 7), tri(5, 7, 6), - // Left. - tri(4, 0, 03), tri(4, 3, 7), - // Top. - tri(3, 2, 6), tri(3, 6, 7), - // Bottom. - tri(0, 4, 5), tri(0, 5, 1)}; - - gfx_imm_draw_triangles(renderer, tris, 12); -} - -// Load the top of the matrix stack into the shader. -static void update_shader_model_matrix(ImmRenderer* renderer) { - assert(renderer); - imm_renderer_flush(renderer); - gfx_set_mat4_uniform( - renderer->shader, "Model", - &renderer->matrix_stack[renderer->stack_pointer]); -} - -void gfx_imm_load_identity(ImmRenderer* renderer) { - assert(renderer); - renderer->matrix_stack[0] = mat4_id(); - renderer->stack_pointer = 0; - update_shader_model_matrix(renderer); -} - -void gfx_imm_push_matrix(ImmRenderer* renderer, const mat4* matrix) { - assert(renderer); - assert(matrix); - assert(renderer->stack_pointer >= 0); - assert(renderer->stack_pointer < IMM_MAX_NUM_MATRICES); // TODO: hard assert. - - renderer->matrix_stack[renderer->stack_pointer + 1] = - mat4_mul(*matrix, renderer->matrix_stack[renderer->stack_pointer]); - renderer->stack_pointer += 1; - - update_shader_model_matrix(renderer); -} - -void gfx_imm_pop_matrix(ImmRenderer* renderer) { - assert(renderer); - assert(renderer->stack_pointer > 0); // TODO: hard assert. - - // For debugging, zero out the matrix stack as matrices are popped out. - memset( - &renderer->matrix_stack[renderer->stack_pointer], 0, - sizeof(renderer->matrix_stack[0])); - - renderer->stack_pointer -= 1; - - update_shader_model_matrix(renderer); -} - -void gfx_imm_translate(ImmRenderer* renderer, vec3 offset) { - assert(renderer); - const mat4 mat = mat4_translate(offset); - gfx_imm_push_matrix(renderer, &mat); -} - -void gfx_imm_set_camera(ImmRenderer* renderer, const Camera* camera) { - assert(renderer); - assert(renderer->shader); - imm_renderer_flush(renderer); - const mat4 view = spatial3_inverse_transform(&camera->spatial); - const mat4 view_proj = mat4_mul(camera->projection, view); - gfx_imm_set_view_projection_matrix(renderer, &view_proj); -} - -void gfx_imm_set_model_matrix(ImmRenderer* renderer, const mat4* model) { - assert(renderer); - assert(model); - imm_renderer_flush(renderer); - renderer->matrix_stack[0] = *model; - renderer->stack_pointer = 0; - update_shader_model_matrix(renderer); -} - -void gfx_imm_set_view_projection_matrix( - ImmRenderer* renderer, const mat4* view_proj) { - assert(renderer); - assert(renderer->shader); - imm_renderer_flush(renderer); - gfx_set_mat4_uniform(renderer->shader, "ViewProjection", view_proj); -} - -void gfx_imm_set_colour(ImmRenderer* renderer, vec4 colour) { - assert(renderer); - assert(renderer->shader); - imm_renderer_flush(renderer); - gfx_set_vec4_uniform(renderer->shader, "Colour", colour); -} diff --git a/gfx/src/renderer/imm_renderer_impl.h b/gfx/src/renderer/imm_renderer_impl.h deleted file mode 100644 index 5ece354..0000000 --- a/gfx/src/renderer/imm_renderer_impl.h +++ /dev/null @@ -1,44 +0,0 @@ -#pragma once - -#include -#include - -#include -#include - -#include -#include - -typedef struct Geometry Geometry; -typedef struct ShaderProgram ShaderProgram; - -/// Immediate mode renderer. -/// -/// Currently, the immediate mode renderer can only draw up to a maximum number -/// of primitives per frame. It does not adjust this number dynamically. Keeps -/// things simple while the extra complexity is not needed. -typedef struct ImmRenderer { - GfxCore* gfxcore; - ShaderProgram* shader; - Geometry* triangles; - size_t num_triangle_verts; // Number of triangle verts this frame. - // TODO: wireframe rendering. - struct { - bool wireframe : 1; - } flags; - vec3 triangle_verts[IMM_MAX_NUM_TRIANGLES * 3]; - // Matrix stack contains pre-multiplied matrices. - // It is also never empty. The top of the stack is an identity matrix when the - // stack is "empty" from the user's perspective. - mat4 matrix_stack[IMM_MAX_NUM_MATRICES]; - int stack_pointer; -} ImmRenderer; - -/// Create a new immediate mode renderer. -bool imm_renderer_make(ImmRenderer*, GfxCore*); - -/// Destroy the immediate mode renderer. -void imm_renderer_destroy(ImmRenderer*); - -/// Flush draw commands. -void imm_renderer_flush(ImmRenderer*); diff --git a/gfx/src/renderer/renderer.c b/gfx/src/renderer/renderer.c deleted file mode 100644 index c2a7dda..0000000 --- a/gfx/src/renderer/renderer.c +++ /dev/null @@ -1,396 +0,0 @@ -#include "renderer_impl.h" - -#include "scene/animation_impl.h" -#include "scene/camera_impl.h" -#include "scene/light_impl.h" -#include "scene/material_impl.h" -#include "scene/mesh_impl.h" -#include "scene/model_impl.h" -#include "scene/node_impl.h" -#include "scene/object_impl.h" -#include "scene/scene_impl.h" -#include "scene/scene_memory.h" - -#include -#include -#include - -#include -#include -#include - -#include - -// TODO: Move to a header like "constants.h". -static const int IRRADIANCE_MAP_WIDTH = 1024; -static const int IRRADIANCE_MAP_HEIGHT = 1024; -static const int PREFILTERED_ENVIRONMENT_MAP_WIDTH = 128; -static const int PREFILTERED_ENVIRONMENT_MAP_HEIGHT = 128; -static const int BRDF_INTEGRATION_MAP_WIDTH = 512; -static const int BRDF_INTEGRATION_MAP_HEIGHT = 512; - -bool renderer_make(Renderer* renderer, GfxCore* gfxcore) { - assert(renderer); - assert(gfxcore); - - renderer->gfxcore = gfxcore; - - return true; -} - -void renderer_destroy(Renderer* renderer) { - if (!renderer) { - return; - } - assert(renderer->gfxcore); - GfxCore* gfxcore = renderer->gfxcore; - if (renderer->ibl) { - gfx_destroy_ibl(gfxcore, &renderer->ibl); - } - if (renderer->shaders.debug) { - gfx_destroy_shader_program(gfxcore, &renderer->shaders.debug); - } - if (renderer->shaders.normals) { - gfx_destroy_shader_program(gfxcore, &renderer->shaders.normals); - } - if (renderer->shaders.normal_mapped_normals) { - gfx_destroy_shader_program( - gfxcore, &renderer->shaders.normal_mapped_normals); - } - if (renderer->shaders.tangents) { - gfx_destroy_shader_program(gfxcore, &renderer->shaders.tangents); - } -} - -/// Initialize renderer state for IBL if not already initialized. -static bool init_ibl(Renderer* renderer) { - assert(renderer); - - if (!renderer->ibl && !(renderer->ibl = gfx_make_ibl(renderer->gfxcore))) { - return false; - } - - if (!renderer->brdf_integration_map && - !(renderer->brdf_integration_map = gfx_make_brdf_integration_map( - renderer->ibl, renderer->gfxcore, BRDF_INTEGRATION_MAP_WIDTH, - BRDF_INTEGRATION_MAP_HEIGHT))) { - return false; - } - - return true; -} - -static ShaderProgram* load_shader(Renderer* renderer, RenderSceneMode mode) { - assert(renderer); - -#define LOAD_AND_RETURN(pShader, constructor) \ - { \ - if (!pShader) { \ - pShader = constructor(renderer->gfxcore); \ - } \ - assert(pShader); \ - return pShader; \ - } - - switch (mode) { - case RenderDefault: - return 0; - case RenderDebug: - LOAD_AND_RETURN(renderer->shaders.debug, gfx_make_debug3d_shader); - case RenderNormals: - LOAD_AND_RETURN(renderer->shaders.normals, gfx_make_view_normals_shader); - case RenderNormalMappedNormals: - LOAD_AND_RETURN( - renderer->shaders.normal_mapped_normals, - gfx_make_view_normal_mapped_normals_shader); - case RenderTangents: - LOAD_AND_RETURN(renderer->shaders.tangents, gfx_make_view_tangents_shader); - } - assert(false); - return 0; -} - -// static void log_matrix(const mat4* m) { -// for (int row = 0; row < 4; ++row) { -// LOGI("[ %5.2f, %5.2f, %5.2f, %5.2f ]", m->val[0][row], m->val[1][row], -// m->val[2][row], m->val[3][row]); -// } -// } - -/// Computes irradiance and prefiltered environment maps for the light if they -/// have not been already computed. -static bool setup_environment_light( - Renderer* renderer, GfxCore* gfxcore, EnvironmentLight* light) { - assert(renderer); - assert(light); - - if (!init_ibl(renderer)) { - return false; - } - - if (light->irradiance_map) { - assert(light->prefiltered_environment_map); - return true; - } - - Texture* irradiance_map = 0; - Texture* prefiltered_environment_map = 0; - - if (!(irradiance_map = gfx_make_irradiance_map( - renderer->ibl, gfxcore, light->environment_map, - IRRADIANCE_MAP_WIDTH, IRRADIANCE_MAP_HEIGHT))) { - goto cleanup; - } - - int max_mip_level = 0; - if (!(prefiltered_environment_map = gfx_make_prefiltered_environment_map( - renderer->ibl, gfxcore, light->environment_map, - PREFILTERED_ENVIRONMENT_MAP_WIDTH, - PREFILTERED_ENVIRONMENT_MAP_HEIGHT, &max_mip_level))) { - goto cleanup; - } - - light->irradiance_map = irradiance_map; - light->prefiltered_environment_map = prefiltered_environment_map; - light->max_reflection_lod = max_mip_level; - - return true; - -cleanup: - if (irradiance_map) { - gfx_destroy_texture(gfxcore, &irradiance_map); - } - if (prefiltered_environment_map) { - gfx_destroy_texture(gfxcore, &prefiltered_environment_map); - } - return false; -} - -typedef struct RenderState { - GfxCore* gfxcore; - Renderer* renderer; - ShaderProgram* shader; // Null to use scene shaders. - const Scene* scene; - const Camera* camera; - const mat4* camera_rotation; // From camera to world space, rotation only. - const mat4* view_matrix; - const mat4* projection; - const float fovy; - const float aspect; - Light* environment_light; - const Anima* anima; - size_t num_joints; - mat4 joint_matrices[GFX_MAX_NUM_JOINTS]; -} RenderState; - -/// Load joint matrices into the render state. -static void load_skeleton(RenderState* state, skeleton_idx skeleton_index) { - assert(state); - assert(skeleton_index.val != 0); - - const Skeleton* skeleton = mem_get_skeleton(skeleton_index); - assert(skeleton); - assert(skeleton->num_joints <= GFX_MAX_NUM_JOINTS); - - state->num_joints = skeleton->num_joints; - - for (size_t i = 0; i < skeleton->num_joints; ++i) { - const joint_idx joint_index = skeleton->joints[i]; - const Joint* joint = &state->anima->joints[joint_index]; - state->joint_matrices[i] = joint->joint_matrix; - } -} - -/// Draw the scene recursively. -static void draw_recursively( - RenderState* state, mat4 parent_transform, const SceneNode* node) { - assert(state); - const mat4 node_transform = mat4_mul(parent_transform, node->transform); - - // Anima. - if (node->type == AnimaNode) { - state->anima = gfx_get_node_anima(node); - } - // Activate light. - else if (node->type == LightNode) { - Light* light = mem_get_light(node->light); - assert(light); - - if (light->type == EnvironmentLightType) { - bool result = setup_environment_light( - state->renderer, state->gfxcore, &light->environment); - // TODO: Handle the result in a better way. - assert(result); - state->environment_light = light; - } - } - // Model. - else if (node->type == ModelNode) { - const Model* model = gfx_get_node_model(node); - const SceneNode* root = mem_get_node(model->root); - draw_recursively(state, parent_transform, root); - } - // Render object. - else if (node->type == ObjectNode) { - const SceneObject* object = mem_get_object(node->object); - assert(object); - - // TODO: Here we would frustum-cull the object. - - // TODO: Avoid computing matrices like Modelview or MVP if the shader does - // not use them. - const mat4 model_matrix = node_transform; - const mat4 modelview = mat4_mul(*state->view_matrix, model_matrix); - const mat4 mvp = mat4_mul(*state->projection, modelview); - - if (object->skeleton.val) { - load_skeleton(state, object->skeleton); - } - - for (mesh_link_idx mesh_link_index = object->mesh_link; - mesh_link_index.val;) { - const MeshLink* mesh_link = mem_get_mesh_link(mesh_link_index); - mesh_link_index = mesh_link->next; - - const Mesh* mesh = mem_get_mesh(mesh_link->mesh); - if (!mesh) { - continue; - } - assert(mesh->geometry); - assert(mesh->material); - - // TODO: Here we would frustum-cull the mesh. The AABB would have to be - // transformed by the model matrix. Rotation would make the AABB - // relatively large, but still, the culling would be conservative. - - // Apply common shader uniforms not captured by materials. - ShaderProgram* shader = state->shader ? state->shader : mesh->shader; - gfx_set_mat4_uniform(shader, "ModelMatrix", &model_matrix); - gfx_set_mat4_uniform(shader, "Modelview", &modelview); - gfx_set_mat4_uniform(shader, "View", state->view_matrix); - gfx_set_mat4_uniform(shader, "Projection", state->projection); - gfx_set_mat4_uniform(shader, "MVP", &mvp); - gfx_set_mat4_uniform(shader, "CameraRotation", state->camera_rotation); - gfx_set_float_uniform(shader, "Fovy", state->fovy); - gfx_set_float_uniform(shader, "Aspect", state->aspect); - if (state->camera) { - gfx_set_vec3_uniform( - shader, "CameraPosition", state->camera->spatial.p); - } - if (state->num_joints > 0) { - gfx_set_mat4_array_uniform( - shader, "JointMatrices", state->joint_matrices, state->num_joints); - } - // Apply lights. - if (state->environment_light) { - const EnvironmentLight* light = &state->environment_light->environment; - assert(light->environment_map); - assert(light->irradiance_map); - assert(light->prefiltered_environment_map); - assert(state->renderer->brdf_integration_map); - gfx_set_texture_uniform( - shader, "BRDFIntegrationMap", - state->renderer->brdf_integration_map); - gfx_set_texture_uniform(shader, "Sky", light->environment_map); - gfx_set_texture_uniform(shader, "IrradianceMap", light->irradiance_map); - gfx_set_texture_uniform( - shader, "PrefilteredEnvironmentMap", - light->prefiltered_environment_map); - gfx_set_float_uniform( - shader, "MaxReflectionLOD", light->max_reflection_lod); - } - material_activate(shader, mesh->material); - gfx_activate_shader_program(shader); - gfx_apply_uniforms(shader); - gfx_render_geometry(mesh->geometry); - } - - // Reset state for next object. - state->num_joints = 0; - } - - // Render children recursively. - for (node_idx child_index = node->child; child_index.val;) { - const SceneNode* child = mem_get_node(child_index); - draw_recursively(state, node_transform, child); - child_index = child->next; - } -} - -void gfx_render_scene(Renderer* renderer, const RenderSceneParams* params) { - assert(renderer); - assert(params); - assert(params->scene); - - ShaderProgram* const shader = load_shader(renderer, params->mode); - - const Scene* scene = params->scene; - const SceneCamera* camera = params->camera; - - GfxCore* gfxcore = renderer->gfxcore; - - mat4 projection, camera_rotation, view_matrix; - if (camera) { - projection = camera->camera.projection; - camera_rotation = - mat4_rotation(spatial3_transform(&camera->camera.spatial)); - view_matrix = spatial3_inverse_transform(&camera->camera.spatial); - } else { - projection = mat4_id(); - camera_rotation = mat4_id(); - view_matrix = mat4_id(); - } - - int x, y, width, height; - gfx_get_viewport(gfxcore, &x, &y, &width, &height); - const float aspect = (float)width / (float)height; - - RenderState state = { - .gfxcore = gfxcore, - .renderer = renderer, - .shader = shader, - .scene = scene, - .camera = &camera->camera, - .camera_rotation = &camera_rotation, - .view_matrix = &view_matrix, - .projection = &projection, - .environment_light = 0, - // Assuming a perspective matrix. - .fovy = atan(1.0 / (mat4_at(projection, 1, 1))) * 2, - .aspect = aspect}; - - draw_recursively(&state, mat4_id(), scene->root); -} - -static void update_rec(SceneNode* node, const SceneCamera* camera, R t) { - assert(node); - assert(camera); - - const NodeType node_type = gfx_get_node_type(node); - - // TODO: Models do not need to be animated if they are not visible to the - // camera. - if (node_type == AnimaNode) { - Anima* anima = gfx_get_node_anima_mut(node); - gfx_update_animation(anima, (R)t); - } else if (node_type == ModelNode) { - Model* model = gfx_get_node_model_mut(node); - SceneNode* root = gfx_get_model_root_mut(model); - update_rec(root, camera, t); - } - - // Children. - SceneNode* child = gfx_get_node_child_mut(node); - while (child) { - update_rec(child, camera, t); - child = gfx_get_node_sibling_mut(child); - } -} - -void gfx_update(Scene* scene, const SceneCamera* camera, R t) { - assert(scene); - assert(camera); - - SceneNode* node = gfx_get_scene_root(scene); - update_rec(node, camera, t); -} diff --git a/gfx/src/renderer/renderer_impl.h b/gfx/src/renderer/renderer_impl.h deleted file mode 100644 index fc14dcb..0000000 --- a/gfx/src/renderer/renderer_impl.h +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once - -#include - -#include - -typedef struct IBL IBL; -typedef struct ShaderProgram ShaderProgram; -typedef struct Texture Texture; - -typedef struct Renderer { - GfxCore* gfxcore; - IBL* ibl; - Texture* brdf_integration_map; - struct { - ShaderProgram* debug; - ShaderProgram* normals; - ShaderProgram* normal_mapped_normals; - ShaderProgram* tangents; - } shaders; -} Renderer; - -/// Create a new renderer. -bool renderer_make(Renderer*, GfxCore*); - -/// Destroy the renderer. -void renderer_destroy(Renderer*); diff --git a/gfx/src/scene/animation.c b/gfx/src/scene/animation.c deleted file mode 100644 index 08d02ce..0000000 --- a/gfx/src/scene/animation.c +++ /dev/null @@ -1,524 +0,0 @@ -#include "animation_impl.h" - -#include "node_impl.h" -#include "scene_memory.h" - -#include - -// #include // Debugging. - -static const R PLAYBACK_UNINITIALIZED = -1; - -static joint_idx get_anima_root_joint_index(Anima* anima) { - assert(anima); - assert(anima->num_joints > 0); - assert(anima->num_joints < GFX_MAX_NUM_JOINTS); - return anima->num_joints - 1; -} - -static Joint* get_anima_root_joint(Anima* anima) { - assert(anima); - return &anima->joints[get_anima_root_joint_index(anima)]; -} - -static const Joint* get_anima_joint(const Anima* anima, joint_idx index) { - assert(anima); - assert(index < GFX_MAX_NUM_JOINTS); - assert(index != INDEX_NONE); - assert(index < anima->num_joints); - return &anima->joints[index]; -} - -static Joint* get_anima_joint_mut(Anima* anima, joint_idx index) { - return (Joint*)get_anima_joint(anima, index); -} - -static const Joint* get_skeleton_joint( - const Anima* anima, const Skeleton* skeleton, joint_idx index) { - assert(anima); - assert(skeleton); - return get_anima_joint(anima, skeleton->joints[index]); -} - -static void set_joint_parent( - Anima* anima, joint_idx joint_index, joint_idx parent_index) { - assert(anima); - assert(joint_index != INDEX_NONE); - assert(joint_index != get_anima_root_joint_index(anima)); - assert(parent_index != INDEX_NONE); - - Joint* parent = get_anima_joint_mut(anima, parent_index); - - if (parent->child == INDEX_NONE) { - parent->child = joint_index; - } else { - // Find the last child in the chain of children. - Joint* child = get_anima_joint_mut(anima, parent->child); - while (child->next != INDEX_NONE) { - child = get_anima_joint_mut(anima, child->next); - } - // Wire up this joint as the last child's sibling. - child->next = joint_index; - } -} - -static void make_joint(Anima* anima, const JointDesc* desc, Joint* joint) { - assert(anima); - assert(desc); - assert(joint); - - // The joint matrix needs to be initialized so that meshes look right even if - // no animation is played. Initializing joint matrices to the identity makes - // meshes appear in their bind pose. - joint->child = INDEX_NONE; - joint->next = INDEX_NONE; - joint->transform = mat4_id(); - joint->inv_bind_matrix = desc->inv_bind_matrix; - joint->joint_matrix = mat4_id(); - joint->box = desc->box; -} - -static Skeleton* make_skeleton(const SkeletonDesc* desc) { - assert(desc); - assert(desc->num_joints <= GFX_MAX_NUM_JOINTS); - - Skeleton* skeleton = mem_alloc_skeleton(); - skeleton->num_joints = desc->num_joints; - memcpy( - skeleton->joints, desc->joints, - desc->num_joints * sizeof(skeleton->joints[0])); - return skeleton; -} - -static Animation* make_animation(const AnimationDesc* desc) { - assert(desc); - assert(desc->num_channels < GFX_MAX_NUM_CHANNELS); - - Animation* animation = mem_alloc_animation(); - animation->name = desc->name; - animation->duration = 0; - animation->num_channels = desc->num_channels; - R start_time = 0; - R end_time = 0; - - for (size_t c = 0; c < desc->num_channels; ++c) { - const ChannelDesc* channel_desc = &desc->channels[c]; - Channel* channel = &animation->channels[c]; - - channel->target = channel_desc->target; - channel->type = channel_desc->type; - channel->interpolation = channel_desc->interpolation; - channel->num_keyframes = channel_desc->num_keyframes; - assert(channel_desc->num_keyframes < GFX_MAX_NUM_KEYFRAMES); - - for (size_t k = 0; k < channel_desc->num_keyframes; ++k) { - const KeyframeDesc* keyframe_desc = &channel_desc->keyframes[k]; - Keyframe* keyframe = &channel->keyframes[k]; - - keyframe->time = keyframe_desc->time; - keyframe->translation = keyframe_desc->translation; - keyframe->rotation = keyframe_desc->rotation; - - start_time = keyframe->time < start_time ? keyframe->time : start_time; - end_time = keyframe->time > end_time ? keyframe->time : end_time; - } - } - - // LOGD("Animation start/end: %f / %f", start_time, end_time); - animation->duration = end_time - start_time; - assert(animation->duration >= 0); - return animation; -} - -Anima* gfx_make_anima(const AnimaDesc* desc) { - assert(desc); - assert(desc->num_joints > 0); - assert(desc->num_joints <= GFX_MAX_NUM_JOINTS); - // All joints should have a parent except for the root. - for (size_t i = 0; i < desc->num_joints - 1; ++i) { - const joint_idx parent = desc->joints[i].parent; - assert(parent != INDEX_NONE); - assert(parent < desc->num_joints); - } - // The root should have no parent. - assert(desc->joints[desc->num_joints - 1].parent == INDEX_NONE); - - Anima* anima = mem_alloc_anima(); - - // Wire the skeletons in the same order they are given in the descriptor. - Skeleton* last_skeleton = 0; - for (size_t i = 0; i < desc->num_skeletons; ++i) { - Skeleton* skeleton = make_skeleton(&desc->skeletons[i]); - const skeleton_idx skeleton_index = mem_get_skeleton_index(skeleton); - if (last_skeleton == 0) { - anima->skeleton = skeleton_index; - } else { - last_skeleton->next = skeleton_index; - } - last_skeleton = skeleton; - } - - // Wire the animations in the same order they are given in the descriptor. - Animation* last_animation = 0; - for (size_t i = 0; i < desc->num_animations; ++i) { - Animation* animation = make_animation(&desc->animations[i]); - const animation_idx animation_index = mem_get_animation_index(animation); - if (last_animation == 0) { - anima->animation = animation_index; - } else { - last_animation->next = animation_index; - } - last_animation = animation; - } - - // Create joints. - anima->num_joints = desc->num_joints; - // Initialize all joints. - // Child and sibling pointers must be initialized before wiring up the - // hierarchy. - for (size_t i = 0; i < desc->num_joints; ++i) { - Joint* joint = get_anima_joint_mut(anima, i); - make_joint(anima, &desc->joints[i], joint); - } - // Wire up joints to their parents. -1 to skip the root. - for (size_t i = 0; i < desc->num_joints - 1; ++i) { - set_joint_parent(anima, i, desc->joints[i].parent); - } - - return anima; -} - -void gfx_destroy_anima(Anima** anima) { - assert(anima); - - if (*anima) { - for (skeleton_idx i = (*anima)->skeleton; i.val != 0;) { - Skeleton* skeleton = mem_get_skeleton(i); - i = skeleton->next; - mem_free_skeleton(&skeleton); - } - - for (animation_idx i = (*anima)->animation; i.val != 0;) { - Animation* animation = mem_get_animation(i); - i = animation->next; - mem_free_animation(&animation); - } - - if ((*anima)->parent.val) { - gfx_del_node((*anima)->parent); - } - - mem_free_anima(anima); - } -} - -static Animation* find_animation(animation_idx index, const char* name) { - assert(name); - - while (index.val != 0) { - Animation* animation = mem_get_animation(index); - if (sstring_eq_cstr(animation->name, name)) { - // LOGD( - // "Found animation at index %u, %s - %s", index.val, - // sstring_cstr(&animation->name), name); - // LOGD("Animation has duration %f", animation->duration); - return animation; - } - index = animation->next; - } - - return 0; -} - -bool gfx_play_animation(Anima* anima, const AnimationPlaySettings* settings) { - assert(anima); - assert(settings); - - // TODO: Should we animate at t=0 here to kickstart the animation? Otherwise - // the client is forced to call gfx_update_animation() to do this. - Animation* animation = find_animation(anima->animation, settings->name); - if (!animation) { - return false; - } - // Playback initialized on first call to update(). - AnimationState* state = &anima->state; - state->start_time = PLAYBACK_UNINITIALIZED; - state->animation = mem_get_animation_index(animation); - state->loop = settings->loop; - return true; -} - -static void gfx_set_joint_position(Joint* joint, vec3 position) { - assert(joint); - mat4_set_v3(&joint->transform, position); -} - -static void gfx_set_joint_rotation(Joint* joint, quat rotation) { - assert(joint); - mat4_set_3x3(&joint->transform, mat4_from_quat(rotation)); -} - -static void find_keyframes(const Channel* channel, R t, int* prev, int* next) { - assert(channel); - assert(prev); - assert(next); - - *prev = -1; - *next = 0; - while (((*next + 1) < (int)channel->num_keyframes) && - (t >= channel->keyframes[*next + 1].time)) { - (*prev)++; - (*next)++; - } -} - -static R normalize_time(R a, R b, R t) { - assert(a <= t); - assert(t <= b); - return (t - a) / (b - a); -} - -static quat interpolate_rotation( - const Channel* channel, int prev, int next, R t) { - assert(channel); - - if (next == 0) { - // Animation has not started at this point in time yet. - return channel->keyframes[next].rotation; - } else { - switch (channel->interpolation) { - case StepInterpolation: - return channel->keyframes[prev].rotation; - case LinearInterpolation: { - const R normalized_t = normalize_time( - channel->keyframes[prev].time, channel->keyframes[next].time, t); - return qnormalize(qslerp( - channel->keyframes[prev].rotation, channel->keyframes[next].rotation, - normalized_t)); - break; - } - case CubicSplineInterpolation: - assert(false); // TODO - return qmake(0, 0, 0, 0); - default: - assert(false); - return qmake(0, 0, 0, 0); - } - } -} - -static vec3 interpolate_translation( - const Channel* channel, int prev, int next, R t) { - assert(channel); - - if (next == 0) { - // Animation has not started at this point in time yet. - return channel->keyframes[next].translation; - } else { - switch (channel->interpolation) { - case StepInterpolation: - return channel->keyframes[prev].translation; - case LinearInterpolation: { - const R normalized_t = normalize_time( - channel->keyframes[prev].time, channel->keyframes[next].time, t); - return vec3_lerp( - channel->keyframes[prev].translation, - channel->keyframes[next].translation, normalized_t); - break; - } - case CubicSplineInterpolation: - assert(false); // TODO - return vec3_make(0, 0, 0); - default: - assert(false); - return vec3_make(0, 0, 0); - } - } -} - -static void animate_channel(Anima* anima, const Channel* channel, R t) { - assert(anima); - assert(channel); - assert(channel->target < anima->num_joints); - - int prev, next; - find_keyframes(channel, t, &prev, &next); - - // Note that not all channels extend to the duration of an animation; some - // channels may stop animating their targets earlier. Clamp the animation time - // to the channel's end keyframe to make the rest of the math (normalize_time) - // work. - t = t > channel->keyframes[next].time ? channel->keyframes[next].time : t; - - Joint* target = get_anima_joint_mut(anima, channel->target); - - switch (channel->type) { - case RotationChannel: { - const quat rotation = interpolate_rotation(channel, prev, next, t); - gfx_set_joint_rotation(target, rotation); - break; - } - case TranslationChannel: { - const vec3 translation = interpolate_translation(channel, prev, next, t); - gfx_set_joint_position(target, translation); - break; - } - // Not yet supported. - case ScaleChannel: - case WeightsChannel: - default: - // TODO: Add back the assertion or add support for scaling. - // assert(false); - break; - } -} - -static void compute_joint_matrices_rec( - Anima* anima, Joint* joint, const mat4* parent_global_joint_transform, - const mat4* root_inv_global_transform) { - assert(anima); - assert(joint); - assert(parent_global_joint_transform); - assert(root_inv_global_transform); - - const mat4 global_joint_transform = - mat4_mul(*parent_global_joint_transform, joint->transform); - - // Compute this joint's matrix. - joint->joint_matrix = mat4_mul( - *root_inv_global_transform, - mat4_mul(global_joint_transform, joint->inv_bind_matrix)); - - // Recursively compute the joint matrices for this joint's siblings. - if (joint->next != INDEX_NONE) { - Joint* sibling = get_anima_joint_mut(anima, joint->next); - - compute_joint_matrices_rec( - anima, sibling, parent_global_joint_transform, - root_inv_global_transform); - } - - // Recursively compute the joint matrices for this joint's children. - if (joint->child != INDEX_NONE) { - Joint* child = get_anima_joint_mut(anima, joint->child); - - compute_joint_matrices_rec( - anima, child, &global_joint_transform, root_inv_global_transform); - } -} - -void gfx_update_animation(Anima* anima, R t) { - assert(anima); - - AnimationState* state = &anima->state; - if (state->animation.val == 0) { - return; // No active animation. - } - const Animation* animation = mem_get_animation(state->animation); - assert(animation); - - // On a call to play(), the start time is set to -1 to signal that the - // animation playback has not yet been initialized. - if (state->start_time == PLAYBACK_UNINITIALIZED) { - state->start_time = t; - } - // Locate the current time point inside the animation's timeline. - assert(t >= state->start_time); - assert(animation->duration >= 0.0); - const R local_time = t - state->start_time; - const R animation_time = state->loop - ? rmod(local_time, animation->duration) - : clamp(local_time, 0.0, animation->duration); - - // LOGD( - // "animation_time = %f, animation duration: %f", animation_time, - // animation->duration); - - // Play through the animation to transform skeleton nodes. - for (size_t i = 0; i < animation->num_channels; ++i) { - const Channel* channel = &animation->channels[i]; - animate_channel(anima, channel, animation_time); - } - - // Compute joint matrices after having transformed the skeletons. - // - // The anima's parent node is the common ancestor of all skeletons, and its - // transform maps the skeletons from object space to world space. This is the - // transform used as the "global transform" in the joint matrix equations. - // - // Joint matrix calculation begins by descending from the anima's root joint, - // which we have constructed to be the common root of all skeletons. - // - // This procedure touches every joint exactly once. - SceneNode* root_node = mem_get_node(anima->parent); - // LOGD("Root: %u, child: %u", anima->parent.val, root->child.val); - const mat4 root_global_transform = gfx_get_node_global_transform(root_node); - const mat4 root_inv_global_transform = mat4_inverse(root_global_transform); - - Joint* root_joint = get_anima_root_joint(anima); - compute_joint_matrices_rec( - anima, root_joint, &root_global_transform, &root_inv_global_transform); -} - -const Skeleton* gfx_get_anima_skeleton(const Anima* anima, size_t i) { - assert(anima); - - skeleton_idx skeleton_index = anima->skeleton; - const Skeleton* skeleton = mem_get_skeleton(skeleton_index); - - for (size_t j = 1; j < i; ++j) { - skeleton_index = skeleton->next; - mem_get_skeleton(skeleton_index); - } - - return skeleton; -} - -size_t gfx_get_skeleton_num_joints(const Skeleton* skeleton) { - assert(skeleton); - return skeleton->num_joints; -} - -bool gfx_joint_has_box( - const Anima* anima, const Skeleton* skeleton, size_t joint_index) { - assert(anima); - assert(skeleton); - assert(joint_index < skeleton->num_joints); - - const Joint* joint = get_skeleton_joint(anima, skeleton, joint_index); - return !aabb3_is_empty(joint->box); -} - -Box gfx_get_joint_box( - const Anima* anima, const Skeleton* skeleton, size_t joint_index) { - assert(anima); - assert(skeleton); - - const Joint* joint = get_skeleton_joint(anima, skeleton, joint_index); - - // Transform the box to anima space. - // Note that joint matrices do not usually have a translation since joints - // mostly just rotate with respect to their parent. - const vec3 pmin = joint->box.min; - const vec3 pmax = joint->box.max; - return (Box){ - .vertices = { - mat4_mul_vec3( - joint->joint_matrix, vec3_make(pmin.x, pmin.y, pmax.z), 1), - mat4_mul_vec3( - joint->joint_matrix, vec3_make(pmax.x, pmin.y, pmax.z), 1), - mat4_mul_vec3( - joint->joint_matrix, vec3_make(pmax.x, pmax.y, pmax.z), 1), - mat4_mul_vec3( - joint->joint_matrix, vec3_make(pmin.x, pmax.y, pmax.z), 1), - mat4_mul_vec3( - joint->joint_matrix, vec3_make(pmin.x, pmin.y, pmin.z), 1), - mat4_mul_vec3( - joint->joint_matrix, vec3_make(pmax.x, pmin.y, pmin.z), 1), - mat4_mul_vec3( - joint->joint_matrix, vec3_make(pmax.x, pmax.y, pmin.z), 1), - mat4_mul_vec3( - joint->joint_matrix, vec3_make(pmin.x, pmax.y, pmin.z), 1), - } - }; -} diff --git a/gfx/src/scene/animation_impl.h b/gfx/src/scene/animation_impl.h deleted file mode 100644 index 4408158..0000000 --- a/gfx/src/scene/animation_impl.h +++ /dev/null @@ -1,98 +0,0 @@ -#pragma once - -#include -#include - -#include "types.h" - -#include -#include -#include -#include -#include - -#include -#include - -typedef struct Buffer Buffer; - -// Currently ignoring scale in skinning and animation. -// -// TODO: Simultaneous animation of disjoint animations. - -/// Skeleton joint. -/// Joints are mutable and store the transform and joint matrices that result -/// from animation, aside from the inverse bind matrix. -typedef struct Joint { - joint_idx child; /// First child Joint; index into Anima's joints. - joint_idx next; /// Next sibling Joint; index into Anima's joints. - mat4 transform; /// Local transform relative to parent. - mat4 inv_bind_matrix; /// Transforms the mesh into the joint's local space. - mat4 joint_matrix; /// inv(global) * global joint transform * inv(bind). - aabb3 box; /// Bounding box of vertices affected by joint. -} Joint; - -/// Animation skeleton. -typedef struct Skeleton { - skeleton_idx next; - size_t num_joints; - joint_idx joints[GFX_MAX_NUM_JOINTS]; /// Indices into Anima's joints array. -} Skeleton; - -/// A keyframe of animation. -typedef struct Keyframe { - R time; /// Start time in [0, end animation time] - union { - vec3 translation; - quat rotation; - }; -} Keyframe; - -/// Animation channel. -typedef struct Channel { - joint_idx target; /// Index into Anima's joints array. - ChannelType type; - AnimationInterpolation interpolation; - size_t num_keyframes; - Keyframe keyframes[GFX_MAX_NUM_KEYFRAMES]; -} Channel; - -/// A skeletal animation. -typedef struct Animation { - animation_idx next; - sstring name; - R duration; - size_t num_channels; - Channel channels[GFX_MAX_NUM_CHANNELS]; -} Animation; - -/// Animation state. -/// -/// This represents the current state of an animation. -typedef struct AnimationState { - R start_time; // Time when the current animation started playing. -1 means the - // animation playback has not yet been initialized. - animation_idx animation; // Current animation. 0 = no animation. - bool loop; -} AnimationState; - -/// Animation object. -/// -/// This is the top-level animation object that encapsulates everything -/// necessary for animation. -/// -/// For lack of a better name, this is called an Anima. It is short and the -/// Latin root of animation. -/// -/// The last joint of the joints array at index 'num_joints - 1' is the root of -/// all skeletons; specifically, the root of all joints that otherwise would -/// have no parent (a skeleton need not have its own root and can be a set of -/// disjoint node hierarchies). -typedef struct Anima { - node_idx parent; /// Parent SceneNode. - skeleton_idx skeleton; /// Index of first skeleton. - animation_idx animation; /// Index of first animation. - AnimationState state; /// Current animation state. - size_t num_joints; /// Number of actual joints in the array. - Joint joints[GFX_MAX_NUM_JOINTS]; /// Shared by all skeletons. -} Anima; diff --git a/gfx/src/scene/camera.c b/gfx/src/scene/camera.c deleted file mode 100644 index be7d806..0000000 --- a/gfx/src/scene/camera.c +++ /dev/null @@ -1,37 +0,0 @@ -#include "camera_impl.h" - -#include "node_impl.h" -#include "scene_memory.h" - -#include - -SceneCamera* gfx_make_camera() { - SceneCamera* camera = mem_alloc_camera(); - - camera->camera = camera_perspective( - /*fovy=*/90.0 * TO_RAD, /*aspect=*/16.0 / 9.0, - /*near=*/0.1, /*far=*/1000); - - return camera; -} - -void gfx_destroy_camera(SceneCamera** camera) { - assert(camera); - if (*camera) { - if ((*camera)->parent.val) { - gfx_del_node((*camera)->parent); - } - mem_free_camera(camera); - } -} - -void gfx_set_camera_camera(SceneCamera* scene_camera, Camera* camera) { - assert(scene_camera); - assert(camera); - scene_camera->camera = *camera; -} - -Camera* gfx_get_camera_camera(SceneCamera* camera) { - assert(camera); - return &camera->camera; -} diff --git a/gfx/src/scene/camera_impl.h b/gfx/src/scene/camera_impl.h deleted file mode 100644 index 20c3890..0000000 --- a/gfx/src/scene/camera_impl.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include - -#include "types.h" - -#include - -typedef struct SceneCamera { - Camera camera; - node_idx parent; // Parent SceneNode. -} SceneCamera; diff --git a/gfx/src/scene/light.c b/gfx/src/scene/light.c deleted file mode 100644 index adbec8d..0000000 --- a/gfx/src/scene/light.c +++ /dev/null @@ -1,42 +0,0 @@ -#include "light_impl.h" - -#include "node_impl.h" -#include "scene_memory.h" - -#include - -static void make_environment_light( - Light* light, const EnvironmentLightDesc* desc) { - assert(light); - assert(desc); - light->type = EnvironmentLightType; - light->environment.environment_map = desc->environment_map; -} - -Light* gfx_make_light(const LightDesc* desc) { - assert(desc); - - Light* light = mem_alloc_light(); - - switch (desc->type) { - case EnvironmentLightType: - make_environment_light(light, &desc->light.environment); - break; - default: - log_error("Unhandled light type"); - gfx_destroy_light(&light); - return 0; - } - - return light; -} - -void gfx_destroy_light(Light** light) { - assert(light); - if (*light) { - if ((*light)->parent.val) { - gfx_del_node((*light)->parent); - } - mem_free_light(light); - } -} diff --git a/gfx/src/scene/light_impl.h b/gfx/src/scene/light_impl.h deleted file mode 100644 index 1aa0bb4..0000000 --- a/gfx/src/scene/light_impl.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once - -#include - -#include "types.h" - -typedef struct Texture Texture; - -/// An environment light. -typedef struct EnvironmentLight { - const Texture* environment_map; - const Texture* irradiance_map; // Renderer implementation. - const Texture* prefiltered_environment_map; // Renderer implementation. - int max_reflection_lod; // Mandatory when prefiltered_environment_map is - // given. -} EnvironmentLight; - -/// A scene light. -typedef struct Light { - LightType type; - union { - EnvironmentLight environment; - }; - node_idx parent; // Parent SceneNode. -} Light; diff --git a/gfx/src/scene/material.c b/gfx/src/scene/material.c deleted file mode 100644 index 3248243..0000000 --- a/gfx/src/scene/material.c +++ /dev/null @@ -1,57 +0,0 @@ -#include "material_impl.h" - -#include "scene_memory.h" - -#include - -static void material_make(Material* material, const MaterialDesc* desc) { - assert(material); - assert(desc); - assert(desc->num_uniforms < GFX_MAX_UNIFORMS_PER_MATERIAL); - material->num_uniforms = desc->num_uniforms; - for (int i = 0; i < desc->num_uniforms; ++i) { - material->uniforms[i] = desc->uniforms[i]; - } -} - -Material* gfx_make_material(const MaterialDesc* desc) { - assert(desc); - Material* material = mem_alloc_material(); - material_make(material, desc); - return material; -} - -void gfx_destroy_material(Material** material) { mem_free_material(material); } - -static void set_uniform(ShaderProgram* prog, const ShaderUniform* uniform) { - switch (uniform->type) { - case UniformTexture: - gfx_set_texture_uniform(prog, uniform->name.str, uniform->value.texture); - break; - case UniformMat4: - gfx_set_mat4_uniform(prog, uniform->name.str, &uniform->value.mat4); - break; - case UniformVec3: - gfx_set_vec3_uniform(prog, uniform->name.str, uniform->value.vec3); - break; - case UniformVec4: - gfx_set_vec4_uniform(prog, uniform->name.str, uniform->value.vec4); - break; - case UniformFloat: - gfx_set_float_uniform(prog, uniform->name.str, uniform->value.scalar); - break; - case UniformMat4Array: - gfx_set_mat4_array_uniform( - prog, uniform->name.str, uniform->value.array.values, - uniform->value.array.count); - break; - } -} - -void material_activate(ShaderProgram* shader, const Material* material) { - assert(material); - for (int i = 0; i < material->num_uniforms; ++i) { - const ShaderUniform* uniform = &material->uniforms[i]; - set_uniform(shader, uniform); - } -} diff --git a/gfx/src/scene/material_impl.h b/gfx/src/scene/material_impl.h deleted file mode 100644 index a6aa95b..0000000 --- a/gfx/src/scene/material_impl.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once - -#include - -typedef struct ShaderProgram ShaderProgram; - -typedef struct Material { - ShaderUniform uniforms[GFX_MAX_UNIFORMS_PER_MATERIAL]; - int num_uniforms; -} Material; - -/// Activate the material. -/// -/// This activates the material's shader and configures the shader uniforms that -/// are specific to the material. -void material_activate(ShaderProgram* shader, const Material* material); diff --git a/gfx/src/scene/mesh.c b/gfx/src/scene/mesh.c deleted file mode 100644 index 1a93bed..0000000 --- a/gfx/src/scene/mesh.c +++ /dev/null @@ -1,24 +0,0 @@ -#include "mesh_impl.h" - -#include "scene_memory.h" - -#include - -static void mesh_make(Mesh* mesh, const MeshDesc* desc) { - assert(mesh); - assert(desc); - assert(desc->geometry); - assert(desc->material); - assert(desc->shader); - mesh->geometry = desc->geometry; - mesh->material = desc->material; - mesh->shader = desc->shader; -} - -Mesh* gfx_make_mesh(const MeshDesc* desc) { - Mesh* mesh = mem_alloc_mesh(); - mesh_make(mesh, desc); - return mesh; -} - -void gfx_destroy_mesh(Mesh** mesh) { mem_free_mesh(mesh); } diff --git a/gfx/src/scene/mesh_impl.h b/gfx/src/scene/mesh_impl.h deleted file mode 100644 index 560b77e..0000000 --- a/gfx/src/scene/mesh_impl.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include - -typedef struct Mesh { - const Geometry* geometry; - const Material* material; - ShaderProgram* shader; -} Mesh; - -// TODO: a mesh_render() that takes a transform, applies the material and the -// transform, and then renders the geometry. diff --git a/gfx/src/scene/model.c b/gfx/src/scene/model.c deleted file mode 100644 index cc41a9a..0000000 --- a/gfx/src/scene/model.c +++ /dev/null @@ -1,45 +0,0 @@ -#include "model_impl.h" - -#include - -#include "scene_memory.h" - -#include - -Model* gfx_make_model(const SceneNode* root) { - assert(root); - - Model* model = mem_alloc_model(); - model->root = mem_get_node_index(root); - return model; -} - -void gfx_del_model(Model** model) { - assert(model); - - if (*model) { - SceneNode* root = mem_get_node((*model)->root); - gfx_destroy_node(&root); - *model = 0; - } -} - -Anima* gfx_get_model_anima(Model* model) { - assert(model); - - SceneNode* root = mem_get_node(model->root); - if (gfx_get_node_type(root) == AnimaNode) { - return gfx_get_node_anima_mut(root); - } else { - return 0; - } -} - -const SceneNode* gfx_get_model_root(const Model* model) { - assert(model); - return mem_get_node(model->root); -} - -SceneNode* gfx_get_model_root_mut(Model* model) { - return (SceneNode*)gfx_get_model_root(model); -} diff --git a/gfx/src/scene/model_impl.h b/gfx/src/scene/model_impl.h deleted file mode 100644 index a99d32c..0000000 --- a/gfx/src/scene/model_impl.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once - -#include - -#include "scene_memory.h" - -/// Model. -typedef struct Model { - node_idx root; - node_idx parent; // Parent SceneNode. -} Model; - -/// Create a new model. -Model* gfx_make_model(const SceneNode* root); - -/// Destroy the model. -void gfx_del_model(Model**); diff --git a/gfx/src/scene/node.c b/gfx/src/scene/node.c deleted file mode 100644 index 67ce93c..0000000 --- a/gfx/src/scene/node.c +++ /dev/null @@ -1,409 +0,0 @@ -#include "node_impl.h" - -#include "animation_impl.h" -#include "camera_impl.h" -#include "light_impl.h" -#include "model_impl.h" -#include "object_impl.h" -#include "scene_graph.h" -#include "scene_memory.h" - -#include "gfx_assert.h" - -#include -#include - -static void scene_node_make(SceneNode* node) { - assert(node); - node->type = LogicalNode; - node->transform = mat4_id(); -} - -SceneNode* gfx_make_node() { - SceneNode* node = mem_alloc_node(); - scene_node_make(node); - return node; -} - -SceneNode* gfx_make_anima_node(Anima* anima) { - assert(anima); - SceneNode* node = gfx_make_node(); - node->type = AnimaNode; - node->anima = mem_get_anima_index(anima); - anima->parent = mem_get_node_index(node); - return node; -} - -SceneNode* gfx_make_camera_node(SceneCamera* camera) { - assert(camera); - SceneNode* node = gfx_make_node(); - node->type = CameraNode; - node->camera = mem_get_camera_index(camera); - camera->parent = mem_get_node_index(node); - return node; -} - -SceneNode* gfx_make_light_node(Light* light) { - assert(light); - SceneNode* node = gfx_make_node(); - node->type = LightNode; - node->light = mem_get_light_index(light); - light->parent = mem_get_node_index(node); - return node; -} - -SceneNode* gfx_make_model_node(Model* model) { - assert(model); - SceneNode* node = gfx_make_node(); - node->type = ModelNode; - node->model = mem_get_model_index(model); - model->parent = mem_get_node_index(node); - return node; -} - -SceneNode* gfx_make_object_node(SceneObject* object) { - assert(object); - SceneNode* node = gfx_make_node(); - node->type = ObjectNode; - node->object = mem_get_object_index(object); - object->parent = mem_get_node_index(node); - return node; -} - -/// Frees the node's resource. -static void free_node_resource(SceneNode* node) { - assert(node); - - // Set the resource's parent node back to 0 to avoid a recursive call into - // gfx_del_node(). - switch (node->type) { - case AnimaNode: { - Anima* anima = mem_get_anima(node->anima); - anima->parent.val = 0; - gfx_destroy_anima(&anima); - return; - } - case CameraNode: { - SceneCamera* camera = mem_get_camera(node->camera); - camera->parent.val = 0; - gfx_destroy_camera(&camera); - return; - } - case LightNode: { - Light* light = mem_get_light(node->light); - light->parent.val = 0; - gfx_destroy_light(&light); - return; - } - case ModelNode: { - return; // Model data is owned by the asset cache. - } - case ObjectNode: { - SceneObject* object = mem_get_object(node->object); - object->parent.val = 0; - gfx_destroy_object(&object); - return; - } - case LogicalNode: - return; // Logical nodes have no resource. - } - FAIL("unhandled node type"); -} - -void gfx_construct_anima_node(SceneNode* node, Anima* anima) { - assert(node); - assert(anima); - free_node_resource(node); - node->type = AnimaNode; - node->anima = mem_get_anima_index(anima); - anima->parent = mem_get_node_index(node); -} - -void gfx_construct_camera_node(SceneNode* node, SceneCamera* camera) { - assert(node); - assert(camera); - free_node_resource(node); - node->type = CameraNode; - node->camera = mem_get_camera_index(camera); - camera->parent = mem_get_node_index(node); -} - -// TODO: Add a common helper function between each gfx_make_xyz_node() and -// gfx_construct_xyz_node() pair. -void gfx_construct_light_node(SceneNode* node, Light* light) { - assert(node); - assert(light); - free_node_resource(node); - node->type = LightNode; - node->light = mem_get_light_index(light); - light->parent = mem_get_node_index(node); -} - -void gfx_construct_model_node(SceneNode* node, Model* model) { - assert(node); - assert(model); - free_node_resource(node); - node->type = ModelNode; - node->model = mem_get_model_index(model); - model->parent = mem_get_node_index(node); -} - -void gfx_construct_object_node(SceneNode* node, SceneObject* object) { - assert(node); - assert(object); - free_node_resource(node); - node->type = ObjectNode; - node->object = mem_get_object_index(object); - object->parent = mem_get_node_index(node); -} - -static void destroy_node_rec(SceneNode* node) { - assert(node); - - // First child. - if (node->child.val) { - destroy_node_rec(mem_get_node(node->child)); - } - - // Right sibling. - if (node->next.val) { - destroy_node_rec(mem_get_node(node->next)); - } - - free_node_resource(node); - mem_free_node(&node); -} - -void gfx_destroy_node(SceneNode** node) { - assert(node); - if (*node) { - // Since the node and the whole hierarchy under it gets destroyed, there is - // no need to individually detach every node from its hierarchy. We can - // simply detach the given node and then destroy it and its sub-hierarchy. - TREE_REMOVE(*node); - destroy_node_rec(*node); - *node = 0; - } -} - -// TODO: Think more about ownership of nodes and resources. Should this function -// even exist? -void gfx_del_node(node_idx index) { - assert(index.val); - SceneNode* node = mem_get_node(index); - assert(node); - // TODO: Should destroy children recursively? - TREE_REMOVE(node); - mem_free_node(&node); -} - -NodeType gfx_get_node_type(const SceneNode* node) { - assert(node); - return node->type; -} - -#define NODE_GET(node, field, expected_type) \ - { \ - assert(node); \ - assert(node->type == expected_type); \ - return mem_get_##field(node->field); \ - } - -const Anima* gfx_get_node_anima(const SceneNode* node) { - NODE_GET(node, anima, AnimaNode); -} - -Anima* gfx_get_node_anima_mut(SceneNode* node) { - NODE_GET(node, anima, AnimaNode); -} - -const SceneCamera* gfx_get_node_camera(const SceneNode* node) { - NODE_GET(node, camera, CameraNode); -} - -SceneCamera* gfx_get_node_camera_mut(SceneNode* node) { - NODE_GET(node, camera, CameraNode); -} - -const Light* gfx_get_node_light(const SceneNode* node) { - NODE_GET(node, light, LightNode); -} - -Light* gfx_get_node_light_mut(SceneNode* node) { - NODE_GET(node, light, LightNode); -} - -const Model* gfx_get_node_model(const SceneNode* node) { - NODE_GET(node, model, ModelNode); -} - -Model* gfx_get_node_model_mut(SceneNode* node) { - NODE_GET(node, model, ModelNode); -} - -const SceneObject* gfx_get_node_object(const SceneNode* node) { - NODE_GET(node, object, ObjectNode); -} - -SceneObject* gfx_get_node_object_mut(SceneNode* node) { - NODE_GET(node, object, ObjectNode); -} - -const SceneNode* gfx_get_node_parent(const SceneNode* node) { - assert(node); - return mem_get_node(node->parent); -} - -SceneNode* gfx_get_node_parent_mut(SceneNode* node) { - assert(node); - return mem_get_node(node->parent); -} - -const SceneNode* gfx_get_node_child(const SceneNode* node) { - assert(node); - if (node->child.val) { - return mem_get_node(node->child); - } else { - return 0; - } -} - -SceneNode* gfx_get_node_child_mut(SceneNode* node) { - return (SceneNode*)gfx_get_node_child(node); -} - -const SceneNode* gfx_get_node_sibling(const SceneNode* node) { - assert(node); - if (node->next.val) { - return mem_get_node(node->next); - } else { - return 0; - } -} - -SceneNode* gfx_get_node_sibling_mut(SceneNode* node) { - return (SceneNode*)gfx_get_node_sibling(node); -} - -mat4 gfx_get_node_transform(const SceneNode* node) { - assert(node); - return node->transform; -} - -mat4 gfx_get_node_global_transform(const SceneNode* node) { - assert(node); - mat4 transform = node->transform; - node_idx parent_index = node->parent; - while (parent_index.val != 0) { - const SceneNode* parent = mem_get_node(parent_index); - transform = mat4_mul(parent->transform, transform); - parent_index = parent->parent; - } - return transform; -} - -void gfx_set_node_parent(SceneNode* child, SceneNode* parent_node) { - assert(child); - // Parent can be null. - SET_PARENT(child, parent_node); -} - -void gfx_set_node_transform(SceneNode* node, const mat4* transform) { - assert(node); - assert(transform); - node->transform = *transform; -} - -void gfx_set_node_position(SceneNode* node, const vec3* position) { - assert(node); - assert(position); - mat4_set_v3(&node->transform, *position); -} - -void gfx_set_node_rotation(SceneNode* node, const quat* rotation) { - assert(node); - assert(rotation); - mat4_set_3x3(&node->transform, mat4_from_quat(*rotation)); -} - -void gfx_set_node_rotation_mat(SceneNode* node, const mat4* rotation) { - assert(node); - assert(rotation); - mat4_set_3x3(&node->transform, *rotation); -} - -static const char* get_node_type_str(NodeType type) { - switch (type) { - case LogicalNode: - return "LogicalNode"; - case AnimaNode: - return "AnimaNode"; - case CameraNode: - return "CameraNode"; - case LightNode: - return "LightNode"; - case ModelNode: - return "ModelNode"; - case ObjectNode: - return "ObjectNode"; - } - FAIL("Unhandled node type"); - return ""; -} - -static void log_node_hierarchy_rec(const SceneNode* node, const sstring* pad) { - assert(node); - assert(pad); - - LOGI( - "%s%s (%u)", sstring_cstr(pad), get_node_type_str(node->type), - mem_get_node_index(node).val); - - // Log the children. - if (node->child.val) { - const sstring new_pad = sstring_concat_cstr(*pad, " "); - log_node_hierarchy_rec(mem_get_node(node->child), &new_pad); - } - - // Then log the siblings. - if (node->next.val) { - log_node_hierarchy_rec(mem_get_node(node->next), pad); - } -} - -void gfx_log_node_hierarchy(const SceneNode* node) { - const sstring pad = sstring_make(""); - log_node_hierarchy_rec(node, &pad); -} - -static SceneNode* clone_scene_rec(const SceneNode* node) { - assert(node); - - SceneNode* copy = mem_alloc_node(); - *copy = *node; // Shallow clone of the node's resource. - - if (node->child.val) { - SceneNode* child = mem_get_node(node->child); - SceneNode* child_copy = clone_scene_rec(child); - copy->child = mem_get_node_index(child_copy); - child_copy->parent = mem_get_node_index(copy); - } - - if (node->next.val) { - SceneNode* next = mem_get_node(node->next); - SceneNode* next_copy = clone_scene_rec(next); - copy->next = mem_get_node_index(next_copy); - next_copy->prev = mem_get_node_index(copy); - } - - return copy; -} - -SceneNode* gfx_clone_scene_shallow(const SceneNode* node) { - assert(node); - // Must be a root node; not allowed to have siblings. - assert(!node->prev.val); - assert(!node->next.val); - - return clone_scene_rec(node); -} diff --git a/gfx/src/scene/node_impl.h b/gfx/src/scene/node_impl.h deleted file mode 100644 index c79f252..0000000 --- a/gfx/src/scene/node_impl.h +++ /dev/null @@ -1,40 +0,0 @@ -#pragma once - -#include - -#include "types.h" - -#include -#include - -/// Scene node. -/// -/// The SceneNode owns its cameras, objects, lights and child nodes. These -/// together form a strict tree hierarchy and not a more general DAG. -typedef struct SceneNode { - NodeType type; - union { - anima_idx anima; - camera_idx camera; - light_idx light; - model_idx model; - object_idx object; - }; - mat4 transform; // Transformation for this node and its children. - node_idx parent; // Parent SceneNode. - node_idx child; // First child SceneNode. - node_idx next; // Next sibling SceneNode. - node_idx prev; // Previous sibling SceneNode. -} SceneNode; - -/// Recursively destroy a node given its index but without destroying the node -/// resources. -/// -/// The node and its children are removed from the scene graph. -/// -/// This function is for the library's internal use only. -void gfx_del_node(node_idx); - -/// Return a shallow clone of the scene rooted at the given node. -/// The given node must have no siblings (must be a root node). -SceneNode* gfx_clone_scene_shallow(const SceneNode*); diff --git a/gfx/src/scene/object.c b/gfx/src/scene/object.c deleted file mode 100644 index e8e3ee6..0000000 --- a/gfx/src/scene/object.c +++ /dev/null @@ -1,83 +0,0 @@ -#include "object_impl.h" - -#include - -#include "mesh_impl.h" -#include "node_impl.h" -#include "scene_memory.h" - -#include - -static aabb3 calc_object_aabb(const SceneObject* object) { - assert(object); - - bool first = true; - aabb3 box; - - mesh_link_idx ml = object->mesh_link; - while (ml.val) { - const MeshLink* mesh_link = mem_get_mesh_link(ml); - const mesh_idx mi = mesh_link->mesh; - if (mi.val) { - const Mesh* mesh = mem_get_mesh(mi); - const aabb3 mesh_box = gfx_get_geometry_aabb(mesh->geometry); - if (first) { - box = mesh_box; - first = false; - } else { - box = aabb3_sum(box, mesh_box); - } - } - ml = mesh_link->next; - } - - return box; -} - -static void add_object_mesh(SceneObject* object, Mesh* mesh) { - assert(object); - assert(mesh); - - MeshLink* link = mem_alloc_mesh_link(); - link->mesh = mem_get_mesh_index(mesh); - link->next = object->mesh_link; - object->mesh_link = mem_get_mesh_link_index(link); -} - -SceneObject* gfx_make_object(const ObjectDesc* desc) { - assert(desc); - - SceneObject* object = mem_alloc_object(); - for (size_t i = 0; i < desc->num_meshes; ++i) { - add_object_mesh(object, desc->meshes[i]); - } - object->box = calc_object_aabb(object); - return object; -} - -void gfx_destroy_object(SceneObject** object) { - assert(object); - - if (*object) { - if ((*object)->parent.val) { - gfx_del_node((*object)->parent); - } - mem_free_object(object); - } -} - -void gfx_set_object_skeleton(SceneObject* object, const Skeleton* skeleton) { - assert(object); - assert(skeleton); - object->skeleton = mem_get_skeleton_index(skeleton); -} - -const Skeleton* gfx_get_object_skeleton(const SceneObject* object) { - assert(object); - return (object->skeleton.val == 0) ? 0 : mem_get_skeleton(object->skeleton); -} - -aabb3 gfx_get_object_aabb(const SceneObject* object) { - assert(object); - return object->box; -} diff --git a/gfx/src/scene/object_impl.h b/gfx/src/scene/object_impl.h deleted file mode 100644 index 88f8e31..0000000 --- a/gfx/src/scene/object_impl.h +++ /dev/null @@ -1,26 +0,0 @@ -#pragma once - -#include - -#include "types.h" - -#include - -typedef struct MeshLink { - mesh_idx mesh; - mesh_link_idx next; // Next MeshLink in the list. -} MeshLink; - -/// Scene object. -/// -/// A SceneObject does not own its Meshes, and they are instead shared for -/// re-use. The SceneObject consequently embeds a list of MeshLinks as opposed -/// to a list of Meshes. The MeshLinks define a list of Meshes, which can be -/// different for each SceneObject. Each SceneObject may then have a unique list -/// of Meshes, and the Meshes are re-used. -typedef struct SceneObject { - mesh_link_idx mesh_link; /// First MeshLink in the list. - skeleton_idx skeleton; /// 0 for static objects. - node_idx parent; /// Parent SceneNode. - aabb3 box; -} SceneObject; diff --git a/gfx/src/scene/scene.c b/gfx/src/scene/scene.c deleted file mode 100644 index 54452dd..0000000 --- a/gfx/src/scene/scene.c +++ /dev/null @@ -1,25 +0,0 @@ -#include "scene_impl.h" - -#include "node_impl.h" -#include "scene_memory.h" - -#include - -Scene* gfx_make_scene(void) { - Scene* scene = mem_alloc_scene(); - scene->root = gfx_make_node(); - return scene; -} - -void gfx_destroy_scene(Scene** scene) { - assert(scene); - if (*scene) { - gfx_destroy_node(&(*scene)->root); - mem_free_scene(scene); - } -} - -SceneNode* gfx_get_scene_root(Scene* scene) { - assert(scene); - return scene->root; -} diff --git a/gfx/src/scene/scene_graph.h b/gfx/src/scene/scene_graph.h deleted file mode 100644 index a26f828..0000000 --- a/gfx/src/scene/scene_graph.h +++ /dev/null @@ -1,138 +0,0 @@ -/// Functions for list manipulation. -#pragma once - -#include "scene_memory.h" - -// NOTE: SceneMemory guarantees that index 0 can be regarded as an invalid -// index. - -#define MEM_GET(INDEX) \ - _Generic((INDEX), camera_idx \ - : mem_get_camera, material_idx \ - : mem_get_material, mesh_idx \ - : mem_get_mesh, mesh_link_idx \ - : mem_get_mesh_link, node_idx \ - : mem_get_node, object_idx \ - : mem_get_object, scene_idx \ - : mem_get_scene)(INDEX) - -#define MEM_GET_INDEX(ITEM) \ - _Generic((ITEM), SceneCamera * \ - : mem_get_camera_index, Material * \ - : mem_get_material_index, Mesh * \ - : mem_get_mesh_index, MeshLink * \ - : mem_get_mesh_link_index, SceneNode * \ - : mem_get_node_index, SceneObject * \ - : mem_get_object_index, Scene * \ - : mem_get_scene_index)(ITEM) - -/// Assert the list node invariant. -/// -/// - A node does not point to itself. -#define ASSERT_LIST_NODE_INVARIANT(ITEM) \ - { \ - const gfx_idx item_idx = MEM_GET_INDEX(ITEM).val; \ - assert((ITEM)->prev.val != item_idx); \ - assert((ITEM)->next.val != item_idx); \ - } - -/// Assert the tree node invariant. -/// -/// - A node does not point to itself. -/// - The node's left and right siblings cannot be equal, unless both are 0. -/// - The node's left/right sibling cannot be its child, unless both are 0. -/// - The node's parent cannot be the node's child or sibling, unless it's 0. -/// - If the node has a parent and the node is the leftmost sibling, then the -/// parent's child is the node. -#define ASSERT_TREE_NODE_INVARIANT(ITEM) \ - { \ - const gfx_idx item_idx = MEM_GET_INDEX(ITEM).val; \ - assert((ITEM)->prev.val != item_idx); \ - assert((ITEM)->next.val != item_idx); \ - if ((ITEM)->prev.val) { \ - assert((ITEM)->prev.val != (ITEM)->next.val); \ - } \ - if ((ITEM)->child.val) { \ - assert((ITEM)->child.val != (ITEM)->prev.val); \ - assert((ITEM)->child.val != (ITEM)->next.val); \ - } \ - assert((ITEM)->parent.val != item_idx); \ - if ((ITEM)->parent.val && !(ITEM)->prev.val) { \ - assert((ITEM)->parent.val != (ITEM)->prev.val); \ - assert((ITEM)->parent.val != (ITEM)->next.val); \ - const __typeof__(ITEM) item_parent = MEM_GET((ITEM)->parent); \ - assert(item_parent->child.val == item_idx); \ - } \ - } - -/// Prepend an item to a list. -/// Modify HEAD_INDEX to equal the index of the new head. -#define LIST_PREPEND(HEAD_INDEX, ITEM) \ - (ITEM)->next = HEAD_INDEX; \ - if (HEAD_INDEX.val) { \ - __typeof__(ITEM) old_head = MEM_GET(HEAD_INDEX); \ - old_head->prev = MEM_GET_INDEX(ITEM); \ - } \ - HEAD_INDEX = MEM_GET_INDEX(ITEM); \ - ASSERT_LIST_NODE_INVARIANT(ITEM); - -/// Disconnect an item from its siblings. -#define LIST_REMOVE(ITEM) \ - if ((ITEM)->prev.val) { \ - __typeof__(ITEM) prev_sibling = MEM_GET((ITEM)->prev); \ - prev_sibling->next = (ITEM)->next; \ - } \ - if ((ITEM)->next.val) { \ - __typeof__(ITEM) next_sibling = MEM_GET((ITEM)->next); \ - next_sibling->prev = (ITEM)->prev; \ - } \ - (ITEM)->prev.val = 0; \ - (ITEM)->next.val = 0; \ - ASSERT_LIST_NODE_INVARIANT(ITEM); - -/// Set the child's parent. -/// -/// The hierarchy is a strict tree hierarchy and a parent node points to its -/// first/leftmost child only. To add a new child, the new child becomes the -/// leftmost node in the list of siblings, the one that the parent then points -/// to. -/// -/// The child is also completely disconnected from its previous hierarchy. This -/// is because siblings in a hierarchy must all point to the same parent. -#define SET_PARENT(CHILD, PARENT) \ - assert(CHILD); \ - assert(CHILD != PARENT); \ - ASSERT_TREE_NODE_INVARIANT(CHILD); \ - ASSERT_TREE_NODE_INVARIANT(PARENT); \ - TREE_REMOVE(CHILD); /* Disconnect CHILD from its previous hierarchy. */ \ - if (PARENT) { \ - LIST_PREPEND((PARENT)->child, CHILD); \ - (CHILD)->parent = MEM_GET_INDEX(PARENT); \ - } else { \ - (CHILD)->parent.val = 0; \ - } \ - ASSERT_TREE_NODE_INVARIANT(CHILD); \ - if (PARENT) { \ - ASSERT_TREE_NODE_INVARIANT(PARENT); \ - } - -/// Remove an item from its hierarchy. -/// -/// The item is disconnected from its parents and siblings. The hierarchy rooted -/// under the item remains intact. -#define TREE_REMOVE(ITEM) \ - assert(ITEM); \ - if ((ITEM)->parent.val) { \ - /* The parent points only to its first/leftmost child. If this item is */ \ - /* the leftmost sibling, then we need to rewire the parent to point to */ \ - /* the next sibling to keep the parent connected to its children. */ \ - __typeof__(ITEM) parent = MEM_GET((ITEM)->parent); \ - const __typeof__(ITEM) parent_child = MEM_GET(parent->child); \ - if (parent_child == ITEM) { \ - assert((ITEM)->prev.val == 0); \ - parent->child = (ITEM)->next; \ - } \ - } \ - (ITEM)->parent.val = 0; \ - LIST_REMOVE(ITEM); /* Disconnect ITEM from its siblings. */ \ - ASSERT_TREE_NODE_INVARIANT(ITEM); diff --git a/gfx/src/scene/scene_impl.h b/gfx/src/scene/scene_impl.h deleted file mode 100644 index 992f620..0000000 --- a/gfx/src/scene/scene_impl.h +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once - -#include - -#include "types.h" - -typedef struct SceneNode SceneNode; - -typedef struct Scene { - SceneNode* root; - scene_idx next; - scene_idx prev; -} Scene; diff --git a/gfx/src/scene/scene_memory.c b/gfx/src/scene/scene_memory.c deleted file mode 100644 index 85c27e7..0000000 --- a/gfx/src/scene/scene_memory.c +++ /dev/null @@ -1,149 +0,0 @@ -#include "scene_memory.h" - -#include - -#include "animation_impl.h" -#include "camera_impl.h" -#include "light_impl.h" -#include "material_impl.h" -#include "mesh_impl.h" -#include "model_impl.h" -#include "node_impl.h" -#include "object_impl.h" -#include "scene_impl.h" - -#include - -DEF_MEMPOOL(anima_pool, Anima, GFX_MAX_NUM_ANIMAS) -DEF_MEMPOOL(animation_pool, Animation, GFX_MAX_NUM_ANIMATIONS) -DEF_MEMPOOL(camera_pool, SceneCamera, GFX_MAX_NUM_CAMERAS) -DEF_MEMPOOL(light_pool, Light, GFX_MAX_NUM_LIGHTS) -DEF_MEMPOOL(material_pool, Material, GFX_MAX_NUM_MATERIALS) -DEF_MEMPOOL(mesh_pool, Mesh, GFX_MAX_NUM_MESHES) -DEF_MEMPOOL(mesh_link_pool, MeshLink, GFX_MAX_NUM_MESH_LINKS) -DEF_MEMPOOL(model_pool, Model, GFX_MAX_NUM_MODELS) -DEF_MEMPOOL(node_pool, SceneNode, GFX_MAX_NUM_NODES) -DEF_MEMPOOL(object_pool, SceneObject, GFX_MAX_NUM_OBJECTS) -DEF_MEMPOOL(scene_pool, Scene, GFX_MAX_NUM_SCENES) -DEF_MEMPOOL(skeleton_pool, Skeleton, GFX_MAX_NUM_SKELETONS) - -/// Scene memory. -/// -/// Holds memory pools for every type of scene object. -typedef struct SceneMemory { - anima_pool animas; - animation_pool animations; - camera_pool cameras; - light_pool lights; - material_pool materials; - mesh_pool meshs; // Purposeful typo to make the PLURAL() macro work. - mesh_link_pool mesh_links; - model_pool models; - node_pool nodes; - object_pool objects; - scene_pool scenes; - skeleton_pool skeletons; -} SceneMemory; - -static SceneMemory mem; - -#define ALLOC_DUMMY(POOL) \ - { \ - const void* object = mempool_alloc(POOL); \ - assert(mempool_get_block_index(POOL, object) == 0); \ - } - -#define PLURAL(name) name##s -#define MEM_FIELD(name) mem.PLURAL(name) - -void scene_mem_init() { - mempool_make(&mem.animas); - mempool_make(&mem.animations); - mempool_make(&mem.cameras); - mempool_make(&mem.lights); - mempool_make(&mem.materials); - mempool_make(&mem.meshs); - mempool_make(&mem.mesh_links); - mempool_make(&mem.models); - mempool_make(&mem.nodes); - mempool_make(&mem.objects); - mempool_make(&mem.scenes); - mempool_make(&mem.skeletons); - - // Allocate dummy objects at index 0 to guarantee that no objects allocated by - // the caller map to index 0. - ALLOC_DUMMY(&mem.animas); - ALLOC_DUMMY(&mem.animations); - ALLOC_DUMMY(&mem.cameras); - ALLOC_DUMMY(&mem.lights); - ALLOC_DUMMY(&mem.materials); - ALLOC_DUMMY(&mem.meshs); - ALLOC_DUMMY(&mem.mesh_links); - ALLOC_DUMMY(&mem.models); - ALLOC_DUMMY(&mem.nodes); - ALLOC_DUMMY(&mem.objects); - ALLOC_DUMMY(&mem.scenes); - ALLOC_DUMMY(&mem.skeletons); -} - -void scene_mem_destroy() { - // NOTE: the dummy objects are not constructed, so the destruction code below - // always skips index 0. (I don't really like the conditional inside the loop, - // but this gets the job done without having to specialize the loop macro.) -#define DESTROY(name) \ - mempool_foreach(&MEM_FIELD(name), obj, { \ - if (i > 0) { \ - gfx_destroy_##name(&obj); \ - } \ - }) - - // Models contain scene elements. Destruction is handled by the remainder of - // scene destructionb elow. - // - // First destroy the scenes. This will recursively destroy the scene's nodes - // and their objects and avoid a double-free when we then destroy any stray - // scene elements. - DESTROY(scene); - // Then delete stray nodes. This will delete their children nodes and - // resource. - DESTROY(node); - // Destroy remaining scene elements. - DESTROY(anima); - // Animations are owned by animas and do not have a destructor. - DESTROY(camera); - DESTROY(light); - DESTROY(material); - DESTROY(mesh); - // Mesh links don't have a destructor. - DESTROY(object); - // Skeletons are owned by animas and do not have a destructor. -} - -#define DEF_MEMORY(name, type) \ - /* xyz* mem_alloc_xyz(); */ \ - type* mem_alloc_##name() { return mempool_alloc(&MEM_FIELD(name)); } \ - /* void mem_free_xyz(xyz**); */ \ - void mem_free_##name(type** obj) { mempool_free(&MEM_FIELD(name), obj); } \ - /* xyz* mem_get_xyz(xyz_idx); */ \ - type* mem_get_##name(NAMED_INDEX(name) index) { \ - assert(index.val != 0); /* 0 is the dummy allocation. */ \ - return mempool_get_block(&MEM_FIELD(name), index.val); \ - } \ - /* xyz_idx mem_get_xyz_index(const xyz*); */ \ - NAMED_INDEX(name) mem_get_##name##_index(const type* obj) { \ - return (NAMED_INDEX(name)){ \ - .val = mempool_get_block_index(&MEM_FIELD(name), obj)}; \ - } - -DEF_MEMORY(anima, Anima) -DEF_MEMORY(animation, Animation) -DEF_MEMORY(camera, SceneCamera) -DEF_MEMORY(light, Light) -DEF_MEMORY(material, Material) -DEF_MEMORY(mesh, Mesh) -DEF_MEMORY(mesh_link, MeshLink) -DEF_MEMORY(model, Model) -DEF_MEMORY(node, SceneNode) -DEF_MEMORY(object, SceneObject) -DEF_MEMORY(scene, Scene) -DEF_MEMORY(skeleton, Skeleton) diff --git a/gfx/src/scene/scene_memory.h b/gfx/src/scene/scene_memory.h deleted file mode 100644 index d175cba..0000000 --- a/gfx/src/scene/scene_memory.h +++ /dev/null @@ -1,39 +0,0 @@ -/// Memory management of scene objects. -#pragma once - -#include "types.h" - -/// Initialize scene memory. -/// -/// The scene memory guarantees that every object maps to an index different -/// than 0. This way, 0 can be used as a special index to denote "no value". -void scene_mem_init(); - -/// Destroy the scene memory and all allocated objects. -void scene_mem_destroy(); - -#define NAMED_INDEX(name) name##_idx - -#define DECL_MEMORY(name, type) \ - typedef struct type type; \ - /* xyz* mem_alloc_xyz() */ \ - type* mem_alloc_##name(); \ - /* mem_free_xyz(xyz**) */ \ - void mem_free_##name(type**); \ - /* xyz* mem_get_xyz(xyz_idx); */ \ - type* mem_get_##name(NAMED_INDEX(name)); \ - /* xyz_idx mem_get_xyz_index(const xyz*); */ \ - NAMED_INDEX(name) mem_get_##name##_index(const type*); - -DECL_MEMORY(anima, Anima) -DECL_MEMORY(animation, Animation) -DECL_MEMORY(camera, SceneCamera) -DECL_MEMORY(light, Light) -DECL_MEMORY(material, Material) -DECL_MEMORY(mesh, Mesh) -DECL_MEMORY(mesh_link, MeshLink) -DECL_MEMORY(model, Model) -DECL_MEMORY(node, SceneNode) -DECL_MEMORY(object, SceneObject) -DECL_MEMORY(scene, Scene) -DECL_MEMORY(skeleton, Skeleton) diff --git a/gfx/src/scene/types.h b/gfx/src/scene/types.h deleted file mode 100644 index d0ffc41..0000000 --- a/gfx/src/scene/types.h +++ /dev/null @@ -1,24 +0,0 @@ -/// Strongly-typed indices for every kind of scene node resource. -#pragma once - -#include - -typedef uint16_t gfx_idx; - -#define DEF_STRONG_INDEX(TYPE_NAME, IDX_TYPE) \ - typedef struct TYPE_NAME##_idx { \ - IDX_TYPE val; \ - } TYPE_NAME##_idx; - -DEF_STRONG_INDEX(anima, gfx_idx) -DEF_STRONG_INDEX(animation, gfx_idx) -DEF_STRONG_INDEX(camera, gfx_idx) -DEF_STRONG_INDEX(light, gfx_idx) -DEF_STRONG_INDEX(material, gfx_idx) -DEF_STRONG_INDEX(mesh, gfx_idx) -DEF_STRONG_INDEX(mesh_link, gfx_idx) -DEF_STRONG_INDEX(model, gfx_idx) -DEF_STRONG_INDEX(node, gfx_idx) -DEF_STRONG_INDEX(object, gfx_idx) -DEF_STRONG_INDEX(scene, gfx_idx) -DEF_STRONG_INDEX(skeleton, gfx_idx) diff --git a/gfx/src/util/geometry.c b/gfx/src/util/geometry.c deleted file mode 100644 index afe0109..0000000 --- a/gfx/src/util/geometry.c +++ /dev/null @@ -1,44 +0,0 @@ -#include - -#include - -static void make_quad_11_positions(vec2 positions[4]) { - positions[0] = vec2_make(-1, +1); - positions[1] = vec2_make(-1, -1); - positions[2] = vec2_make(+1, +1); - positions[3] = vec2_make(+1, -1); -} - -static void make_quad_01_positions(vec2 positions[4]) { - positions[0] = vec2_make(0, 0); - positions[1] = vec2_make(1, 0); - positions[2] = vec2_make(1, 1); - positions[3] = vec2_make(0, 1); -} - -static GeometryDesc make_quad_desc(vec2 positions[4]) { - GeometryDesc desc = (GeometryDesc){0}; - desc.positions2d.data = positions; - desc.positions2d.size_bytes = 4 * sizeof(vec2); - desc.num_verts = 4; - desc.type = TriangleStrip; - return desc; -} - -Geometry* gfx_make_quad_11(GfxCore* gfxcore) { - assert(gfxcore); - - vec2 positions[4]; - make_quad_11_positions(positions); - const GeometryDesc geometry_desc = make_quad_desc(positions); - return gfx_make_geometry(gfxcore, &geometry_desc); -} - -Geometry* gfx_make_quad_01(GfxCore* gfxcore) { - assert(gfxcore); - - vec2 positions[4]; - make_quad_01_positions(positions); - const GeometryDesc geometry_desc = make_quad_desc(positions); - return gfx_make_geometry(gfxcore, &geometry_desc); -} diff --git a/gfx/src/util/ibl.c b/gfx/src/util/ibl.c deleted file mode 100644 index 5a79990..0000000 --- a/gfx/src/util/ibl.c +++ /dev/null @@ -1,328 +0,0 @@ -#include - -#include -#include -#include -#include - -#include -#include - -typedef struct IBL { - Geometry* quad; - ShaderProgram* brdf_integration_map_shader; - ShaderProgram* irradiance_map_shader; - ShaderProgram* prefiltered_environment_map_shader; - Texture* brdf_integration_map; - FrameBuffer* framebuffer; - mat4 rotations[6]; -} IBL; - -static const CubemapFace faces[6] = { - CubemapFacePosX, // Right. - CubemapFaceNegX, // Left. - CubemapFacePosY, // Up. - CubemapFaceNegY, // Down. - CubemapFacePosZ, // Back. - CubemapFaceNegZ, // Front. -}; - -static const float flips[6] = { - -1.0f, // Right. - -1.0f, // Left. - +1.0f, // Up. - +1.0f, // Down. - -1.0f, // Back. - -1.0f, // Front. -}; - -IBL* gfx_make_ibl(GfxCore* gfxcore) { - assert(gfxcore); - - IBL* ibl = calloc(1, sizeof(IBL)); - if (!ibl) { - return 0; - } - - if (!(ibl->quad = gfx_make_quad_11(gfxcore))) { - goto cleanup; - } - - // We only need the BRDF integration once since we are caching the map, but - // compiling the shader up front may lead to fewer surprises. Not that the - // shader is fully compiled up front anyway, since the driver will typically - // defer full compilation to the first draw call. - if (!(ibl->brdf_integration_map_shader = - gfx_make_brdf_integration_map_shader(gfxcore))) { - goto cleanup; - } - - if (!(ibl->irradiance_map_shader = gfx_make_irradiance_map_shader(gfxcore))) { - goto cleanup; - } - - if (!(ibl->prefiltered_environment_map_shader = - gfx_make_prefiltered_environment_map_shader(gfxcore))) { - goto cleanup; - } - - // Create an empty framebuffer for now. Will attach the colour buffer later - // as we render the faces of the cube. - if (!(ibl->framebuffer = gfx_make_framebuffer( - gfxcore, - &(FrameBufferDesc){ - .colour = - (FrameBufferAttachment){.type = FrameBufferNoAttachment}, - .depth = (FrameBufferAttachment){ - .type = FrameBufferNoAttachment}}))) { - goto cleanup; - } - - // TODO: Debug the camera rotations. Irradiance debug output should appear - // just like the input cubemap. - - // Right. - ibl->rotations[0] = mat4_lookat( - /*position=*/vec3_make(0, 0, 0), - /*target=*/vec3_make(1, 0, 0), - /*up=*/vec3_make(0, 1, 0)); - // Left. - ibl->rotations[1] = mat4_lookat( - /*position=*/vec3_make(0, 0, 0), - /*target=*/vec3_make(-1, 0, 0), - /*up=*/vec3_make(0, 1, 0)); - // Up. - ibl->rotations[2] = mat4_lookat( - /*position=*/vec3_make(0, 0, 0), - /*target=*/vec3_make(0, 1, 0), - /*up=*/vec3_make(0, 0, 1)); - // Down. - ibl->rotations[3] = mat4_lookat( - /*position=*/vec3_make(0, 0, 0), - /*target=*/vec3_make(0, -1, 0), - /*up=*/vec3_make(0, 0, -1)); - // Back. - ibl->rotations[4] = mat4_lookat( - /*position=*/vec3_make(0, 0, 0), - /*target=*/vec3_make(0, 0, 1), - /*up=*/vec3_make(0, 1, 0)); - // Front. - ibl->rotations[5] = mat4_lookat( - /*position=*/vec3_make(0, 0, 0), - /*target=*/vec3_make(0, 0, -1), - /*up=*/vec3_make(0, 1, 0)); - - return ibl; - -cleanup: - gfx_destroy_ibl(gfxcore, &ibl); - return 0; -} - -void gfx_destroy_ibl(GfxCore* gfxcore, IBL** ibl) { - if (!ibl) { - return; - } - if ((*ibl)->quad) { - gfx_destroy_geometry(gfxcore, &(*ibl)->quad); - } - if ((*ibl)->brdf_integration_map_shader) { - gfx_destroy_shader_program(gfxcore, &(*ibl)->brdf_integration_map_shader); - } - if ((*ibl)->irradiance_map_shader) { - gfx_destroy_shader_program(gfxcore, &(*ibl)->irradiance_map_shader); - } - if ((*ibl)->prefiltered_environment_map_shader) { - gfx_destroy_shader_program( - gfxcore, &(*ibl)->prefiltered_environment_map_shader); - } - if ((*ibl)->brdf_integration_map) { - gfx_destroy_texture(gfxcore, &(*ibl)->brdf_integration_map); - } - if ((*ibl)->framebuffer) { - gfx_destroy_framebuffer(gfxcore, &(*ibl)->framebuffer); - } - free(*ibl); - *ibl = 0; -} - -Texture* gfx_make_brdf_integration_map( - IBL* ibl, GfxCore* gfxcore, int width, int height) { - assert(ibl); - assert(gfxcore); - - if (ibl->brdf_integration_map) { - return ibl->brdf_integration_map; - } - - bool success = false; - - if (!(ibl->brdf_integration_map = gfx_make_texture( - gfxcore, &(TextureDesc){ - .width = width, - .height = height, - .depth = 1, - .dimension = Texture2D, - .format = TextureRG16F, - .filtering = LinearFiltering, - .wrap = ClampToEdge, - .mipmaps = false}))) { - goto cleanup; - } - - gfx_activate_framebuffer(ibl->framebuffer); - gfx_framebuffer_set_viewport(ibl->framebuffer, 0, 0, width, height); - gfx_activate_shader_program(ibl->brdf_integration_map_shader); - if (!gfx_framebuffer_attach_colour( - ibl->framebuffer, &(FrameBufferAttachment){ - .type = FrameBufferTexture, - .texture.texture = ibl->brdf_integration_map, - .texture.mip_level = 0})) { - goto cleanup; - } - gfx_render_geometry(ibl->quad); - - success = true; - -cleanup: - gfx_deactivate_shader_program(ibl->brdf_integration_map_shader); - gfx_deactivate_framebuffer(ibl->framebuffer); - if (!success && ibl->brdf_integration_map) { - gfx_destroy_texture(gfxcore, &ibl->brdf_integration_map); - return 0; - } else { - return ibl->brdf_integration_map; - } -} - -Texture* gfx_make_irradiance_map( - IBL* ibl, GfxCore* gfxcore, const Texture* environment_map, int width, - int height) { - assert(ibl); - assert(gfxcore); - assert(environment_map); - - bool success = false; - - Texture* irradiance_map = 0; - - // TODO: Could define colour-renderable texture formats separately to make - // framebuffer creation less error-prone. Or, at the very least, validate the - // choice at runtime. - // - // Make sure to use a float colour format to avoid [0,1] clamping when the - // irradiance values are computed! - if (!(irradiance_map = gfx_make_texture( - gfxcore, &(TextureDesc){ - .width = width, - .height = height, - .depth = 1, - .dimension = TextureCubeMap, - .format = TextureR11G11B10F, - .filtering = LinearFiltering, - .mipmaps = false}))) { - goto cleanup; - } - - gfx_activate_framebuffer(ibl->framebuffer); - gfx_framebuffer_set_viewport(ibl->framebuffer, 0, 0, width, height); - gfx_activate_shader_program(ibl->irradiance_map_shader); - gfx_set_texture_uniform(ibl->irradiance_map_shader, "Sky", environment_map); - for (int i = 0; i < 6; ++i) { - if (!gfx_framebuffer_attach_colour( - ibl->framebuffer, &(FrameBufferAttachment){ - .type = FrameBufferCubemapTexture, - .cubemap.face = faces[i], - .cubemap.texture = irradiance_map})) { - goto cleanup; - } - gfx_set_float_uniform(ibl->irradiance_map_shader, "Flip", flips[i]); - gfx_set_mat4_uniform( - ibl->irradiance_map_shader, "CameraRotation", &ibl->rotations[i]); - gfx_apply_uniforms(ibl->irradiance_map_shader); - gfx_render_geometry(ibl->quad); - } - - success = true; - -cleanup: - gfx_deactivate_shader_program(ibl->irradiance_map_shader); - gfx_deactivate_framebuffer(ibl->framebuffer); - if (!success && irradiance_map) { - gfx_destroy_texture(gfxcore, &irradiance_map); - return 0; - } else { - return irradiance_map; - } -} - -Texture* gfx_make_prefiltered_environment_map( - IBL* ibl, GfxCore* gfxcore, const Texture* environment_map, int width, - int height, int* max_mip_level) { - assert(ibl); - assert(gfxcore); - assert(environment_map); - assert(max_mip_level); - - bool success = false; - - Texture* prefiltered_env_map = 0; - - if (!(prefiltered_env_map = gfx_make_texture( - gfxcore, &(TextureDesc){ - .width = width, - .height = height, - .depth = 1, - .dimension = TextureCubeMap, - .format = TextureR11G11B10F, - .filtering = LinearFiltering, - .mipmaps = true}))) { - goto cleanup; - } - - gfx_activate_framebuffer(ibl->framebuffer); - gfx_activate_shader_program(ibl->prefiltered_environment_map_shader); - gfx_set_texture_uniform( - ibl->prefiltered_environment_map_shader, "Sky", environment_map); - const int max_mip = (int)(rlog2(min(width, height))); - for (int mip = 0; mip <= max_mip; ++mip) { - const int mip_width = width >> mip; - const int mip_height = height >> mip; - const float roughness = (float)mip / (float)(max_mip); - gfx_framebuffer_set_viewport(ibl->framebuffer, 0, 0, mip_width, mip_height); - gfx_set_float_uniform( - ibl->prefiltered_environment_map_shader, "Roughness", roughness); - - for (int i = 0; i < 6; ++i) { - if (!gfx_framebuffer_attach_colour( - ibl->framebuffer, &(FrameBufferAttachment){ - .type = FrameBufferCubemapTexture, - .cubemap.face = faces[i], - .cubemap.mip_level = mip, - .cubemap.texture = prefiltered_env_map})) { - goto cleanup; - } - gfx_set_float_uniform( - ibl->prefiltered_environment_map_shader, "Flip", flips[i]); - gfx_set_mat4_uniform( - ibl->prefiltered_environment_map_shader, "CameraRotation", - &ibl->rotations[i]); - gfx_apply_uniforms(ibl->prefiltered_environment_map_shader); - gfx_render_geometry(ibl->quad); - } - } - - *max_mip_level = max_mip; - - success = true; - -cleanup: - gfx_deactivate_shader_program(ibl->prefiltered_environment_map_shader); - gfx_deactivate_framebuffer(ibl->framebuffer); - if (!success && prefiltered_env_map) { - gfx_destroy_texture(gfxcore, &prefiltered_env_map); - return 0; - } else { - return prefiltered_env_map; - } -} diff --git a/gfx/src/util/shader.c b/gfx/src/util/shader.c deleted file mode 100644 index f5c22cc..0000000 --- a/gfx/src/util/shader.c +++ /dev/null @@ -1,136 +0,0 @@ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -static ShaderProgram* make_shader_program( - GfxCore* gfxcore, const char* vert_source, const char* frag_source, - const ShaderCompilerDefine* defines, size_t num_defines) { - assert(gfxcore); - assert(vert_source); - assert(frag_source); - - Shader* vert = 0; - Shader* frag = 0; - - ShaderDesc vertex_shader_desc = { - .code = vert_source, .type = VertexShader, .num_defines = num_defines}; - ShaderDesc fragment_shader_desc = { - .code = frag_source, .type = FragmentShader, .num_defines = num_defines}; - if (num_defines > 0) { - memcpy( - vertex_shader_desc.defines, defines, - num_defines * sizeof(ShaderCompilerDefine)); - memcpy( - fragment_shader_desc.defines, defines, - num_defines * sizeof(ShaderCompilerDefine)); - } - vert = gfx_make_shader(gfxcore, &vertex_shader_desc); - if (!vert) { - goto cleanup; - } - frag = gfx_make_shader(gfxcore, &fragment_shader_desc); - if (!frag) { - goto cleanup; - } - - ShaderProgramDesc shader_program_desc = { - .vertex_shader = vert, .fragment_shader = frag}; - ShaderProgram* prog = gfx_make_shader_program(gfxcore, &shader_program_desc); - if (!prog) { - goto cleanup; - } - return prog; - -cleanup: - if (vert) { - gfx_destroy_shader(gfxcore, &vert); - } - if (frag) { - gfx_destroy_shader(gfxcore, &frag); - } - return 0; -} - -ShaderProgram* gfx_make_brdf_integration_map_shader(GfxCore* gfxcore) { - return make_shader_program( - gfxcore, quad_vert, brdf_integration_map_frag, 0, 0); -} - -ShaderProgram* gfx_make_cook_torrance_shader(GfxCore* gfxcore) { - return make_shader_program( - gfxcore, cook_torrance_vert, cook_torrance_frag, 0, 0); -} - -ShaderProgram* gfx_make_cook_torrance_shader_perm( - GfxCore* gfxcore, const ShaderCompilerDefine* defines, size_t num_defines) { - return make_shader_program( - gfxcore, cook_torrance_vert, cook_torrance_frag, defines, num_defines); -} - -ShaderProgram* gfx_make_immediate_mode_shader(GfxCore* gfxcore) { - return make_shader_program( - gfxcore, immediate_mode_vert, immediate_mode_frag, 0, 0); -} - -ShaderProgram* gfx_make_irradiance_map_shader(GfxCore* gfxcore) { - return make_shader_program( - gfxcore, cubemap_filtering_vert, irradiance_map_frag, 0, 0); -} - -ShaderProgram* gfx_make_prefiltered_environment_map_shader(GfxCore* gfxcore) { - return make_shader_program( - gfxcore, cubemap_filtering_vert, prefiltered_environment_map_frag, 0, 0); -} - -ShaderProgram* gfx_make_debug3d_shader(GfxCore* gfxcore) { - return make_shader_program(gfxcore, debug3d_vert, debug3d_frag, 0, 0); -} - -ShaderProgram* gfx_make_skyquad_shader(GfxCore* gfxcore) { - return make_shader_program(gfxcore, skyquad_vert, skyquad_frag, 0, 0); -} - -ShaderProgram* gfx_make_view_normal_mapped_normals_shader(GfxCore* gfxcore) { - return make_shader_program( - gfxcore, view_normal_mapped_normals_vert, view_normal_mapped_normals_frag, - 0, 0); -} - -ShaderProgram* gfx_make_view_normals_shader(GfxCore* gfxcore) { - return make_shader_program( - gfxcore, view_normals_vert, view_normals_frag, 0, 0); -} - -ShaderProgram* gfx_make_view_tangents_shader(GfxCore* gfxcore) { - return make_shader_program( - gfxcore, view_tangents_vert, view_tangents_frag, 0, 0); -} - -ShaderProgram* gfx_make_view_texture_shader(GfxCore* gfxcore) { - return make_shader_program( - gfxcore, view_texture_vert, view_texture_frag, 0, 0); -} diff --git a/gfx/src/util/skyquad.c b/gfx/src/util/skyquad.c deleted file mode 100644 index 08fa044..0000000 --- a/gfx/src/util/skyquad.c +++ /dev/null @@ -1,161 +0,0 @@ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include - -SceneObject* gfx_make_skyquad(GfxCore* gfxcore, const Texture* texture) { - assert(gfxcore); - assert(texture); - - ShaderProgram* shader = 0; - Geometry* geometry = 0; - Material* material = 0; - Mesh* mesh = 0; - SceneObject* object = 0; - - shader = gfx_make_skyquad_shader(gfxcore); - if (!shader) { - goto cleanup; - } - - geometry = gfx_make_quad_11(gfxcore); - if (!geometry) { - goto cleanup; - } - - MaterialDesc material_desc = (MaterialDesc){0}; - material_desc.uniforms[0] = (ShaderUniform){ - .type = UniformTexture, - .value.texture = texture, - .name = sstring_make("Skyquad")}; - material_desc.num_uniforms = 1; - material = gfx_make_material(&material_desc); - if (!material) { - goto cleanup; - } - - MeshDesc mesh_desc = (MeshDesc){0}; - mesh_desc.geometry = geometry; - mesh_desc.material = material; - mesh_desc.shader = shader; - mesh = gfx_make_mesh(&mesh_desc); - if (!mesh) { - goto cleanup; - } - - object = gfx_make_object(&(ObjectDesc){.num_meshes = 1, .meshes = {mesh}}); - if (!object) { - goto cleanup; - } - - return object; - -cleanup: - if (shader) { - gfx_destroy_shader_program(gfxcore, &shader); - } - if (geometry) { - gfx_destroy_geometry(gfxcore, &geometry); - } - if (material) { - gfx_destroy_material(&material); - } - if (mesh) { - gfx_destroy_mesh(&mesh); - } - if (object) { - gfx_destroy_object(&object); - } - return false; -} - -/// Create an environment light node. -static SceneNode* make_environment_light( - SceneNode* root, const Texture* environment_map) { - assert(root); - assert(environment_map); - - Light* light = 0; - SceneNode* light_node = 0; - - light = gfx_make_light(&(LightDesc){ - .type = EnvironmentLightType, - .light = {(EnvironmentLightDesc){.environment_map = environment_map}}}); - if (!light) { - goto cleanup; - } - - light_node = gfx_make_light_node(light); - if (!light_node) { - goto cleanup; - } - gfx_set_node_parent(light_node, root); - - return light_node; - -cleanup: - if (light) { - gfx_destroy_light(&light); - } - if (light_node) { - gfx_destroy_node(&light_node); - } - return 0; -} - -SceneNode* gfx_setup_skyquad( - GfxCore* gfxcore, SceneNode* root, const Texture* environment_map) { - assert(gfxcore); - assert(root); - assert(environment_map); - - SceneObject* skyquad_object = 0; - SceneNode* object_node = 0; - SceneNode* light_node = 0; - - // Create the skyquad object. - skyquad_object = gfx_make_skyquad(gfxcore, environment_map); - if (!skyquad_object) { - goto cleanup; - } - - // Create an object node to render the skyquad in the background. - object_node = gfx_make_object_node(skyquad_object); - if (!object_node) { - goto cleanup; - } - gfx_set_node_parent(object_node, root); - - // Create an environment light node under which to root objects affected by - // the skyquad. - light_node = make_environment_light(root, environment_map); - if (!light_node) { - goto cleanup; - } - - return light_node; - -cleanup: - if (skyquad_object) { - gfx_destroy_object(&skyquad_object); - } - if (object_node) { - gfx_destroy_node(&object_node); - } - if (light_node) { - gfx_destroy_node(&light_node); - } - return 0; -} diff --git a/include/gfx/asset.h b/include/gfx/asset.h new file mode 100644 index 0000000..caf40c1 --- /dev/null +++ b/include/gfx/asset.h @@ -0,0 +1,99 @@ +/* Asset Management */ +#pragma once + +#include + +#include + +typedef struct Gfx Gfx; +typedef struct Model Model; +typedef struct ShaderProgram ShaderProgram; +typedef struct Texture Texture; + +/// Describes where the asset comes from. +typedef enum AssetOrigin { + AssetFromMemory, + AssetFromFile, +} AssetOrigin; + +/// Describes a texture's colour space. +typedef enum TextureColourSpace { + sRGB, // The most likely default. + LinearColourSpace, +} TextureColourSpace; + +/// Describes a command to load a texture. +typedef struct LoadTextureCmd { + AssetOrigin origin; + enum { LoadTexture, LoadCubemap } type; + TextureColourSpace colour_space; + TextureFiltering filtering; + TextureWrapping wrap; + bool mipmaps; + union { + // A single texture. + struct { + union { + struct { + mstring filepath; + }; + struct { + const void* data; + size_t size_bytes; + }; + }; + } texture; + // Cubemap texture. + struct { + union { + struct { + mstring filepath_pos_x; + mstring filepath_neg_x; + mstring filepath_pos_y; + mstring filepath_neg_y; + mstring filepath_pos_z; + mstring filepath_neg_z; + } filepaths; + struct { + const void* data_pos_x; + const void* data_neg_x; + const void* data_pos_y; + const void* data_neg_y; + const void* data_pos_z; + const void* data_neg_z; + } buffers; + }; + } cubemap; + } data; +} LoadTextureCmd; + +/// Describes a command to load a model. +/// +/// |shader| is an optional shader program assigned to the loaded model objects. +/// If no shader is given, a Cook-Torrance shader based on the object's +/// characteristics (presence of normals, tangents, etc) is assigned. +typedef struct LoadModelCmd { + AssetOrigin origin; + union { + struct { + mstring filepath; + }; + struct { + const void* data; + size_t size_bytes; + }; + }; + ShaderProgram* shader; +} LoadModelCmd; + +/// Load a model. +/// +/// For animated models, this function returns a (shallow) clone of the model +/// that is safe to mutate. For static models, this returns the original model +/// in the cache. +/// +/// Currently only supports the GLTF format. +Model* gfx_load_model(Gfx*, const LoadModelCmd*); + +/// Load a texture. +const Texture* gfx_load_texture(Gfx*, const LoadTextureCmd*); diff --git a/include/gfx/core.h b/include/gfx/core.h new file mode 100644 index 0000000..44509c9 --- /dev/null +++ b/include/gfx/core.h @@ -0,0 +1,501 @@ +/// Render Backend. +/// +/// The Render Backend creates and owns graphics objects and performs low-level +/// rendering operations. +#pragma once + +#include "sizes.h" + +#include +#include +#include +#include + +#include + +#include +#include + +// Implementation objects. +typedef struct Buffer Buffer; +typedef struct FrameBuffer FrameBuffer; +typedef struct Geometry Geometry; +typedef struct GfxCore GfxCore; +typedef struct RenderBuffer RenderBuffer; +typedef struct Shader Shader; +typedef struct ShaderProgram ShaderProgram; +typedef struct Texture Texture; + +/// Data type for vertex indices. +/// Might need U32 for bigger models. +typedef uint8_t VertexIndex8; +typedef uint16_t VertexIndex16; +typedef uint16_t VertexCount; + +/// Geometry drawing modes. +typedef enum PrimitiveType { + Triangles, + TriangleFan, + TriangleStrip +} PrimitiveType; + +/// Buffer usage. +typedef enum BufferUsage { BufferStatic, BufferDynamic } BufferUsage; + +/// Buffer type. +typedef enum BufferType { + BufferUntyped, + Buffer2d, + Buffer3d, + Buffer4d, + BufferFloat, + BufferU8, + BufferU16 +} BufferType; + +/// Buffer data descriptor. +typedef struct BufferDataDesc { + union { + const void* data; + const vec2* vec2s; + const vec3* vec3s; + const float* floats; + const uint8_t* u8s; + const uint16_t* u16s; + }; + size_t count; +} BufferDataDesc; + +/// Buffer descriptor. +/// +/// 'count' is the number of elements in the array. For untyped buffers, this is +/// the size in bytes of the 'data' array. For other types, it is the number of +/// vec2s, vec3s, etc. in the corresponding array. +/// +/// The data pointers can also be null. In such a case, a buffer of the given +/// size is created with its contents uninitialized. +/// +/// TODO: Think about typed buffers (Buffer, Buffer2d, Buffer3d, BufferU8, etc). +/// Typed buffers don't work well with interleaved vertex attributes. Not sure +/// this is really worth it. +typedef struct BufferDesc { + BufferUsage usage; + BufferType type; + BufferDataDesc data; +} BufferDesc; + +/// A buffer view for vertex data (attributes or indices). +/// Either 'data' or 'buffer' must be set. +#define MAKE_BUFFER_VIEW(NAME, TYPE) \ + typedef struct NAME { \ + const TYPE* data; \ + Buffer* buffer; \ + size_t offset_bytes; \ + size_t size_bytes; \ + size_t stride_bytes; \ + } NAME; + +/// A buffer view for untyped data. +MAKE_BUFFER_VIEW(BufferView, void) + +/// A buffer view for 2D vectors. +MAKE_BUFFER_VIEW(BufferView2d, vec2) + +/// A buffer view for 3D vectors. +MAKE_BUFFER_VIEW(BufferView3d, vec3) + +/// A buffer view for 4D vectors. +MAKE_BUFFER_VIEW(BufferView4d, vec4) + +/// A buffer view for floats. +MAKE_BUFFER_VIEW(BufferViewFloat, float) + +/// A buffer view for 8-bit unsigned integers. +MAKE_BUFFER_VIEW(BufferViewU8, uint8_t) + +/// A buffer view for 16-bit unsigned integers. +MAKE_BUFFER_VIEW(BufferViewU16, uint16_t) + +/// A buffer view for 8-bit vertex indices. +MAKE_BUFFER_VIEW(BufferViewIdx8, uint16_t) + +/// A buffer view for 16-bit vertex indices. +MAKE_BUFFER_VIEW(BufferViewIdx16, uint16_t) + +/// Describes a piece of geometry. +/// +/// Buffer views may point to either already-existing GPU buffers or to data in +/// host memory. +/// +/// If the buffer views do not already point to GPU buffers, GPU buffers are +/// created for the geometry. The 'buffer_usage' field specifies the usage for +/// the created buffers. Use BufferStatic for static geometry and BufferDynamic +/// for dynamic geometry. +/// +/// Currently we support only up to 16-bit vertex indices. Might have to change +/// this to support a larger variety of 3D models. +typedef struct GeometryDesc { + BufferView2d positions2d; + BufferView3d positions3d; + BufferView3d normals; + BufferView4d tangents; + BufferView2d texcoords; + struct { + BufferViewU8 u8; + BufferViewU16 u16; + } joints; // uvec4. + struct { + BufferViewFloat floats; + BufferViewU8 u8; + BufferViewU16 u16; + } weights; // vec4 or uvec4. + BufferViewIdx8 indices8; + BufferViewIdx16 indices16; + VertexCount num_verts; + size_t num_indices; + PrimitiveType type; + BufferUsage buffer_usage; + aabb3 aabb; +} GeometryDesc; + +/// Shader compiler define. +typedef struct ShaderCompilerDefine { + sstring name; + sstring value; +} ShaderCompilerDefine; + +/// Shader types. +typedef enum { VertexShader, FragmentShader } ShaderType; + +/// Describes a shader. +typedef struct ShaderDesc { + ShaderType type; + const char* code; + ShaderCompilerDefine defines[GFX_MAX_SHADER_COMPILER_DEFINES]; + size_t num_defines; +} ShaderDesc; + +/// Describes a shader program. +typedef struct ShaderProgramDesc { + const Shader* vertex_shader; + const Shader* fragment_shader; +} ShaderProgramDesc; + +/// Shader uniform type. +typedef enum { + UniformFloat, + UniformMat4, + UniformTexture, + UniformVec3, + UniformVec4, + UniformMat4Array +} UniformType; + +/// Shader uniform. +/// +/// For uniform arrays, the client must ensure that the array is still valid by +/// the time the uniform data is passed to the GPU. +typedef struct ShaderUniform { + sstring name; + UniformType type; + union { + const Texture* texture; + mat4 mat4; + vec3 vec3; + vec4 vec4; + float scalar; + struct { + size_t count; + union { + const mat4* values; + }; + } array; + } value; +} ShaderUniform; + +/// Texture dimension. +typedef enum { Texture2D, TextureCubeMap } TextureDimension; + +/// Texture data format. +typedef enum { + TextureDepth, + TextureRG16, + TextureRG16F, + TextureRGB8, + TextureR11G11B10F, + TextureRGBA8, + TextureSRGB8, + TextureSRGBA8 +} TextureFormat; + +/// Texture filtering. +typedef enum { NearestFiltering, LinearFiltering } TextureFiltering; + +/// Texture wrap mode. +typedef enum { Repeat, ClampToEdge } TextureWrapping; + +/// Cubemap faces. +typedef enum { + CubemapFacePosX, + CubemapFaceNegX, + CubemapFacePosY, + CubemapFaceNegY, + CubemapFacePosZ, + CubemapFaceNegZ +} CubemapFace; + +/// Texture data descriptor. +typedef struct TextureDataDesc { + union { + const void* pixels; + struct { + const void* pixels_pos_x; + const void* pixels_neg_x; + const void* pixels_pos_y; + const void* pixels_neg_y; + const void* pixels_pos_z; + const void* pixels_neg_z; + } cubemap; + }; +} TextureDataDesc; + +/// Describes a texture. +typedef struct TextureDesc { + int width; + int height; + int depth; // Not used until 3D textures are exposed. + TextureDimension dimension; + TextureFormat format; + TextureFiltering filtering; + TextureWrapping wrap; + bool mipmaps; + TextureDataDesc data; +} TextureDesc; + +/// Describes a renderbuffer. +typedef struct RenderBufferDesc { + int width; + int height; + TextureFormat texture_format; +} RenderBufferDesc; + +/// Framebuffer attachment type. +typedef enum FrameBufferAttachmentType { + FrameBufferNoAttachment, + FrameBufferTexture, + FrameBufferCubemapTexture, + FrameBufferRenderBuffer +} FrameBufferAttachmentType; + +/// Describes a framebuffer attachment. +typedef struct FrameBufferAttachment { + FrameBufferAttachmentType type; + union { + struct { + Texture* texture; + int mip_level; + } texture; + struct { + Texture* texture; + int mip_level; + CubemapFace face; + } cubemap; + RenderBuffer* renderbuffer; + }; +} FrameBufferAttachment; + +/// Describes a framebuffer. +typedef struct FrameBufferDesc { + FrameBufferAttachment colour; + FrameBufferAttachment depth; +} FrameBufferDesc; + +// ----------------------------------------------------------------------------- +// Render commands. +// ----------------------------------------------------------------------------- + +/// Start a new frame. +void gfx_start_frame(GfxCore*); + +/// End a frame. +void gfx_end_frame(GfxCore*); + +/// Set the render backend's viewport dimensions. +void gfx_set_viewport(GfxCore*, int x, int y, int width, int height); + +/// Get the render backend's viewport dimensions. +void gfx_get_viewport(GfxCore*, int* x, int* y, int* width, int* height); + +/// Clear the viewport. +void gfx_clear(GfxCore*, vec4 colour); + +/// Set blending state. +void gfx_set_blending(GfxCore*, bool enable); + +/// Set depth mask. +void gfx_set_depth_mask(GfxCore*, bool enable); + +/// Set cull mode. +void gfx_set_culling(GfxCore*, bool enable); + +/// Set polygon offset. +void gfx_set_polygon_offset(GfxCore*, float scale, float bias); + +/// Reset the polygon offset. +void gfx_reset_polygon_offset(GfxCore*); + +// ----------------------------------------------------------------------------- +// Buffers. +// ----------------------------------------------------------------------------- + +/// Create a buffer from raw data. +Buffer* gfx_make_buffer(GfxCore*, const BufferDesc*); + +/// Destroy the buffer. +void gfx_destroy_buffer(GfxCore*, Buffer**); + +/// Update the buffer's data. +void gfx_update_buffer(Buffer*, const BufferDataDesc*); + +// ----------------------------------------------------------------------------- +// Geometry. +// ----------------------------------------------------------------------------- + +/// Create geometry. +Geometry* gfx_make_geometry(GfxCore*, const GeometryDesc*); + +/// Destroy the geometry. +void gfx_destroy_geometry(GfxCore*, Geometry**); + +/// Upload new vertex data for the geometry. +/// +/// This is similar to gfx_make_geometry(), but the geometry need not be +/// entirely specified. +/// +/// Only the vertex attributes, vertex count, and index count set in the +/// descriptor are updated. Index data, primitive type, and other properties of +/// the geometry are not updated. +/// +/// New data must be given as arrays in host memory. That is, the buffer views +/// in the descriptor must point to CPU arrays, not GPU buffers. +/// +/// Note that the descriptor cannot specify a larger vertex or index count than +/// what the geometry was created with. If the geometry size or any other +/// attribute not handled by this update function needs to be changed, then a +/// new geometry must be created. +void gfx_update_geometry(Geometry*, const GeometryDesc*); + +/// Render the geometry. +void gfx_render_geometry(const Geometry*); + +/// Return the geometry's bounding box. +aabb3 gfx_get_geometry_aabb(const Geometry*); + +// ----------------------------------------------------------------------------- +// Textures. +// ----------------------------------------------------------------------------- + +/// Create a texture. +Texture* gfx_make_texture(GfxCore*, const TextureDesc*); + +/// Destroy the texture. +void gfx_destroy_texture(GfxCore*, Texture**); + +/// Update the texture. +void gfx_update_texture(Texture*, const TextureDataDesc*); + +// ----------------------------------------------------------------------------- +// Renderbuffers. +// ----------------------------------------------------------------------------- + +/// Create a renderbuffer. +RenderBuffer* gfx_make_renderbuffer(GfxCore*, const RenderBufferDesc*); + +/// Destroy the renderbuffer. +void gfx_destroy_renderbuffer(GfxCore*, RenderBuffer**); + +// ----------------------------------------------------------------------------- +// Framebuffers. +// ----------------------------------------------------------------------------- + +/// Create a framebuffer. +FrameBuffer* gfx_make_framebuffer(GfxCore*, const FrameBufferDesc*); + +/// Destroy the framebuffer. +void gfx_destroy_framebuffer(GfxCore*, FrameBuffer**); + +/// Attach a colour buffer to the framebuffer. +bool gfx_framebuffer_attach_colour(FrameBuffer*, const FrameBufferAttachment*); + +/// Attach a depth buffer to the framebuffer. +bool gfx_framebuffer_attach_depth(FrameBuffer*, const FrameBufferAttachment*); + +/// Activate the framebuffer. +/// Subsequent draw calls write to this framebuffer. +void gfx_activate_framebuffer(const FrameBuffer*); + +/// Deactivate the framebuffer. +/// Subsequent draw calls write to the default framebuffer. +void gfx_deactivate_framebuffer(const FrameBuffer*); + +/// Set the framebuffer's viewport. +/// This function should be called every time the framebuffer is activated. +void gfx_framebuffer_set_viewport( + FrameBuffer*, int x, int y, int width, int height); + +// ----------------------------------------------------------------------------- +// Shaders. +// ----------------------------------------------------------------------------- + +/// Create a shader. +Shader* gfx_make_shader(GfxCore*, const ShaderDesc*); + +/// Destroy the shader. +void gfx_destroy_shader(GfxCore*, Shader**); + +/// Create a shader program. +ShaderProgram* gfx_make_shader_program(GfxCore*, const ShaderProgramDesc*); + +/// Destroy the shader program. +void gfx_destroy_shader_program(GfxCore*, ShaderProgram**); + +/// Activate the shader program. +void gfx_activate_shader_program(const ShaderProgram*); + +/// Deactivate the shader program. +void gfx_deactivate_shader_program(const ShaderProgram*); + +/// Apply the shader program's uniform variables. +/// +/// Calls to gfx_set_XYZ_uniform save the values of the uniform variables in the +/// graphics library. By calling this function, those values are passed on to +/// the graphics driver for rendering. +/// +/// This function should be called after setting all of the uniform variables +/// and prior to issuing a draw call. +void gfx_apply_uniforms(const ShaderProgram*); + +/// Set the texture uniform. +/// Has no effect if the shader does not contain the given uniform. +void gfx_set_texture_uniform(ShaderProgram*, const char* name, const Texture*); + +/// Set the matrix uniform. +/// Has no effect if the shader does not contain the given uniform. +void gfx_set_mat4_uniform(ShaderProgram*, const char* name, const mat4*); + +/// Set the vec3 uniform. +/// Has no effect if the shader does not contain the given uniform. +void gfx_set_vec3_uniform(ShaderProgram*, const char* name, vec3); + +/// Set the vec4 uniform. +/// Has no effect if the shader does not contain the given uniform. +void gfx_set_vec4_uniform(ShaderProgram*, const char* name, vec4); + +/// Set the float uniform. +/// Has no effect if the shader does not contain the given uniform. +void gfx_set_float_uniform(ShaderProgram*, const char* name, float value); + +/// Set the matrix array uniform. +/// Has no effect if the shader does not contain the given uniform. +void gfx_set_mat4_array_uniform( + ShaderProgram*, const char* name, const mat4*, size_t count); diff --git a/include/gfx/gfx.h b/include/gfx/gfx.h new file mode 100644 index 0000000..7c670a5 --- /dev/null +++ b/include/gfx/gfx.h @@ -0,0 +1,31 @@ +#pragma once + +typedef struct AssetCache AssetCache; +typedef struct GfxCore GfxCore; +typedef struct ImmRenderer ImmRenderer; +typedef struct Renderer Renderer; + +typedef struct Gfx Gfx; + +/// Create a new graphics system, +Gfx* gfx_init(void); + +/// Destroy the graphics system. +void gfx_destroy(Gfx**); + +/// Get the render backend. +GfxCore* gfx_get_core(Gfx*); + +/// Get the renderer. +Renderer* gfx_get_renderer(Gfx*); + +/// Get the immediate mode renderer. +ImmRenderer* gfx_get_imm_renderer(Gfx*); + +/// Get the asset cache. +AssetCache* gfx_get_asset_cache(Gfx*); + +/// Remove unused resources from the scene (meshes, materials). +/// TODO: need to think about the interface for scene_purge(). Maybe this +/// should be gfx_purge() and take a list of Scenes? +// void gfx_purge(Scene*); diff --git a/include/gfx/renderer.h b/include/gfx/renderer.h new file mode 100644 index 0000000..2a4ada1 --- /dev/null +++ b/include/gfx/renderer.h @@ -0,0 +1,104 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +typedef struct GfxCore GfxCore; +typedef struct Scene Scene; +typedef struct SceneCamera SceneCamera; + +typedef struct ImmRenderer ImmRenderer; +typedef struct Renderer Renderer; + +// ----------------------------------------------------------------------------- +// Main Renderer. +// ----------------------------------------------------------------------------- + +typedef enum RenderSceneMode { + RenderDefault, + RenderDebug, + RenderNormals, + RenderNormalMappedNormals, + RenderTangents +} RenderSceneMode; + +typedef struct RenderSceneParams { + RenderSceneMode mode; + const Scene* scene; + const SceneCamera* camera; +} RenderSceneParams; + +/// Render the scene. +void gfx_render_scene(Renderer*, const RenderSceneParams*); + +/// Update the scene. +void gfx_update(Scene*, const SceneCamera*, R t); + +// ----------------------------------------------------------------------------- +// Immediate Mode Renderer. +// ----------------------------------------------------------------------------- + +/// Prepare the graphics systems for immediate-mode rendering. +/// +/// Call this before issuing any immediate-mode rendering draws. +void gfx_imm_start(ImmRenderer*); + +/// End immediate mode rendering. +/// +/// Call this after issuing immediate-mode rendering draws and before swapping +/// buffers. +void gfx_imm_end(ImmRenderer*); + +/// Draw a set of triangles. +void gfx_imm_draw_triangles(ImmRenderer*, const vec3[], size_t num_triangles); + +/// Draw a triangle. +void gfx_imm_draw_triangle(ImmRenderer*, const vec3[3]); + +/// Draw a bounding box. +void gfx_imm_draw_aabb2(ImmRenderer*, aabb2); + +/// Draw a bounding box. +void gfx_imm_draw_aabb3(ImmRenderer*, aabb3); + +/// Draw a box. +/// +/// The vertices must be given in the following order: +/// +/// 7 ----- 6 +/// / /| +/// 3 ----- 2 | +/// | | | +/// | 4 ----- 5 +/// |/ |/ +/// 0 ----- 1 +void gfx_imm_draw_box3(ImmRenderer* renderer, const vec3 vertices[8]); + +/// Set the camera. +void gfx_imm_set_camera(ImmRenderer*, const Camera*); + +/// Load an identity model matrix. Clears the matrix stack. +void gfx_imm_load_identity(ImmRenderer* renderer); + +/// Push the given matrix to the matrix stack. +void gfx_imm_push_matrix(ImmRenderer* renderer, const mat4* matrix); + +/// Pop the top of the matrix stack. +void gfx_imm_pop_matrix(ImmRenderer* renderer); + +/// Push a translation matrix to the matrix stack. +void gfx_imm_translate(ImmRenderer* renderer, vec3 offset); + +/// Set the model matrix. Clears the matrix stack. +void gfx_imm_set_model_matrix(ImmRenderer*, const mat4*); + +/// Set the view-projection matrix. +void gfx_imm_set_view_projection_matrix(ImmRenderer*, const mat4*); + +/// Set the render colour. +void gfx_imm_set_colour(ImmRenderer*, vec4 colour); diff --git a/include/gfx/scene.h b/include/gfx/scene.h new file mode 100644 index 0000000..abcaa70 --- /dev/null +++ b/include/gfx/scene.h @@ -0,0 +1,11 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include diff --git a/include/gfx/scene/animation.h b/include/gfx/scene/animation.h new file mode 100644 index 0000000..d95b895 --- /dev/null +++ b/include/gfx/scene/animation.h @@ -0,0 +1,142 @@ +#pragma once + +#include "node.h" +#include "object.h" +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +typedef struct Buffer Buffer; +typedef struct SceneNode SceneNode; + +typedef struct Anima Anima; +typedef struct Joint Joint; +typedef struct Skeleton Skeleton; + +/// Index type used to store relative indices into arrays. +typedef uint16_t joint_idx; + +/// Index value denoting no index. +static const joint_idx INDEX_NONE = (joint_idx)-1; + +typedef struct Box { + vec3 vertices[8]; +} Box; + +/// Joint descriptor. +typedef struct JointDesc { + joint_idx parent; /// Parent Joint; index into Anima's joints. + mat4 inv_bind_matrix; /// Transforms the mesh into the joint's local space. + aabb3 box; /// Bounding box. +} JointDesc; + +/// Skeleton descriptor. +typedef struct SkeletonDesc { + size_t num_joints; + joint_idx joints[GFX_MAX_NUM_JOINTS]; /// Indices into Anima's joints array. +} SkeletonDesc; + +/// Animation interpolation mode. +typedef enum AnimationInterpolation { + StepInterpolation, + LinearInterpolation, + CubicSplineInterpolation +} AnimationInterpolation; + +/// The kind of transformation applied by a Channel. +typedef enum ChannelType { + RotationChannel, + ScaleChannel, + TranslationChannel, + WeightsChannel +} ChannelType; + +/// Animation keyframe descriptor. +/// +/// The arrays should have as many entries as 'num_joints' in the SkeletonDesc. +typedef struct KeyframeDesc { + R time; // Start time in [0, end animation time] + union { + vec3 translation; + quat rotation; + }; +} KeyframeDesc; + +/// Animation channel descriptor. +typedef struct ChannelDesc { + joint_idx target; /// Index into Anima's joints array. + ChannelType type; + AnimationInterpolation interpolation; + size_t num_keyframes; + KeyframeDesc keyframes[GFX_MAX_NUM_KEYFRAMES]; +} ChannelDesc; + +/// Animation descriptor. +typedef struct AnimationDesc { + // TODO: Store a name hash for faster comparisons. + sstring name; // Animation name. Required for playback. + size_t num_channels; // Number of channels. + ChannelDesc channels[GFX_MAX_NUM_CHANNELS]; +} AnimationDesc; + +/// Anima object descriptor. +/// +/// The last joint of the joints array at index 'num_joints - 1' must be the +/// root of all skeletons; specifically, the root of all joints that otherwise +/// would have no parent (a skeleton need not have its own root and can be a set +/// of disjoint node hierarchies). +typedef struct AnimaDesc { + size_t num_skeletons; + size_t num_animations; + size_t num_joints; + SkeletonDesc skeletons[GFX_MAX_NUM_SKELETONS]; + AnimationDesc animations[GFX_MAX_NUM_ANIMATIONS]; + JointDesc joints[GFX_MAX_NUM_JOINTS]; +} AnimaDesc; + +/// Animation play settings. +typedef struct AnimationPlaySettings { + const char* name; // Animation name. + bool loop; // Whether to loop the animation or just play once. + // TODO: Add animation speed. +} AnimationPlaySettings; + +/// Create an anima object. +Anima* gfx_make_anima(const AnimaDesc*); + +/// Destroy the anima. +void gfx_destroy_anima(Anima**); + +/// Play an animation (sets the current animation). +bool gfx_play_animation(Anima*, const AnimationPlaySettings*); + +/// Update the current animation. +void gfx_update_animation(Anima*, R t); + +/// Stop the current animation. +void gfx_stop_animation(Anima*); + +/// Return the anima's ith skeleton. +const Skeleton* gfx_get_anima_skeleton(const Anima* anima, size_t i); + +/// Return the number of joints in the skeleton. +size_t gfx_get_skeleton_num_joints(const Skeleton*); + +/// Return true if the skeleton's ith joint has a bounding box. +/// +/// IK joints that do not directly transform vertices have no bounding box. +bool gfx_joint_has_box(const Anima*, const Skeleton*, size_t joint); + +/// Return the bounding box of the skeleton's ith joint. +/// +/// IK joints that do not directly transform vertices have no box. +Box gfx_get_joint_box(const Anima*, const Skeleton*, size_t joint); diff --git a/include/gfx/scene/camera.h b/include/gfx/scene/camera.h new file mode 100644 index 0000000..99d83fe --- /dev/null +++ b/include/gfx/scene/camera.h @@ -0,0 +1,22 @@ +#pragma once + +#include + +typedef struct SceneNode SceneNode; + +typedef struct SceneCamera SceneCamera; + +/// Create a new camera. +SceneCamera* gfx_make_camera(); + +/// Destroy the camera. +/// +/// The camera is conveniently removed from the scene graph and its parent scene +/// node is destroyed. +void gfx_destroy_camera(SceneCamera**); + +/// Set the scene camera's math camera. +void gfx_set_camera_camera(SceneCamera* scene_camera, Camera* camera); + +/// Get the scene camera's math camera. +Camera* gfx_get_camera_camera(SceneCamera*); diff --git a/include/gfx/scene/light.h b/include/gfx/scene/light.h new file mode 100644 index 0000000..132e344 --- /dev/null +++ b/include/gfx/scene/light.h @@ -0,0 +1,30 @@ +#pragma once + +typedef struct Texture Texture; + +typedef struct Light Light; + +/// Light type. +typedef enum LightType { EnvironmentLightType } LightType; + +/// Describes an environment light. +typedef struct EnvironmentLightDesc { + const Texture* environment_map; +} EnvironmentLightDesc; + +/// Describes a light. +typedef struct LightDesc { + LightType type; + union { + EnvironmentLightDesc environment; + } light; +} LightDesc; + +/// Create a light. +Light* gfx_make_light(const LightDesc*); + +/// Destroy the light. +/// +/// The light is conveniently removed from the scene graph and its parent scene +/// node is destroyed. +void gfx_destroy_light(Light**); diff --git a/include/gfx/scene/material.h b/include/gfx/scene/material.h new file mode 100644 index 0000000..bca664e --- /dev/null +++ b/include/gfx/scene/material.h @@ -0,0 +1,25 @@ +#pragma once + +#include +#include + +typedef struct Material Material; + +/// Describes a material. +/// +/// A material holds a shader program and a set of shader-specific uniform +/// variables. Two materials can share the same shader, but shader parameters +/// generally give two materials a different appearance. +typedef struct MaterialDesc { + ShaderUniform uniforms[GFX_MAX_UNIFORMS_PER_MATERIAL]; + int num_uniforms; +} MaterialDesc; + +/// Create a material. +Material* gfx_make_material(const MaterialDesc*); + +/// Destroy the material. +/// +/// The caller must make sure that no Mesh points to the given Material. +/// For a safe purge of unused resources, see scene_purge(). +void gfx_destroy_material(Material**); diff --git a/include/gfx/scene/mesh.h b/include/gfx/scene/mesh.h new file mode 100644 index 0000000..0d3b4d4 --- /dev/null +++ b/include/gfx/scene/mesh.h @@ -0,0 +1,23 @@ +#pragma once + +typedef struct Geometry Geometry; +typedef struct Material Material; +typedef struct ShaderProgram ShaderProgram; + +typedef struct Mesh Mesh; + +/// Describes a mesh. +typedef struct MeshDesc { + const Geometry* geometry; + const Material* material; + ShaderProgram* shader; +} MeshDesc; + +/// Create a mesh. +Mesh* gfx_make_mesh(const MeshDesc*); + +/// Destroy the mesh. +/// +/// The caller must make sure that no SceneObject points to the given Mesh. +/// For a safe purge of unused resources, see scene_purge(). +void gfx_destroy_mesh(Mesh**); diff --git a/include/gfx/scene/model.h b/include/gfx/scene/model.h new file mode 100644 index 0000000..42f85d4 --- /dev/null +++ b/include/gfx/scene/model.h @@ -0,0 +1,12 @@ +#pragma once + +typedef struct Anima Anima; +typedef struct Model Model; +typedef struct SceneNode SceneNode; + +/// Return the model's anima, or null if the model is not animated. +Anima* gfx_get_model_anima(Model*); + +/// Return the model's root node. +const SceneNode* gfx_get_model_root(const Model*); +SceneNode* gfx_get_model_root_mut(Model*); diff --git a/include/gfx/scene/node.h b/include/gfx/scene/node.h new file mode 100644 index 0000000..a2c2836 --- /dev/null +++ b/include/gfx/scene/node.h @@ -0,0 +1,156 @@ +#pragma once + +#include "animation.h" + +#include +#include + +#include + +typedef struct Anima Anima; +typedef struct Light Light; +typedef struct Model Model; +typedef struct SceneCamera SceneCamera; +typedef struct SceneObject SceneObject; + +/// Scene node type. +typedef enum NodeType { + LogicalNode, + AnimaNode, + CameraNode, + LightNode, + ModelNode, + ObjectNode, +} NodeType; + +/// A node in the scene graph. +/// +/// Scene nodes take ownership of the object they are associated with (Camera, +/// Light, SceneObject, etc), as well as of child nodes. +typedef struct SceneNode SceneNode; + +// ----------------------------------------------------------------------------- +// Constructors and destructor. +// ----------------------------------------------------------------------------- + +/// Create a new scene node. +/// +/// This node does not contain any camera, light, object, etc. and exists simply +/// as a logical and spatial construct. +SceneNode* gfx_make_node(); + +/// Create an anima node. +SceneNode* gfx_make_anima_node(Anima*); + +/// Create a new camera node. +SceneNode* gfx_make_camera_node(SceneCamera*); + +/// Create a new light node. +SceneNode* gfx_make_light_node(Light*); + +/// Create a new model node. +SceneNode* gfx_make_model_node(Model*); + +/// Create a new object node. +SceneNode* gfx_make_object_node(SceneObject*); + +/// Make the node an anima node. +void gfx_construct_anima_node(SceneNode*, Anima*); + +/// Make the node a camera node. +void gfx_construct_camera_node(SceneNode*, SceneCamera*); + +/// Make the node a light node. +void gfx_construct_light_node(SceneNode*, Light*); + +/// Make the node a model node. +void gfx_construct_model_node(SceneNode*, Model*); + +/// Make the node an object node. +void gfx_construct_object_node(SceneNode*, SceneObject*); + +/// Recursively destroy the scene node and its children. +/// +/// The scene node and its children are removed from the scene graph. +/// +/// Node resources -- cameras, lights, objects, etc. -- are also destroyed. +void gfx_destroy_node(SceneNode**); + +// ----------------------------------------------------------------------------- +// Getters. +// ----------------------------------------------------------------------------- + +/// Get the node's type. +NodeType gfx_get_node_type(const SceneNode*); + +/// Get the node's anima. +/// +/// The node must be of type AnimaNode. +const Anima* gfx_get_node_anima(const SceneNode*); +Anima* gfx_get_node_anima_mut(SceneNode*); + +/// Get the node's camera. +/// +/// The node must be of type CameraNode. +const SceneCamera* gfx_get_node_camera(const SceneNode* node); +SceneCamera* gfx_get_node_camera_mut(SceneNode* node); + +/// Get the node's light. +/// +/// The node must be of type LightNode. +const Light* gfx_get_node_light(const SceneNode*); +Light* gfx_get_node_light_mut(SceneNode*); + +/// Get the node's model. +/// +/// The node must be of type ModelNode. +const Model* gfx_get_node_model(const SceneNode*); +Model* gfx_get_node_model_mut(SceneNode*); + +/// Get the node's scene object. +/// +/// The node must be of type ObjectNode. +const SceneObject* gfx_get_node_object(const SceneNode*); +SceneObject* gfx_get_node_object_mut(SceneNode*); + +/// Get the node's parent. +const SceneNode* gfx_get_node_parent(const SceneNode*); +SceneNode* gfx_get_node_parent_mut(SceneNode*); + +/// Get the node's first child. +const SceneNode* gfx_get_node_child(const SceneNode*); +SceneNode* gfx_get_node_child_mut(SceneNode*); + +/// Get the node's immediate sibling. +const SceneNode* gfx_get_node_sibling(const SceneNode*); +SceneNode* gfx_get_node_sibling_mut(SceneNode*); + +/// Get the node's (local) transform. +mat4 gfx_get_node_transform(const SceneNode*); + +/// Get the node's global transform. +mat4 gfx_get_node_global_transform(const SceneNode*); + +// ----------------------------------------------------------------------------- +// Setters. +// ----------------------------------------------------------------------------- + +/// Set the node's parent. +/// +/// Pass in null to unwire from the existing parent, if one exists. +void gfx_set_node_parent(SceneNode*, SceneNode* parent_node); + +/// Set the node's (local) transform. +void gfx_set_node_transform(SceneNode*, const mat4* transform); + +/// Set the node's position. +void gfx_set_node_position(SceneNode*, const vec3* position); + +/// Set the node's rotation. +void gfx_set_node_rotation(SceneNode*, const quat* rotation); + +/// Set the node's rotation. +void gfx_set_node_rotation_mat(SceneNode*, const mat4* rotation); + +/// Log the node's hierarchy. +void gfx_log_node_hierarchy(const SceneNode*); diff --git a/include/gfx/scene/object.h b/include/gfx/scene/object.h new file mode 100644 index 0000000..7579d29 --- /dev/null +++ b/include/gfx/scene/object.h @@ -0,0 +1,39 @@ +#pragma once + +#include + +#include + +#include + +typedef struct Mesh Mesh; +typedef struct SceneNode SceneNode; +typedef struct Skeleton Skeleton; + +typedef struct SceneObject SceneObject; + +typedef struct ObjectDesc { + size_t num_meshes; + Mesh* meshes[GFX_MAX_NUM_MESHES]; +} ObjectDesc; + +/// Create a new object. +SceneObject* gfx_make_object(const ObjectDesc*); + +/// Destroy the object. +/// +/// The object is conveniently removed from the scene graph and its parent scene +/// node is destroyed. +void gfx_destroy_object(SceneObject**); + +/// Set the object's skeleton. +void gfx_set_object_skeleton(SceneObject*, const Skeleton*); + +/// Get the object's skeleton. +/// Return null if the object has no skeleton. +const Skeleton* gfx_get_object_skeleton(const SceneObject*); + +/// Gets the object's bounding box. +/// +/// The object's bounding box is the bounding box of its mesh geometries. +aabb3 gfx_get_object_aabb(const SceneObject*); diff --git a/include/gfx/scene/scene.h b/include/gfx/scene/scene.h new file mode 100644 index 0000000..0d96210 --- /dev/null +++ b/include/gfx/scene/scene.h @@ -0,0 +1,21 @@ +#pragma once + +#include +#include + +typedef struct SceneNode SceneNode; + +typedef struct Scene Scene; + +/// Create a new scene. +Scene* gfx_make_scene(void); + +/// Destroy the scene. +/// +/// This function destroys the scene and all objects that it owns (scene +/// objects, cameras, lights, etc), but not objects that could be shared with +/// other scenes (meshes, materials, etc). +void gfx_destroy_scene(Scene**); + +/// Get the scene's root node. +SceneNode* gfx_get_scene_root(Scene*); diff --git a/include/gfx/sizes.h b/include/gfx/sizes.h new file mode 100644 index 0000000..076113c --- /dev/null +++ b/include/gfx/sizes.h @@ -0,0 +1,95 @@ +/// Size constants used throughout the library. +#pragma once + +// Scene. + +/// Maximum number of cameras per scene. +#define GFX_MAX_NUM_CAMERAS 16 + +/// Maximum number of lights. +#define GFX_MAX_NUM_LIGHTS 1024 + +/// Maximum number of materials. +#define GFX_MAX_NUM_MATERIALS 1024 + +/// Maximum number of meshes. +#define GFX_MAX_NUM_MESHES 1024 + +/// Maximum number of mesh links. +#define GFX_MAX_NUM_MESH_LINKS 1024 + +/// Maximum number of models. +#define GFX_MAX_NUM_MODELS 64 + +/// Maximum number of joints per skeleton. +#define GFX_MAX_NUM_JOINTS 96 + +/// Maximum number of keyframes per channel. +#define GFX_MAX_NUM_KEYFRAMES 32 + +/// Maximum number of channels per animation. +#define GFX_MAX_NUM_CHANNELS 128 + +/// Maximum number of skeletons. +#define GFX_MAX_NUM_SKELETONS 128 + +/// Maximum number of animations. +#define GFX_MAX_NUM_ANIMATIONS 128 + +/// Maximum number of animas. +#define GFX_MAX_NUM_ANIMAS 128 + +/// Maximum number of nodes per scene. +#define GFX_MAX_NUM_NODES 1024 + +/// Maximum number of objects per scene. +#define GFX_MAX_NUM_OBJECTS 1024 + +/// Maximum number of uniforms in a Material. +#define GFX_MAX_UNIFORMS_PER_MATERIAL 18 + +// Render. + +/// Maximum number of buffers per renderer. +#define GFX_MAX_NUM_BUFFERS 1024 + +/// Maximum number of framebuffers per renderer. +#define GFX_MAX_NUM_FRAMEBUFFERS 32 + +/// Maximum number of geometries per renderer. +#define GFX_MAX_NUM_GEOMETRIES 1024 + +/// Maximum number of renderbuffers per renderer. +#define GFX_MAX_NUM_RENDERBUFFERS (GFX_MAX_NUM_FRAMEBUFFERS * 2) + +/// Maximum number of shader programs per renderer. +#define GFX_MAX_NUM_SHADER_PROGRAMS 128 + +/// Maximum number of shaders per renderer. +#define GFX_MAX_NUM_SHADERS (GFX_MAX_NUM_SHADER_PROGRAMS * 2) + +/// Maximum number of textures per renderer. +#define GFX_MAX_NUM_TEXTURES 1024 + +/// Maximum number of uniforms in a ShaderProgram. +#define GFX_MAX_UNIFORMS_PER_SHADER (GFX_MAX_UNIFORMS_PER_MATERIAL + 8) + +/// Maximum number of compiler defines in a Shader. +#define GFX_MAX_SHADER_COMPILER_DEFINES 16 + +// Renderer. + +/// Maximum number of triangles that the immediate-mode renderer can draw in a +/// frame. +#define IMM_MAX_NUM_TRIANGLES 1024 + +/// Maximum number of matrices in the immediate-mode renderer's matrix stack. +#define IMM_MAX_NUM_MATRICES 32 + +// Asset Manager. + +#define GFX_MAX_NUM_ASSETS 1024 + +// Gfx. + +#define GFX_MAX_NUM_SCENES 4 diff --git a/include/gfx/util/geometry.h b/include/gfx/util/geometry.h new file mode 100644 index 0000000..a962291 --- /dev/null +++ b/include/gfx/util/geometry.h @@ -0,0 +1,13 @@ +/// Functions to construct geometry procedurally. +#pragma once + +#include + +#include +#include + +/// Construct a quad with positions in the range [-1, 1]^2. +Geometry* gfx_make_quad_11(GfxCore*); + +/// Construct a quad with positions in the range [0, 1]^2. +Geometry* gfx_make_quad_01(GfxCore*); diff --git a/include/gfx/util/ibl.h b/include/gfx/util/ibl.h new file mode 100644 index 0000000..6e39180 --- /dev/null +++ b/include/gfx/util/ibl.h @@ -0,0 +1,25 @@ +/// Functions for image-based lighting. +#pragma once + +typedef struct IBL IBL; + +typedef struct GfxCore GfxCore; +typedef struct Texture Texture; + +/// Create an environment map filterer for IBL. +IBL* gfx_make_ibl(GfxCore*); + +/// Destroy the environment map filterer. +void gfx_destroy_ibl(GfxCore*, IBL**); + +/// Create a BRDF integration map for IBL. +Texture* gfx_make_brdf_integration_map(IBL*, GfxCore*, int width, int height); + +/// Create an irradiance map (cubemap) from an environment map for IBL. +Texture* gfx_make_irradiance_map( + IBL*, GfxCore*, const Texture* environment_map, int width, int height); + +/// Create a prefiltered environment map (cubemap) for IBL. +Texture* gfx_make_prefiltered_environment_map( + IBL*, GfxCore*, const Texture* environment_map, int width, int height, + int* max_mip_level); diff --git a/include/gfx/util/shader.h b/include/gfx/util/shader.h new file mode 100644 index 0000000..bd058f4 --- /dev/null +++ b/include/gfx/util/shader.h @@ -0,0 +1,46 @@ +/// A variety of shaders included for convenience. +#pragma once + +#include + +typedef struct GfxCore GfxCore; +typedef struct ShaderCompilerDefine ShaderCompilerDefine; +typedef struct ShaderProgram ShaderProgram; + +/// Create a BRDF integration map shader. +ShaderProgram* gfx_make_brdf_integration_map_shader(GfxCore*); + +/// Create a Cook-Torrance shader. +ShaderProgram* gfx_make_cook_torrance_shader(GfxCore*); + +/// Create a Cook-Torrance shader with additional shader compiler defines. +/// This function can be used to create shader permutations. +ShaderProgram* gfx_make_cook_torrance_shader_perm( + GfxCore*, const ShaderCompilerDefine*, size_t num_defines); + +/// Create a 3D debugging shader. +ShaderProgram* gfx_make_debug3d_shader(GfxCore*); + +/// Create a shader for drawing in immediate mode. +ShaderProgram* gfx_make_immediate_mode_shader(GfxCore*); + +/// Create a shader for computing irradiance maps from cube maps. +ShaderProgram* gfx_make_irradiance_map_shader(GfxCore*); + +/// Create a shader for computing prefiltered environment maps from cube maps. +ShaderProgram* gfx_make_prefiltered_environment_map_shader(GfxCore*); + +/// Create a skyquad shader. +ShaderProgram* gfx_make_skyquad_shader(GfxCore*); + +/// Create a shader to view normal-mapped normals. +ShaderProgram* gfx_make_view_normal_mapped_normals_shader(GfxCore*); + +/// Create a shader to view vertex normals. +ShaderProgram* gfx_make_view_normals_shader(GfxCore*); + +/// Create a shader to view vertex tangents. +ShaderProgram* gfx_make_view_tangents_shader(GfxCore*); + +/// Create a shader to view textures. +ShaderProgram* gfx_make_view_texture_shader(GfxCore*); diff --git a/include/gfx/util/skyquad.h b/include/gfx/util/skyquad.h new file mode 100644 index 0000000..2b3fe17 --- /dev/null +++ b/include/gfx/util/skyquad.h @@ -0,0 +1,22 @@ +/// A skyquad is like a skybox but with a single quad. +#pragma once + +typedef struct GfxCore GfxCore; +typedef struct Scene Scene; +typedef struct SceneNode SceneNode; +typedef struct SceneObject SceneObject; +typedef struct Texture Texture; + +/// Create a skyquad. +SceneObject* gfx_make_skyquad(GfxCore*, const Texture*); + +/// Set up a skyquad in the scene. +/// +/// This function adds two scene nodes under the given root node: +/// - An object node to render the skyquad in the background. +/// - A light node to light up other objects with the skyquad. +/// +/// Return the light node under which objects affected by the light can be +/// rooted. +SceneNode* gfx_setup_skyquad( + GfxCore*, SceneNode* root, const Texture* environment_map); diff --git a/shaders/brdf_integration_map.frag b/shaders/brdf_integration_map.frag new file mode 100644 index 0000000..bb2cebd --- /dev/null +++ b/shaders/brdf_integration_map.frag @@ -0,0 +1,93 @@ +precision highp float; + +#define PI 3.1415926535897932384626433832795 +#define NUM_SAMPLES 1024 + +in vec2 Texcoord; + +layout (location = 0) out vec2 Color; + +float radical_inverse_VdC(uint bits) { + bits = (bits << 16u) | (bits >> 16u); + bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); + bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); + bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); + bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); + return float(bits) * 2.3283064365386963e-10; // / 0x100000000 +} + +vec2 hammersley(uint i, uint N) { + return vec2(float(i)/float(N), radical_inverse_VdC(i)); +} + +vec3 importance_sample_GGX(vec2 sample_box, vec3 N, float roughness) { + float r2 = roughness * roughness; + + // Spherical coordinates. + float phi = 2.0 * PI * sample_box.x; + float cos_theta = sqrt((1.0 - sample_box.y) / (1.0 + (r2*r2 - 1.0) * sample_box.y)); + float sin_theta = sqrt(1.0 - cos_theta * cos_theta); + + // Map spherical coordinates to Cartesian coordinates in tangent space. + vec3 H = vec3(cos(phi) * sin_theta, sin(phi) * sin_theta, cos_theta); + + // Map from tangent space to world space. + // + // Tangent space: + // + // N + // | + // | + // | + // |_ _ _ _ _ B + // / + // / + // T + vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); + vec3 T = normalize(cross(up,N)); + vec3 B = cross(N,T); + vec3 H_ws = H.x*T + H.y*B + H.z*N; + return H_ws; +} + +float geometry_schlick_GGX(float k, float NdotV) { + return NdotV / (NdotV * (1.0 - k) + k); +} + +float geometry_smith(float roughness, float NdotL, float NdotV) { + float k = roughness * roughness / 2.0; // IBL + return geometry_schlick_GGX(k, NdotV) * geometry_schlick_GGX(k, NdotL); +} + +vec2 integrate_brdf(float NdotV, float roughness) +{ + vec3 V = vec3(sqrt(1.0 - NdotV * NdotV), 0.0, NdotV); + vec3 N = vec3(0.0, 0.0, 1.0); + + float scale = 0.0; + float bias = 0.0; + for (int i = 0; i < NUM_SAMPLES; ++i) { + vec2 sample_box = hammersley(i, NUM_SAMPLES); + vec3 H = importance_sample_GGX(sample_box, N, roughness); + vec3 L = reflect(-V,H); + float NdotL = max(0.0, L.z); + + if (NdotL > 0.0) { + float NdotH = max(0.0, H.z); + float VdotH = max(0.0, dot(V,H)); + float G = geometry_smith(roughness, NdotL, NdotV); + float G_vis = (G * VdotH) / (NdotH * NdotV); + float Fc = pow(1.0 - VdotH, 5.0); + scale += (1.0 - Fc) * G_vis; + bias += Fc * G_vis; + } + } + scale /= float(NUM_SAMPLES); + bias /= float(NUM_SAMPLES); + return vec2(scale, bias); +} + +void main() +{ + Color = integrate_brdf(Texcoord.x, Texcoord.y); +} diff --git a/shaders/cook_torrance.frag b/shaders/cook_torrance.frag new file mode 100644 index 0000000..1975491 --- /dev/null +++ b/shaders/cook_torrance.frag @@ -0,0 +1,255 @@ +precision highp float; + +uniform vec4 BaseColorFactor; +uniform float MetallicFactor; +uniform float RoughnessFactor; +uniform vec3 EmissiveFactor; + +#ifdef HAS_ALBEDO_MAP +uniform sampler2D BaseColorTexture; +#endif +#ifdef HAS_METALLIC_ROUGHNESS_MAP +uniform sampler2D MetallicRoughnessTexture; +#endif +#ifdef HAS_EMISSIVE_MAP +uniform sampler2D EmissiveTexture; +#endif +#ifdef HAS_OCCLUSION_MAP +uniform sampler2D AmbientOcclusionTexture; +#endif +#ifdef HAS_NORMAL_MAP +uniform sampler2D NormalMap; +#endif + +// TODO: Handle case in which there is no sky. Pass a boolean. +uniform samplerCube Sky; +uniform samplerCube IrradianceMap; +uniform samplerCube PrefilteredEnvironmentMap; +uniform sampler2D BRDFIntegrationMap; +uniform float MaxReflectionLOD; + +uniform vec3 CameraPosition; // World space. + +// World-space position, normal and tangent. +in vec3 Position; +#ifdef HAS_NORMALS +in vec3 Normal; +#endif +#ifdef HAS_TANGENTS +in vec4 Tangent; +#endif +#ifdef HAS_TEXCOORDS +in vec2 Texcoord; +#endif + +layout (location = 0) out vec4 Colour; + +#define PI 3.1415926535897932384626433832795 +#define INV_PI 0.3183098861837907 + +/// Transform a normal map sample into world space. +/// +/// |normalWs| is the surface normal in world space. +/// |normalMapSample| is the normal map sample, not necessarily normalized. +/// +/// TODO: Move to "normal.h" +#if defined(HAS_NORMAL_MAP) && (defined(HAS_TANGENTS) || defined(HAS_TEXCOORDS)) +vec3 get_ws_normal(vec3 normalWs, vec3 normalMapSample) { + vec3 N = normalize(Normal); +#ifdef HAS_TANGENTS + //vec3 T = normalize(tangent.xyz - dot(tangent.xyz, N) * N); + vec3 T = Tangent.xyz; + vec3 B = Tangent.w * cross(N, T); +#elif HAS_TEXCOORDS // No tangents, but must have texcoords. + vec3 pos_dx = dFdx(Position); + vec3 pos_dy = dFdy(Position); + // vec3 uv_dx = vec3(dFdx(Texcoord), 0.0); + // vec3 uv_dy = vec3(dFdy(Texcoord), 0.0); + vec3 uv_dx = dFdx(vec3(Texcoord, 0.0)); + vec3 uv_dy = dFdy(vec3(Texcoord, 0.0)); + vec3 T = (uv_dy.t * pos_dx - uv_dx.t * pos_dy) / + (uv_dx.s * uv_dy.t - uv_dy.s * uv_dx.t); + // vec3 T = pos_dx * uv_dy.t - pos_dy * uv_dx.t; + T = normalize(T - dot(T, N) * N); + vec3 B = normalize(cross(N, T)); +#endif + + if (gl_FrontFacing == false) { + T = -T; + B = -B; + N = -N; + } + + vec3 s = normalMapSample; + //return normalize(s.x * T + s.y * B + s.z * N); + return normalize(mat3(T,B,N) * s); +} +#endif // HAS_TANGENTS || HAS_TEXCOORDS + +float trowbridge_reitz_GGX(float roughness, float NdotH) { + float a = roughness * roughness; + float a2 = a * a; + float d = NdotH * NdotH * (a2 - 1.0) + 1.0; + return a2 / (PI * d * d); +} + +float geometry_schlick_GGX(float k, float NdotV) { + return NdotV / (NdotV * (1.0 - k) + k); +} + +float geometry_smith(float roughness, float NdotL, float NdotV) { + float k = roughness * roughness / 2.0; // IBL + return geometry_schlick_GGX(k, NdotV) * geometry_schlick_GGX(k, NdotL); +} + +vec3 fresnel_schlick(vec3 F0, float HdotV) { + return F0 + (1.0 - F0) * pow(clamp(1.0 - HdotV, 0.0, 1.0), 5.0); +} + +vec3 fresnel_schlick_roughness(vec3 F0, float NdotV, float roughness) { + return F0 + + (max(vec3(1.0 - roughness), F0) - F0) + * pow(clamp(1.0 - NdotV, 0.0, 1.0), 5.0); +} + +// Cook-Torrance BRDF for a single light direction. +vec3 cook_torrance( + vec3 albedo, float metallic, float roughness, + float NdotL, float NdotV, float NdotH, float HdotV) { + vec3 F0 = mix(vec3(0.04), albedo, metallic); + float D = trowbridge_reitz_GGX(roughness, NdotH); + vec3 F = fresnel_schlick(F0, HdotV); + float G = geometry_smith(roughness, NdotL, NdotV); + vec3 Kd = mix(vec3(1.0) - F, vec3(0.0), metallic); + vec3 diffuse = Kd*albedo*INV_PI; + // Take a max to prevent division by 0 when either dot product is 0. + vec3 specular = (D*F*G) / max(4.0 * NdotV * NdotL, 0.0001); + return diffuse + specular; +} + +// Cook-Torrance BRDF for IBL. +vec3 cook_torrance_IBL( + vec3 albedo, float metallic, float roughness, float occlusion, + float NdotV, + vec3 irradiance, vec3 prefiltered_env, vec2 BRDF_env) { + vec3 F0 = mix(vec3(0.04), albedo, metallic); + vec3 F = fresnel_schlick_roughness(F0, NdotV, roughness); + vec3 Kd = mix(vec3(1.0) - F, vec3(0.0), metallic); + vec3 diffuse = Kd * albedo * INV_PI * irradiance; + vec3 specular = prefiltered_env * (F * BRDF_env.x + BRDF_env.y); + return occlusion * (diffuse + specular); +} + +void main() +{ + // TODO: Also use the specular F0 map from the model, and emissive. Make sure + // to use all maps. + // https://sketchfab.com/models/b81008d513954189a063ff901f7abfe4 +#ifdef HAS_NORMAL_MAP + vec3 normalMapSample = texture(NormalMap, Texcoord).xyz * 2.0 - 1.0; + vec3 N = get_ws_normal(Normal, normalMapSample); +#elif HAS_NORMALS + vec3 N = normalize(Normal); +#endif + vec3 V = normalize(CameraPosition - Position); + vec3 R = reflect(-V, N); + // Not needed for IBL. + //vec3 L = N; + //vec3 H = normalize(L + V); + + float NdotV = max(0.0, dot(N, V)); + // Not needed for IBL. + //float NdotL = max(0.0, dot(N,L)); + //float NdotH = max(0.0, dot(N,H)); + //float HdotV = clamp(dot(H,V), 0.0, 1.0); // Clamp to prevent black spots. + + // TODO: BaseColorFactor and BaseColorTexture are vec4/rgba quantities + // respectively. Handle the alpha channel. + // TODO: Other factors. +#ifdef HAS_ALBEDO_MAP + vec3 albedo = vec3(BaseColorFactor) * texture(BaseColorTexture, Texcoord).rgb; +#else + vec3 albedo = vec3(BaseColorFactor); +#endif +#ifdef HAS_METALLIC_ROUGHNESS_MAP + // Spec: "Its green channel contains roughness values and its blue channel + // contains metalness values." + vec2 metal_roughness + = vec2(MetallicFactor, RoughnessFactor) + * texture(MetallicRoughnessTexture, Texcoord).bg; +#else + vec2 metal_roughness = vec2(MetallicFactor, RoughnessFactor); +#endif +#ifdef HAS_EMISSIVE_MAP + vec3 emissive = EmissiveFactor * texture(EmissiveTexture, Texcoord).rgb; +#else + vec3 emissive = EmissiveFactor; +#endif +#ifdef HAS_OCCLUSION_MAP + float occlusion = texture(AmbientOcclusionTexture, Texcoord).r; +#else + float occlusion = 1.0; +#endif + float metallic = metal_roughness.x; + float roughness = metal_roughness.y; + + // For a single light direction: + // vec3 brdf = cook_torrance(albedo, metallic, roughness, NdotL, NdotV, NdotH, HdotV); + // vec3 Li = texture(Sky, N).rgb; + // vec3 colour = brdf * Li * NdotL; + + // For IBL: + vec3 irradiance = texture(IrradianceMap, N).rgb; + vec3 prefiltered_env = textureLod(PrefilteredEnvironmentMap, R, roughness * MaxReflectionLOD).rgb; + vec2 BRDF_env = texture(BRDFIntegrationMap, vec2(NdotV, roughness)).rg; + vec3 colour = cook_torrance_IBL( + albedo, metallic, roughness, occlusion, NdotV, irradiance, prefiltered_env, BRDF_env); + + colour += emissive; + + // Reinhard tone mapping. + colour = colour / (colour + vec3(1.0)); + + // Gamma correction. + colour = pow(colour, vec3(1.0 / 2.2)); + + // Debugging. + // + // Normal texture. + //colour = normalMapSample * 0.5 + 0.5; + // + // Geometry normal. + //colour = normalize(Normal) * 0.5 + 0.5; + // + // Shading normal. + //colour = N * 0.5 + 0.5; + // + // Tangent and bitangent. + // { + // vec3 pos_dx = dFdx(Position); + // vec3 pos_dy = dFdy(Position); + // // vec3 uv_dx = vec3(dFdx(Texcoord), 0.0); + // // vec3 uv_dy = vec3(dFdy(Texcoord), 0.0); + // vec3 uv_dx = dFdx(vec3(Texcoord, 0.0)); + // vec3 uv_dy = dFdy(vec3(Texcoord, 0.0)); + // vec3 T = (uv_dy.t * pos_dx - uv_dx.t * pos_dy) / + // (uv_dx.s * uv_dy.t - uv_dy.s * uv_dx.t); + // // vec3 T = pos_dx * uv_dy.t - pos_dy * uv_dx.t; + // vec3 N = normalize(Normal); + // T = normalize(T - dot(T, N) * N); + // vec3 B = normalize(cross(N, T)); + + // if (gl_FrontFacing == false) { + // T = -T; + // B = -B; + // N = -N; + // } + + // // Tangent. + // //colour = T * 0.5 + 0.5; + // // Bitangent. + // //colour = B * 0.5 + 0.5; + // } + + Colour = vec4(colour, 1.0); +} diff --git a/shaders/cook_torrance.vert b/shaders/cook_torrance.vert new file mode 100644 index 0000000..5f126c0 --- /dev/null +++ b/shaders/cook_torrance.vert @@ -0,0 +1,75 @@ +precision highp float; + +uniform mat4 ModelMatrix; +// uniform mat4 Modelview; +uniform mat4 View; +uniform mat4 Projection; +//uniform mat4 MVP; +#ifdef HAS_JOINTS +// The client should pass in an appropriate value for MAX_JOINTS. +// #define MAX_JOINTS 96 +// +// matnxm -- n columns and m rows, different convention from math. +// We don't need the last row of [0, 0, 0, 1], so drop it to pack the matrices +// as tightly as possible. +// 256 joints * 4x4 matrix * 4 bytes/float = 16.0KB +// 256 joints * 4x3 matrix * 4 bytes/float = 12.0KB +// 96 joints * 4x4 matrix * 4 bytes/float = 6.0KB +// 96 joints * 4x3 matrix * 4 bytes/float = 4.5KB +//uniform mat4x3 Joints[MAX_JOINTS]; +uniform mat4 JointMatrices[MAX_JOINTS]; // Use 4x4 for now to keep it simple. +#endif + +layout (location = 0) in vec3 vPosition; +#ifdef HAS_NORMALS +layout (location = 1) in vec3 vNormal; +#endif +#ifdef HAS_TANGENTS +layout (location = 2) in vec4 vTangent; +#endif +#ifdef HAS_TEXCOORDS +layout (location = 3) in vec2 vTexcoord; +#endif +#ifdef HAS_JOINTS +layout (location = 4) in uvec4 vJoint; +layout (location = 5) in vec4 vWeight; +#endif + +// World-space position, normal and tangent. +out vec3 Position; +#ifdef HAS_NORMALS +out vec3 Normal; +#endif +#ifdef HAS_TANGENTS +out vec4 Tangent; +#endif +#ifdef HAS_TEXCOORDS +out vec2 Texcoord; +#endif + +void main() +{ +#ifdef HAS_JOINTS + mat4 skinMatrix = + vWeight.x * JointMatrices[vJoint.x] + + vWeight.y * JointMatrices[vJoint.y] + + vWeight.z * JointMatrices[vJoint.z] + + vWeight.w * JointMatrices[vJoint.w]; + Position = vec3(ModelMatrix * skinMatrix * vec4(vPosition, 1.0)); +#else + Position = vec3(ModelMatrix * vec4(vPosition, 1.0)); +#endif +#ifdef HAS_NORMALS + Normal = mat3(ModelMatrix) * vNormal; + //Normal = normalize(ModelMatrix * vec4(vNormal, 0.0)).xyz; +#endif +#ifdef HAS_TANGENTS + Tangent = vec4(mat3(ModelMatrix) * vTangent.xyz, vTangent.w); +#endif +#ifdef HAS_TEXCOORDS + Texcoord = vTexcoord; +#endif + gl_Position = Projection * View * vec4(Position, 1.0); + //gl_Position = Projection * vec4(Position, 1.0); + //gl_Position = MVP * vec4(vPosition, 1.0); +} diff --git a/shaders/cubemap_filtering.vert b/shaders/cubemap_filtering.vert new file mode 100644 index 0000000..d0cf73f --- /dev/null +++ b/shaders/cubemap_filtering.vert @@ -0,0 +1,39 @@ +precision highp float; + +#define PI 3.1415926535897932384626433832795 +#define FOVY (90.0 * PI / 180.0) + +uniform mat4 CameraRotation; // From camera space to world space. +uniform float Flip; + +layout (location = 0) in vec2 vPosition; + +out vec3 Ray; + +// DEBUG +// out vec2 Texcoord; + +// This is very similar to the skyquad vertex shader. +// +// The ray is not normalized because it isn't necessary for cubemap sampling. +// +// We also use a fixed fovy = 90 degrees because we want the frustum to pass +// exactly through each face of the cube. The aspect ratio is also just 1. +vec3 sky_ray(vec2 FilmPosition) +{ + float d = 0.5 / tan(FOVY/2.0); + return vec3(FilmPosition, -d); +} + +void main() +{ + vec2 FilmPosition = vPosition * 0.5; // map [-1,1] -> [-1/2, +1/2] + FilmPosition *= Flip; + Ray = mat3(CameraRotation) * sky_ray(FilmPosition); + // TODO: Should disable depth test when rendering. + gl_Position = vec4(vPosition, 0.99999, 1.0); // z=1 -> send to background + + // DEBUG + // Texcoord = FilmPosition + 0.5; + // Texcoord.y = 1.0 - Texcoord.y; +} diff --git a/shaders/debug3d.frag b/shaders/debug3d.frag new file mode 100644 index 0000000..54568d4 --- /dev/null +++ b/shaders/debug3d.frag @@ -0,0 +1,21 @@ +precision highp float; + +const vec3 Colour = vec3(0.97, 0.948, 0.91); + +const vec3 ToLight = vec3(1, 0.7, 1); + +in vec3 Normal; + +out vec4 FragColour; + +void main() +{ + vec3 N = normalize(Normal); + vec3 L = normalize(ToLight); + + vec3 a = vec3(0.7); + vec3 d = vec3(0.3 * (0.7*max(0.0, dot(L,N)) + 0.3*max(0.0, dot(-L,N)))); + vec3 c = Colour * (a+d); + + FragColour = vec4(pow(c, vec3(1.0 / 2.2)), 1.0); +} diff --git a/shaders/debug3d.vert b/shaders/debug3d.vert new file mode 100644 index 0000000..d51684f --- /dev/null +++ b/shaders/debug3d.vert @@ -0,0 +1,15 @@ +precision highp float; + +uniform mat4 Modelview; +uniform mat4 Projection; + +layout (location = 0) in vec3 vPosition; +layout (location = 1) in vec3 vNormal; + +out vec3 Normal; + +void main() +{ + Normal = mat3(Modelview) * vNormal; + gl_Position = Projection * Modelview * vec4(vPosition, 1.0); +} diff --git a/shaders/immediate_mode.frag b/shaders/immediate_mode.frag new file mode 100644 index 0000000..ac23b5c --- /dev/null +++ b/shaders/immediate_mode.frag @@ -0,0 +1,10 @@ +precision highp float; + +uniform vec4 Colour; + +out vec4 FragColour; + +void main() +{ + FragColour = vec4(pow(Colour.rgb, vec3(1.0/2.2)), Colour.a); +} diff --git a/shaders/immediate_mode.vert b/shaders/immediate_mode.vert new file mode 100644 index 0000000..65070bb --- /dev/null +++ b/shaders/immediate_mode.vert @@ -0,0 +1,11 @@ +precision highp float; + +uniform mat4 Model; +uniform mat4 ViewProjection; + +layout (location = 0) in vec3 vPosition; + +void main() +{ + gl_Position = ViewProjection * Model * vec4(vPosition, 1.0); +} diff --git a/shaders/irradiance_map.frag b/shaders/irradiance_map.frag new file mode 100644 index 0000000..8200e73 --- /dev/null +++ b/shaders/irradiance_map.frag @@ -0,0 +1,65 @@ +precision highp float; + +#define PI 3.1415926535897932384626433832795 +#define EPS 0.001 +#define NUM_SAMPLES_AZIMUTH 250 +#define NUM_SAMPLES_ZENITH 50 +#define MAX_AZIMUTH (2*PI) +#define MAX_ZENITH (PI/2.0) +#define AZIMUTH_DELTA (MAX_AZIMUTH / float(NUM_SAMPLES_AZIMUTH)) +#define ZENITH_DELTA (MAX_ZENITH / float(NUM_SAMPLES_ZENITH)) + +uniform samplerCube Sky; + +in vec3 Ray; + +// DEBUG +// in vec2 Texcoord; + +layout (location = 0) out vec4 Color; + +void main() +{ + // Tangent space: + // + // N + // | + // | + // | + // |_ _ _ _ _ B + // / + // / + // T + vec3 N = normalize(Ray); + vec3 B = (abs(N.x) - 1.0 <= EPS) ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); + vec3 T = normalize(cross(B, N)); + B = normalize(cross(N, T)); + + int num_samples = 0; + vec3 irradiance = vec3(0.0); + for (float theta = 0.0; theta < MAX_AZIMUTH; theta += AZIMUTH_DELTA) { + for (float phi = 0.0; phi < MAX_ZENITH; phi += ZENITH_DELTA) { + // Spherical to Cartesian. + vec3 sample_tangent_space = vec3( + sin(phi) * cos(theta), + sin(phi) * sin(theta), + cos(phi)); + // Tangent space to world space. + vec3 sample_world_space = + sample_tangent_space.x * B + + sample_tangent_space.y * T + + sample_tangent_space.z * N; + + irradiance += texture(Sky, sample_world_space).rgb * sin(phi) * cos(phi); + num_samples += 1; + } + } + irradiance = PI * irradiance / float(num_samples); + + // For debugging in trace. + //irradiance = texture(Sky, Ray).rgb; + // irradiance = vec3(Texcoord, 0.0); + //irradiance = pow(irradiance, vec3(1.0/2.2)); + + Color = vec4(irradiance, 1.0); +} diff --git a/shaders/prefiltered_environment_map.frag b/shaders/prefiltered_environment_map.frag new file mode 100644 index 0000000..8327950 --- /dev/null +++ b/shaders/prefiltered_environment_map.frag @@ -0,0 +1,78 @@ +precision highp float; + +#define PI 3.1415926535897932384626433832795 +#define NUM_SAMPLES 4096 + +uniform samplerCube Sky; +uniform float Roughness; + +in vec3 Ray; + +layout (location = 0) out vec4 Color; + +float radical_inverse_VdC(uint bits) { + bits = (bits << 16u) | (bits >> 16u); + bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); + bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); + bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); + bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); + return float(bits) * 2.3283064365386963e-10; // / 0x100000000 +} + +vec2 hammersley(uint i, uint N) { + return vec2(float(i)/float(N), radical_inverse_VdC(i)); +} + +vec3 importance_sample_GGX(vec2 sample_box, vec3 N, float roughness) { + float r2 = roughness * roughness; + + // Spherical coordinates. + float phi = 2.0 * PI * sample_box.x; + float cos_theta = sqrt((1.0 - sample_box.y) / (1.0 + (r2*r2 - 1.0) * sample_box.y)); + float sin_theta = sqrt(1.0 - cos_theta * cos_theta); + + // Map spherical coordinates to Cartesian coordinates in tangent space. + vec3 H = vec3(cos(phi) * sin_theta, sin(phi) * sin_theta, cos_theta); + + // Map from tangent space to world space. + // + // Tangent space: + // + // N + // | + // | + // | + // |_ _ _ _ _ B + // / + // / + // T + vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); + vec3 T = normalize(cross(up,N)); + vec3 B = cross(N,T); + vec3 H_ws = H.x*T + H.y*B + H.z*N; + return H_ws; +} + +void main() +{ + vec3 N = normalize(Ray); + vec3 R = N; + vec3 V = R; + + vec3 irradiance = vec3(0.0); + float total_weight = 0.0; + for (uint i = 0; i < NUM_SAMPLES; ++i) { + vec2 sample_box = hammersley(i, NUM_SAMPLES); + vec3 H = importance_sample_GGX(sample_box, N, Roughness); + vec3 L = reflect(-V,H); + + float NdotL = max(dot(N,L), 0.0); + if (NdotL > 0.0) { + irradiance += texture(Sky, H).rgb * NdotL; + total_weight += NdotL; + } + } + irradiance /= total_weight; + + Color = vec4(irradiance, 1.0); +} diff --git a/shaders/quad.vert b/shaders/quad.vert new file mode 100644 index 0000000..ef1834c --- /dev/null +++ b/shaders/quad.vert @@ -0,0 +1,9 @@ +layout (location = 0) in vec2 Position; // Assuming Position in [-1,1]. + +out vec2 Texcoord; + +void main() +{ + Texcoord = Position * 0.5 + 0.5; + gl_Position = vec4(Position, 0.0, 1.0); +} diff --git a/shaders/skyquad.frag b/shaders/skyquad.frag new file mode 100644 index 0000000..9b44bfd --- /dev/null +++ b/shaders/skyquad.frag @@ -0,0 +1,13 @@ +uniform samplerCube Skyquad; + +in vec3 Ray; + +layout (location = 0) out vec4 Colour; + +void main() +{ + vec3 R = normalize(Ray); + Colour = vec4(pow(texture(Skyquad, R).rgb, vec3(1.0/2.2)), 1.0); + // Debug. + //Colour = vec4(pow(R*0.5 + 0.5, vec3(1.0 / 2.2)), 1.0); +} diff --git a/shaders/skyquad.vert b/shaders/skyquad.vert new file mode 100644 index 0000000..c0c46e6 --- /dev/null +++ b/shaders/skyquad.vert @@ -0,0 +1,27 @@ +uniform mat4 CameraRotation; // From camera space to world space. +uniform float Fovy; +uniform float Aspect; + +layout (location = 0) in vec2 Position; + +out vec3 Ray; + +// We would typically normalize the vector, but there is no need to do so when +// sampling a cube map. +vec3 sky_ray(vec2 FilmPosition) +{ + //float d = 0.5 / tan(Fovy/2.0); + // return vec3((FilmPosition.x - 0.5) * Aspect, + // FilmPosition.y - 0.5, + // -d); + float d = 0.5 / tan(Fovy/2.0); + return vec3(FilmPosition, -d); +} + +void main() +{ + vec2 FilmPosition = Position * 0.5; // map [-1,1] -> [-1/2, +1/2] + Ray = mat3(CameraRotation) * sky_ray(FilmPosition); + // Set z to the background. + gl_Position = vec4(Position, 0.99999, 1.0); // z=1 -> send to background +} diff --git a/shaders/view_normal_mapped_normals.frag b/shaders/view_normal_mapped_normals.frag new file mode 100644 index 0000000..a372c02 --- /dev/null +++ b/shaders/view_normal_mapped_normals.frag @@ -0,0 +1,28 @@ +precision highp float; + +uniform sampler2D NormalMap; + +in vec3 Normal; +in vec4 Tangent; +in vec3 Bitangent; // TODO: Compute here or in PS? +in vec2 Texcoord; + +out vec4 FragColour; + +// TODO: Move to "normal.h" +vec3 get_vs_normal(vec3 normal, vec4 tangent, vec3 normalMapSample) { + vec3 N = normal; + // vec3 T = normalize(interpTangent - dot(tangent, N)*N); + // vec3 B = normalize(interpBitangent - dot(interpTangent, N)*N - dot(interpTangent, T)*T); + vec3 T = tangent.xyz; + //vec3 B = tangent.w * cross(N,T); + vec3 B = Bitangent; + vec3 n = normalMapSample; + return normalize(n.x*T + n.y*B + n.z*N); +} + +void main() { + vec3 normalMapSample = texture(NormalMap, Texcoord).xyz * 2.0 - 1.0; + vec3 N = get_vs_normal(Normal, Tangent, normalMapSample); + FragColour = vec4(pow(N, vec3(1.0 / 2.2)), 1.0); +} diff --git a/shaders/view_normal_mapped_normals.vert b/shaders/view_normal_mapped_normals.vert new file mode 100644 index 0000000..004ed9a --- /dev/null +++ b/shaders/view_normal_mapped_normals.vert @@ -0,0 +1,22 @@ +precision highp float; + +uniform mat4 Modelview; +uniform mat4 Projection; + +layout (location = 0) in vec3 vPosition; +layout (location = 1) in vec3 vNormal; +layout (location = 2) in vec4 vTangent; +layout (location = 3) in vec2 vTexcoord; + +out vec3 Normal; +out vec4 Tangent; +out vec3 Bitangent; // TODO: Compute here or in PS? +out vec2 Texcoord; + +void main() { + Texcoord = vTexcoord; + Normal = mat3(Modelview) * vNormal; + Tangent = vec4(mat3(Modelview) * vTangent.xyz, vTangent.w); + Bitangent = cross(Normal, Tangent.xyz) * vTangent.w; + gl_Position = Projection * Modelview * vec4(vPosition, 1.0); +} diff --git a/shaders/view_normals.frag b/shaders/view_normals.frag new file mode 100644 index 0000000..e90189c --- /dev/null +++ b/shaders/view_normals.frag @@ -0,0 +1,11 @@ +precision highp float; + +in vec3 Normal; + +out vec4 FragColour; + +void main() +{ + vec3 N = normalize(Normal); + FragColour = vec4(pow(N, vec3(1.0 / 2.2)), 1.0); +} diff --git a/shaders/view_normals.vert b/shaders/view_normals.vert new file mode 100644 index 0000000..d51684f --- /dev/null +++ b/shaders/view_normals.vert @@ -0,0 +1,15 @@ +precision highp float; + +uniform mat4 Modelview; +uniform mat4 Projection; + +layout (location = 0) in vec3 vPosition; +layout (location = 1) in vec3 vNormal; + +out vec3 Normal; + +void main() +{ + Normal = mat3(Modelview) * vNormal; + gl_Position = Projection * Modelview * vec4(vPosition, 1.0); +} diff --git a/shaders/view_tangents.frag b/shaders/view_tangents.frag new file mode 100644 index 0000000..11d1455 --- /dev/null +++ b/shaders/view_tangents.frag @@ -0,0 +1,17 @@ +precision highp float; + +in vec4 Tangent; + +out vec4 FragColour; + +void main() { + vec3 T = normalize(Tangent.xyz); + FragColour = vec4(pow(T, vec3(1.0 / 2.2)), 1.0);FragColour = vec4(pow(T, vec3(1.0 / 2.2)), 1.0); + + // View sign. + // float sign = Tangent.w; + // float R = sign > 0.0 ? 1.0 : 0.0; + // float B = sign < 0.0 ? 1.0 : 0.0; + // vec3 signColour = vec3(R,0.0,B); + // FragColour = vec4(pow(signColour, vec3(1.0 / 2.2)), 1.0); +} diff --git a/shaders/view_tangents.vert b/shaders/view_tangents.vert new file mode 100644 index 0000000..561ad22 --- /dev/null +++ b/shaders/view_tangents.vert @@ -0,0 +1,14 @@ +precision highp float; + +uniform mat4 Modelview; +uniform mat4 Projection; + +layout (location = 0) in vec3 vPosition; +layout (location = 2) in vec4 vTangent; + +out vec4 Tangent; + +void main() { + Tangent = vec4(Tangent.xyz = mat3(Modelview) * vTangent.xyz, vTangent.w); + gl_Position = Projection * Modelview * vec4(vPosition, 1.0); +} diff --git a/shaders/view_texture.frag b/shaders/view_texture.frag new file mode 100644 index 0000000..12fa367 --- /dev/null +++ b/shaders/view_texture.frag @@ -0,0 +1,15 @@ +uniform sampler2D Texture; + +in vec2 Texcoord; + +layout (location = 0) out vec4 Colour; + +void main() +{ + // There is a question here whether we want to view the texture through the + // sampler or unfiltered. Prefer the latter for now. + //vec3 colour = texture(Texture, Texcoord).rgb; + ivec2 st = ivec2(Texcoord * vec2(textureSize(Texture, 0))); + vec3 colour = texelFetch(Texture, st, 0).rgb; + Colour = vec4(pow(colour, vec3(1.0 / 2.2)), 1.0); +} diff --git a/shaders/view_texture.vert b/shaders/view_texture.vert new file mode 100644 index 0000000..4e3c7d7 --- /dev/null +++ b/shaders/view_texture.vert @@ -0,0 +1,13 @@ +layout (location = 0) in vec2 Position; + +out vec2 Texcoord; + +void main() +{ + Texcoord = Position * vec2(0.5) + vec2(0.5);// Map from [-1, +1] to [0, 1]. + // The Gfx library is written to work with the glTF sample models, which + // seem to want the textures loaded "as is" without flipping. Flip the + // y-coordinate here so that the texture appears as expected. + Texcoord.y = 1.0 - Texcoord.y; + gl_Position = vec4(Position, 0.0, 1.0); +} diff --git a/src/asset/asset_cache.c b/src/asset/asset_cache.c new file mode 100644 index 0000000..16c4d5c --- /dev/null +++ b/src/asset/asset_cache.c @@ -0,0 +1,252 @@ +#include "asset_cache.h" + +#include "model.h" +#include "scene/animation_impl.h" +#include "scene/model_impl.h" +#include "scene/node_impl.h" +#include "scene/scene_memory.h" +#include "texture.h" + +#include +#include +#include +#include + +#include +#include +#include + +static void log_model_load_failure(const LoadModelCmd* cmd) { + assert(cmd); + + switch (cmd->origin) { + case AssetFromFile: + log_error("Failed to load model: %s", mstring_cstr(&cmd->filepath)); + break; + case AssetFromMemory: + log_error("Failed to load model: %p", cmd->data); + break; + } +} + +static void log_texture_load_failure(const LoadTextureCmd* cmd) { + assert(cmd); + + switch (cmd->origin) { + case AssetFromFile: + switch (cmd->type) { + case LoadTexture: + log_error( + "Failed to load texture: %s", + mstring_cstr(&cmd->data.texture.filepath)); + break; + case LoadCubemap: + log_error( + "Failed to load cubemap texture: %s", + mstring_cstr(&cmd->data.cubemap.filepaths.filepath_pos_x)); + break; + } + break; + case AssetFromMemory: + switch (cmd->type) { + case LoadTexture: + log_error("Failed to load texture: %p", cmd->data.texture.data); + break; + case LoadCubemap: + log_error( + "Failed to load texture: %p", cmd->data.cubemap.buffers.data_pos_x); + break; + } + break; + } +} + +static Hash calc_model_hash(const LoadModelCmd* cmd) { + assert(cmd); + switch (cmd->origin) { + case AssetFromFile: + return cstring_hash(mstring_cstr(&cmd->filepath)); + case AssetFromMemory: + return (Hash)cmd->data; + } + FAIL("Unhandled model asset origin"); + return 0; +} + +static Hash calc_texture_hash(const LoadTextureCmd* cmd) { + assert(cmd); + switch (cmd->origin) { + case AssetFromFile: + switch (cmd->type) { + case LoadTexture: + return cstring_hash(mstring_cstr(&cmd->data.texture.filepath)); + case LoadCubemap: + return cstring_hash( + mstring_cstr(&cmd->data.cubemap.filepaths.filepath_pos_x)) ^ + cstring_hash( + mstring_cstr(&cmd->data.cubemap.filepaths.filepath_neg_x)) ^ + cstring_hash( + mstring_cstr(&cmd->data.cubemap.filepaths.filepath_pos_y)) ^ + cstring_hash( + mstring_cstr(&cmd->data.cubemap.filepaths.filepath_neg_y)) ^ + cstring_hash( + mstring_cstr(&cmd->data.cubemap.filepaths.filepath_pos_z)) ^ + cstring_hash( + mstring_cstr(&cmd->data.cubemap.filepaths.filepath_neg_z)); + } + break; + case AssetFromMemory: + switch (cmd->type) { + case LoadTexture: + return (Hash)cmd->data.texture.data; + case LoadCubemap: + return (Hash)cmd->data.cubemap.buffers.data_pos_x ^ + (Hash)cmd->data.cubemap.buffers.data_neg_x ^ + (Hash)cmd->data.cubemap.buffers.data_pos_y ^ + (Hash)cmd->data.cubemap.buffers.data_neg_y ^ + (Hash)cmd->data.cubemap.buffers.data_pos_z ^ + (Hash)cmd->data.cubemap.buffers.data_neg_z; + } + break; + } + FAIL("Unhandled texture asset origin"); + return 0; +} + +static Asset* lookup_cache(AssetCache* cache, Hash hash) { + assert(cache); + mempool_foreach(&cache->assets, asset, { + if (asset->hash == hash) { + return asset; + } + }); + return 0; +} + +static void log_model_cache_hit(const LoadModelCmd* cmd, Hash hash) { + assert(cmd); + switch (cmd->origin) { + case AssetFromFile: + LOGD( + "Found asset [%s] in cache with hash [%lu]", + mstring_cstr(&cmd->filepath), hash); + break; + case AssetFromMemory: + LOGD("Found asset [%p] in cache with hash [%lu]", cmd->data, hash); + break; + } +} + +static void log_model_loaded(const LoadModelCmd* cmd) { + assert(cmd); + switch (cmd->origin) { + case AssetFromFile: + LOGD("Loaded asset from file: [%s]", mstring_cstr(&cmd->filepath)); + break; + case AssetFromMemory: + LOGD("Loaded asset from memory: [%p]", cmd->data); + break; + } +} + +static Model* clone_model(const Model* model) { + assert(model); + + // Only the Anima needs to be cloned since everything else in the model is + // static. + // + // The Anima can be partially shallow-cloned. Skeletons and animations are + // static and can be shared with the original Anima. Other members are + // deep-cloned. Skeletons in particular point back to their Anima, so need to + // be deep-cloned. + const SceneNode* root = mem_get_node(model->root); + if (gfx_get_node_type(root) == AnimaNode) { + const Anima* anima = gfx_get_node_anima(root); + Anima* anima_copy = mem_alloc_anima(); + *anima_copy = *anima; // Shallow copy. + + SceneNode* root_copy = gfx_clone_scene_shallow(root); + root_copy->anima = mem_get_anima_index(anima_copy); + anima_copy->parent = mem_get_node_index(root_copy); + + Model* copy = mem_alloc_model(); + copy->root = mem_get_node_index(root_copy); + return copy; + } else { + return (Model*)model; // Static model, can't be mutated. + } +} + +void gfx_init_asset_cache(AssetCache* cache) { + assert(cache); + mempool_make(&cache->assets); + + // Allocate a dummy asset at index 0 to guarantee that no assets allocated by + // the caller map to index 0. + const Asset* dummy = mempool_alloc(&cache->assets); + assert(mempool_get_block_index(&cache->assets, dummy) == 0); +} + +void gfx_destroy_asset_cache(AssetCache* cache) { + assert(cache); + mempool_del(&cache->assets); +} + +Model* gfx_load_model(Gfx* gfx, const LoadModelCmd* cmd) { + assert(gfx); + + AssetCache* cache = gfx_get_asset_cache(gfx); + + // First search for the asset in the cache. + const uint64_t hash = calc_model_hash(cmd); + Asset* asset = lookup_cache(cache, hash); + if (asset) { + log_model_cache_hit(cmd, hash); + return clone_model(asset->model); + } + + // Asset not found in the cache. + // Load it, insert it into the cache, and return it. + Model* model = gfx_model_load(gfx, cmd); + if (model) { + *(Asset*)mempool_alloc(&cache->assets) = (Asset){ + .type = ModelAsset, + .hash = hash, + .model = model, + }; + log_model_loaded(cmd); + return clone_model(model); + } else { + log_model_load_failure(cmd); + return 0; + } +} + +const Texture* gfx_load_texture(Gfx* gfx, const LoadTextureCmd* cmd) { + assert(gfx); + assert(cmd); + + AssetCache* cache = gfx_get_asset_cache(gfx); + + // First search for the asset in the cache. + const uint64_t hash = calc_texture_hash(cmd); + Asset* asset = lookup_cache(cache, hash); + if (asset) { + return asset->texture; + } + + // Asset not found in the cache. + // Load it, insert it into the cache, and return it. + GfxCore* gfxcore = gfx_get_core(gfx); + const Texture* texture = gfx_texture_load(gfxcore, cmd); + if (texture) { + *(Asset*)mempool_alloc(&cache->assets) = (Asset){ + .type = TextureAsset, + .hash = hash, + .texture = texture, + }; + } else { + log_texture_load_failure(cmd); + } + return texture; +} diff --git a/src/asset/asset_cache.h b/src/asset/asset_cache.h new file mode 100644 index 0000000..b2a35ed --- /dev/null +++ b/src/asset/asset_cache.h @@ -0,0 +1,37 @@ +#pragma once + +#include + +#include +#include + +typedef struct Model Model; +typedef struct Texture Texture; + +typedef uint64_t Hash; + +typedef enum AssetType { + ModelAsset, + TextureAsset, +} AssetType; + +typedef struct Asset { + AssetType type; + Hash hash; + union { + Model* model; + const Texture* texture; + }; +} Asset; + +DEF_MEMPOOL(asset_pool, Asset, GFX_MAX_NUM_ASSETS) + +typedef struct AssetCache { + asset_pool assets; +} AssetCache; + +/// Create a new asset cache. +void gfx_init_asset_cache(AssetCache*); + +/// Destroy the asset cache. +void gfx_destroy_asset_cache(AssetCache*); diff --git a/src/asset/model.c b/src/asset/model.c new file mode 100644 index 0000000..25f2780 --- /dev/null +++ b/src/asset/model.c @@ -0,0 +1,1968 @@ +/// Loads scenes from memory and files. +/// +/// Only the GLTF scene format is current supported. +/// +/// ---------------------------------------------------------------------------- +/// glTF File Format Documentation +/// ---------------------------------------------------------------------------- +/// +/// cgltf: +/// https://github.com/jkuhlmann/cgltf +/// +/// gltf overview: +/// https://raw.githubusercontent.com/KhronosGroup/glTF/master/specification/2.0/figures/gltfOverview-2.0.0b.png +/// +/// gltf spec: +/// https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md +/// +/// Sample models: +/// https://github.com/KhronosGroup/glTF-Sample-Models/tree/master/2.0 +/// https://github.com/KhronosGroup/glTF-Sample-Models/blob/master/2.0/Sponza/glTF/Sponza.gltf +/// https://github.com/KhronosGroup/glTF-Sample-Models/blob/master/2.0/AlphaBlendModeTest/glTF/AlphaBlendModeTest.gltf +/// https://github.com/KhronosGroup/glTF-Sample-Models/blob/master/2.0/Buggy/glTF/Buggy.gltf +/// https://github.com/KhronosGroup/glTF-Sample-Models/blob/master/2.0/AntiqueCamera/glTF/AntiqueCamera.gltf +/// https://github.com/KhronosGroup/glTF-Sample-Models/blob/master/2.0/DamagedHelmet/glTF/DamagedHelmet.gltf +/// +/// ---------------------------------------------------------------------------- +/// Implementation Notes +/// ---------------------------------------------------------------------------- +/// +/// # glTF and the gfx library +/// +/// glTF has concepts that are similar to those in the gfx library, but there +/// isn't an exact 1-1 mapping. Concepts map as follows: +/// +/// glTF gfx +/// ---- --- +/// buffer Buffer +/// accessor + buffer view BufferView +/// mesh primitive (geom + mat) Mesh (also geom + mat) +/// mesh SceneObject +/// node SceneNode +/// +/// glTF buffers map 1-1 with gfx Buffers. glTF scenes make heavy re-use of +/// buffers across views/accessors/meshes, so it is important to make that same +/// re-use in the gfx library to use the data effectively and without +/// duplication. The Sponza scene, for example, has all of its data in one giant +/// buffer. +/// +/// glTF accessors and buffer views are combined and mapped to gfx BufferViews. +/// The glTF buffer view's offset/length/stride are combined with the accessor's +/// offset, and together with the remaining information of both data structures +/// baked into a BufferView. Internally, this information is fed into +/// glVertexAttribPointer() calls, wrapped in a VAO (index view/accessor +/// information is fed into glDrawElements()). This baking should not hurt +/// re-use, at least in the OpenGL world. +/// +/// A glTF mesh primitive contains a piece of geometry and a material. This maps +/// directly to a gfx Mesh. +/// +/// A glTF mesh is a list of mesh primitives. This maps nicely to a gfx +/// SceneObject, with the only inconvenience that terminology gets a little +/// confusing. +/// +/// Finally, glTF nodes map directly to gfx SceneNodes. Both enforce a strict +/// tree hierarchy; DAGs are not supported. +/// +/// # Materials +/// +/// glTF uses the metallic-roughness material model. However, an extension +/// allows a scene to use the specular-glossiness model as well and cgltf +/// supports it: +/// +/// https://kcoley.github.io/glTF/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness/ +/// +/// From the docs, the specular-glossiness model can represent more materials +/// than the metallic-roughness model, but it is also more computationally +/// expensive. Furthermore, a material in glTF can specify parameters for both +/// models, leaving it up to the implementation to decide which one to use. +/// In our case, we use the specular-glosiness model if parameters for it are +/// provided, otherwise we use the metallic-roughness model. + +#include "asset/model.h" + +#include "asset/texture.h" +#include "gfx/core.h" +#include "gfx/gfx.h" +#include "gfx/scene/animation.h" +#include "gfx/scene/camera.h" +#include "gfx/scene/material.h" +#include "gfx/scene/mesh.h" +#include "gfx/scene/node.h" +#include "gfx/scene/object.h" +#include "gfx/scene/scene.h" +#include "gfx/sizes.h" +#include "gfx/util/shader.h" + +#include "gfx_assert.h" +#include "scene/model_impl.h" + +#include "cstring.h" +#include "error.h" +#include "log/log.h" +#include "math/camera.h" +#include "math/defs.h" +#include "math/mat4.h" +#include "math/quat.h" +#include "math/vec2.h" +#include "math/vec3.h" + +#include "cgltf_tangents.h" +#define CGLTF_IMPLEMENTATION +#include "cgltf.h" + +#include +#include + +// Taken from the GL header file. +#define GL_NEAREST 0x2600 +#define GL_LINEAR 0x2601 +#define GL_NEAREST_MIPMAP_NEAREST 0x2700 +#define GL_LINEAR_MIPMAP_NEAREST 0x2701 +#define GL_NEAREST_MIPMAP_LINEAR 0x2702 +#define GL_LINEAR_MIPMAP_LINEAR 0x2703 + +// Uniforms names. Must match the names in shaders. +#define UNIFORM_BASE_COLOR_FACTOR "BaseColorFactor" +#define UNIFORM_METALLIC_FACTOR "MetallicFactor" +#define UNIFORM_ROUGHNESS_FACTOR "RoughnessFactor" +#define UNIFORM_EMISSIVE_FACTOR "EmissiveFactor" +#define UNIFORM_BASE_COLOR_TEXTURE "BaseColorTexture" +#define UNIFORM_METALLIC_ROUGHNESS_TEXTURE "MetallicRoughnessTexture" +#define UNIFORM_EMISSIVE_TEXTURE "EmissiveTexture" +#define UNIFORM_AMBIENT_OCCLUSION_TEXTURE "AmbientOcclusionTexture" +#define UNIFORM_NORMAL_MAP "NormalMap" + +// Shader compiler defines. Must match the names in shaders. +#define DEFINE_HAS_TEXCOORDS "HAS_TEXCOORDS" +#define DEFINE_HAS_NORMALS "HAS_NORMALS" +#define DEFINE_HAS_TANGENTS "HAS_TANGENTS" +#define DEFINE_HAS_ALBEDO_MAP "HAS_ALBEDO_MAP" +#define DEFINE_HAS_METALLIC_ROUGHNESS_MAP "HAS_METALLIC_ROUGHNESS_MAP" +#define DEFINE_HAS_NORMAL_MAP "HAS_NORMAL_MAP" +#define DEFINE_HAS_OCCLUSION_MAP "HAS_OCCLUSION_MAP" +#define DEFINE_HAS_EMISSIVE_MAP "HAS_EMISSIVE_MAP" +#define DEFINE_HAS_JOINTS "HAS_JOINTS" +#define DEFINE_MAX_JOINTS "MAX_JOINTS" + +typedef enum TextureType { + BaseColorTexture, + MetallicRoughnessTexture, + EmissiveTexture, + AmbientOcclusionTexture, + NormalMap, +} TextureType; + +/// Describes the properties of a mesh. +/// This is used to create shader permutations. +typedef struct MeshPermutation { + union { + struct { + // Vertex attributes. + bool has_texcoords : 1; + bool has_normals : 1; + bool has_tangents : 1; + bool has_joints : 1; + bool has_weights : 1; + // Textures. + bool has_albedo_map : 1; + bool has_metallic_roughness_map : 1; + bool has_normal_map : 1; + bool has_occlusion_map : 1; + bool has_emissive_map : 1; + }; + int32_t all; + }; +} MeshPermutation; + +/// Build shader compiler defines from a mesh permutation. +static size_t make_defines( + MeshPermutation perm, ShaderCompilerDefine* defines) { + static const char* str_true = "1"; + size_t next = 0; + +#define check(field, define) \ + if (perm.field) { \ + defines[next].name = sstring_make(define); \ + defines[next].value = sstring_make(str_true); \ + next++; \ + } + check(has_texcoords, DEFINE_HAS_TEXCOORDS); + check(has_normals, DEFINE_HAS_NORMALS); + check(has_tangents, DEFINE_HAS_TANGENTS); + check(has_joints, DEFINE_HAS_JOINTS); + check(has_albedo_map, DEFINE_HAS_ALBEDO_MAP); + check(has_metallic_roughness_map, DEFINE_HAS_METALLIC_ROUGHNESS_MAP); + check(has_normal_map, DEFINE_HAS_NORMAL_MAP); + check(has_occlusion_map, DEFINE_HAS_OCCLUSION_MAP); + check(has_emissive_map, DEFINE_HAS_EMISSIVE_MAP); + + if (perm.has_joints) { + defines[next].name = sstring_make(DEFINE_MAX_JOINTS); + defines[next].value = sstring_itoa(GFX_MAX_NUM_JOINTS); + next++; + } + + return next; +} + +/// Compile a shader permutation. +static ShaderProgram* make_shader_permutation( + GfxCore* gfxcore, MeshPermutation perm) { + LOGD( + "Compiling Cook-Torrance shader permutation: texcoords: %d, normals: " + "%d, tangents: %d, joints: %d, weights: %d, albedo map: %d, " + "metallic-roughness map: " + "%d, normal " + "map: %d, AO map: %d, emissive map: %d", + perm.has_texcoords, perm.has_normals, perm.has_tangents, perm.has_joints, + perm.has_weights, perm.has_albedo_map, perm.has_metallic_roughness_map, + perm.has_normal_map, perm.has_occlusion_map, perm.has_emissive_map); + + ShaderCompilerDefine defines[GFX_MAX_SHADER_COMPILER_DEFINES]; + const size_t num_defines = make_defines(perm, defines); + return gfx_make_cook_torrance_shader_perm(gfxcore, defines, num_defines); +} + +/// Map a texture type to the name of the shader uniform used to access the +/// texture. +static const char* get_texture_uniform_name(TextureType type) { + switch (type) { + case BaseColorTexture: + return UNIFORM_BASE_COLOR_TEXTURE; + case MetallicRoughnessTexture: + return UNIFORM_METALLIC_ROUGHNESS_TEXTURE; + case EmissiveTexture: + return UNIFORM_EMISSIVE_TEXTURE; + case AmbientOcclusionTexture: + return UNIFORM_AMBIENT_OCCLUSION_TEXTURE; + case NormalMap: + return UNIFORM_NORMAL_MAP; + } + assert(false); + return 0; +} + +/// Map a glTF primitive type to a gfx primitive type. +static PrimitiveType from_gltf_primitive_type(cgltf_primitive_type type) { + switch (type) { + case cgltf_primitive_type_triangles: + return Triangles; + case cgltf_primitive_type_triangle_fan: + return TriangleFan; + case cgltf_primitive_type_triangle_strip: + return TriangleStrip; + // Not yet implemented. + case cgltf_primitive_type_lines: + case cgltf_primitive_type_line_loop: + case cgltf_primitive_type_line_strip: + case cgltf_primitive_type_points: + break; + } + LOGE("Unsupported primitive type: %d", type); + assert(false); + return 0; +} + +/// Map a glTF animation path type to its Gfx equivalent. +static ChannelType from_gltf_animation_path_type( + cgltf_animation_path_type type) { + switch (type) { + case cgltf_animation_path_type_translation: + return TranslationChannel; + case cgltf_animation_path_type_rotation: + return RotationChannel; + case cgltf_animation_path_type_scale: + return ScaleChannel; + case cgltf_animation_path_type_weights: + return WeightsChannel; + case cgltf_animation_path_type_invalid: + assert(false); + break; + } + assert(false); + return 0; +} + +/// Map a glTF interpolation to its Gfx equivalent. +static AnimationInterpolation from_gltf_interpolation_type( + cgltf_interpolation_type type) { + switch (type) { + case cgltf_interpolation_type_linear: + return LinearInterpolation; + case cgltf_interpolation_type_step: + return StepInterpolation; + case cgltf_interpolation_type_cubic_spline: + return CubicSplineInterpolation; + } + assert(false); + return 0; +} + +/// Return the component's size in bytes. +static cgltf_size get_component_size(cgltf_component_type type) { + switch (type) { + case cgltf_component_type_r_8: + return 1; + case cgltf_component_type_r_8u: + return 1; + case cgltf_component_type_r_16: + return 2; + case cgltf_component_type_r_16u: + return 2; + case cgltf_component_type_r_32u: + return 4; + case cgltf_component_type_r_32f: + return 4; + case cgltf_component_type_invalid: + assert(false); + break; + } + assert(false); + return 0; +} + +/// Return the number dimensionality of the given data type. +int get_num_dimensions(cgltf_type type) { + switch (type) { + case cgltf_type_scalar: + return 1; + case cgltf_type_vec2: + return 2; + case cgltf_type_vec3: + return 3; + case cgltf_type_vec4: + return 4; + case cgltf_type_mat2: + return 4; // 2x2 + case cgltf_type_mat3: + return 9; // 3x3 + case cgltf_type_mat4: + return 16; // 4x4 + case cgltf_type_invalid: + FAIL(); + break; + } + FAIL(); + return 0; +} + +/// Read an int64 from the given data pointer and accessor. +/// The largest integer in glTF is u32, so we can fit all integers in an int64. +static int64_t read_int(const void* component, const cgltf_accessor* accessor) { + assert(component); + assert(accessor); + + switch (accessor->component_type) { + case cgltf_component_type_r_8: { + const int8_t c = *((int8_t*)component); + return c; + } + case cgltf_component_type_r_8u: { + const uint8_t c = *((uint8_t*)component); + return c; + } + case cgltf_component_type_r_16: { + const int16_t c = *((int16_t*)component); + return c; + } + case cgltf_component_type_r_16u: { + const uint16_t c = *((uint16_t*)component); + return c; + } + case cgltf_component_type_r_32u: { + const uint32_t c = *((uint32_t*)component); + return c; + } + case cgltf_component_type_r_32f: { + const float c = *((float*)component); + return (int64_t)c; + } + case cgltf_component_type_invalid: + FAIL(); + break; + } + FAIL(); + return 0; +} + +/// Read a float from the given data pointer and accessor. +/// +/// This function uses the normalization equations from the spec. See the +/// animation section: +/// +/// https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#animations +static float read_float(const void* component, const cgltf_accessor* accessor) { + assert(component); + assert(accessor); + + switch (accessor->component_type) { + case cgltf_component_type_r_8: { + // assert(accessor->normalized); + const int8_t c = *((int8_t*)component); + return max((float)c / 127.0, -1.0); + } + case cgltf_component_type_r_8u: { + // assert(accessor->normalized); + const uint8_t c = *((uint8_t*)component); + return (float)c / 255.0; + } + case cgltf_component_type_r_16: { + // assert(accessor->normalized); + const int16_t c = *((int16_t*)component); + return max((float)c / 32767.0, -1.0); + } + case cgltf_component_type_r_16u: { + // assert(accessor->normalized); + const uint16_t c = *((uint16_t*)component); + return (float)c / 65535.0; + } + case cgltf_component_type_r_32u: { + // assert(accessor->normalized); + const uint32_t c = *((uint32_t*)component); + return (float)c / 4294967295.0; + } + case cgltf_component_type_r_32f: { + const float c = *((float*)component); + return c; + } + case cgltf_component_type_invalid: + FAIL(); + break; + } + FAIL(); + return 0; +} + +typedef struct AccessorIter { + const cgltf_accessor* accessor; + const uint8_t* next_element; + cgltf_size comp_size; // Component size in bytes. + cgltf_size stride; // ELement stride in bytes. + cgltf_size index; // Index of the next element. + bool is_matrix; +} AccessorIter; + +typedef struct AccessorData { + union { + struct { + float x, y, z, w; // Possibly normalized. + int64_t xi, yi, zi, wi; // Always unnormalized. + }; + const float* floats; + }; +} AccessorData; + +bool accessor_iter_next(AccessorIter* iter, AccessorData* data) { + assert(iter); + assert(data); + + if (iter->index < iter->accessor->count) { + const int dimensions = get_num_dimensions(iter->accessor->type); + const uint8_t* component = iter->next_element; + + // So that the caller can access the element's components as an array. + data->floats = (const float*)component; + + if (!iter->is_matrix) { // Scalar or vector. + // x + data->x = read_float(component, iter->accessor); + data->xi = read_int(component, iter->accessor); + component += iter->comp_size; + // y + if (dimensions > 1) { + data->y = read_float(component, iter->accessor); + data->yi = read_int(component, iter->accessor); + component += iter->comp_size; + } + // z + if (dimensions > 2) { + data->z = read_float(component, iter->accessor); + data->zi = read_int(component, iter->accessor); + component += iter->comp_size; + } + // w + if (dimensions > 3) { + data->w = read_float(component, iter->accessor); + data->wi = read_int(component, iter->accessor); + component += iter->comp_size; + } + } + + iter->next_element += iter->stride; + iter->index++; + return true; + } + + return false; +} + +AccessorIter make_accessor_iter(const cgltf_accessor* accessor) { + assert(accessor); + + const bool is_matrix = (accessor->type == cgltf_type_mat2) || + (accessor->type == cgltf_type_mat3) || + (accessor->type == cgltf_type_mat4); + + const int dimensions = get_num_dimensions(accessor->type); + assert( + ((dimensions == 1) && (accessor->type == cgltf_type_scalar)) || + ((dimensions == 2) && (accessor->type == cgltf_type_vec2)) || + ((dimensions == 3) && (accessor->type == cgltf_type_vec3)) || + ((dimensions == 4) && (accessor->type == cgltf_type_vec4)) || + ((dimensions == 4) && (accessor->type == cgltf_type_mat2)) || + ((dimensions == 9) && (accessor->type == cgltf_type_mat3)) || + ((dimensions == 16) && (accessor->type == cgltf_type_mat4))); + + const cgltf_buffer_view* view = accessor->buffer_view; + const cgltf_buffer* buffer = view->buffer; + const cgltf_size offset = accessor->offset + view->offset; + const uint8_t* bytes = (const uint8_t*)buffer->data + offset; + // Component size in bytes. + const cgltf_size comp_size = get_component_size(accessor->component_type); + // Element size in bytes. + const cgltf_size elem_size = dimensions * comp_size; + // Stride in bytes. If the view stride is 0, then the elements are tightly + // packed. + const cgltf_size stride = view->stride != 0 ? view->stride : elem_size; + + // There isn't an accessor stride in the spec, but cgltf still specifies one. + assert(accessor->stride == elem_size); + + // Accessor data must fit inside the view. + assert(accessor->offset + (accessor->count * accessor->stride) <= view->size); + + // Accessor data must fit inside the buffer. + assert( + (offset + (accessor->count * elem_size) + + ((accessor->count - 1) * view->stride)) <= buffer->size); + + return (AccessorIter){ + .accessor = accessor, + .next_element = bytes, + .comp_size = comp_size, + .stride = stride, + .index = 0, + .is_matrix = is_matrix, + }; +} + +/// Return the total number of primitives in the scene. Each mesh may contain +/// multiple primitives. +/// +/// Note that this function scans all of the scenes in the glTF data. +static size_t get_total_primitives(const cgltf_data* data) { + size_t total = 0; + for (cgltf_size i = 0; i < data->meshes_count; ++i) { + total += data->meshes[i].primitives_count; + } + return total; +} + +/// Load all buffers from the glTF scene. +/// +/// If buffer data is loaded from memory, set filepath = null. +/// +/// Return an array of Buffers such that the index of each glTF buffer in the +/// original array matches the same Buffer in the resulting array. +/// +/// TODO: There is no need to load the inverse bind matrices buffer into the +/// GPU. Might need to lazily load buffers. +static bool load_buffers( + const cgltf_data* data, GfxCore* gfxcore, Buffer** buffers) { + assert(data); + assert(gfxcore); + assert(buffers); + + for (cgltf_size i = 0; i < data->buffers_count; ++i) { + const cgltf_buffer* buffer = &data->buffers[i]; + assert(buffer->data); + buffers[i] = gfx_make_buffer( + gfxcore, &(BufferDesc){ + .usage = BufferStatic, + .type = BufferUntyped, + .data.data = buffer->data, + .data.count = buffer->size}); + if (!buffers[i]) { + return false; + } + } + + return true; +} + +/// Load tangent buffers. +static bool load_tangent_buffers( + const cgltfTangentBuffer* cgltf_tangent_buffers, + cgltf_size num_tangent_buffers, GfxCore* gfxcore, + Buffer** tangent_buffers) { + assert(cgltf_tangent_buffers); + assert(gfxcore); + assert(tangent_buffers); + + for (cgltf_size i = 0; i < num_tangent_buffers; ++i) { + const cgltfTangentBuffer* buffer = &cgltf_tangent_buffers[i]; + assert(buffer->data); + tangent_buffers[i] = gfx_make_buffer( + gfxcore, &(BufferDesc){ + .usage = BufferStatic, + .type = BufferUntyped, + .data.data = buffer->data, + .data.count = buffer->size_bytes}); + if (!tangent_buffers[i]) { + return false; + } + } + + return true; +} + +/// Lazily load all textures from the glTF scene. +/// +/// Colour textures like albedo are in sRGB colour space. Non-colour textures +/// like normal maps are in linear space (e.g. DamagedHelmet sample). Since we +/// don't know how the texture is going to be used at this point, we can't tell +/// what colour space it should be loaded in (ideally this would be part of the +/// image file format, but not all formats specify colour space.) Therefore, we +/// load the textures lazily and don't actually commit them to GPU memory until +/// we know their colour space when loading glTF materials. +/// +/// Return an array of LoadTextureCmds such that the index of each cmd matches +/// the index of each glTF texture in the scene. +static void load_textures_lazy( + const cgltf_data* data, GfxCore* gfxcore, const char* directory, + LoadTextureCmd* load_texture_cmds) { + assert(data); + assert(gfxcore); + assert(load_texture_cmds); + + for (cgltf_size i = 0; i < data->textures_count; ++i) { + const cgltf_texture* texture = &data->textures[i]; + const cgltf_image* image = texture->image; + const cgltf_sampler* sampler = texture->sampler; + + // glTF models might not specify a sampler. In such case, the client can + // pick its own defaults. + // https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#samplers + bool mipmaps = true; + TextureFiltering filtering = LinearFiltering; + TextureWrapping wrap = Repeat; + + if (sampler) { + // The gfx library does not distinguish between sampling the texture and + // combining the mipmap levels. + const cgltf_int filter = + sampler->min_filter == 0 ? sampler->mag_filter : sampler->min_filter; + + switch (filter) { + case GL_NEAREST_MIPMAP_NEAREST: + mipmaps = true; + filtering = NearestFiltering; + break; + case GL_NEAREST_MIPMAP_LINEAR: + case GL_LINEAR_MIPMAP_NEAREST: + case GL_LINEAR_MIPMAP_LINEAR: + mipmaps = true; + filtering = LinearFiltering; + break; + case GL_NEAREST: + filtering = NearestFiltering; + break; + case GL_LINEAR: + filtering = LinearFiltering; + break; + default: + break; + } + } + + // Currently only supporting loading textures from files. + assert(image->uri); + assert(directory); + mstring fullpath = + mstring_concat_path(mstring_make(directory), mstring_make(image->uri)); + + load_texture_cmds[i] = (LoadTextureCmd){ + .origin = AssetFromFile, + .type = LoadTexture, + .colour_space = sRGB, + .filtering = filtering, + .wrap = wrap, + .mipmaps = mipmaps, + .data.texture.filepath = fullpath}; + } +} + +/// Load a texture uniform. +/// +/// This determines a texture's colour space based on its intended use, loads +/// the texture, and then defines the sampler shader uniform. +static bool load_texture_and_uniform( + const cgltf_data* data, Gfx* gfx, const cgltf_texture_view* texture_view, + TextureType texture_type, const Texture** textures, + LoadTextureCmd* load_texture_cmds, int* next_uniform, MaterialDesc* desc) { + assert(data); + assert(gfx); + assert(texture_view); + assert(textures); + assert(next_uniform); + assert(desc); + assert(*next_uniform < GFX_MAX_UNIFORMS_PER_MATERIAL); + + const size_t texture_index = texture_view->texture - data->textures; + assert(texture_index < data->textures_count); + + // Here we are assuming that if a texture is re-used, it is re-used with the + // same texture view. This should be fine because, e.g., a normal map would + // not be used as albedo and vice versa. + if (!textures[texture_index]) { + LoadTextureCmd* cmd = &load_texture_cmds[texture_index]; + // TODO: Check for colour textures and default to LinearColourSpace instead. + if (texture_type == NormalMap) { + cmd->colour_space = LinearColourSpace; + } + + LOGD( + "Load texture: %s (mipmaps: %d, filtering: %d)", + mstring_cstr(&cmd->data.texture.filepath), cmd->mipmaps, + cmd->filtering); + + textures[texture_index] = gfx_load_texture(gfx, cmd); + if (!textures[texture_index]) { + log_error( + "Failed to load texture: %s", + mstring_cstr(&cmd->data.texture.filepath)); + return false; + } + } + + assert(*next_uniform < GFX_MAX_UNIFORMS_PER_MATERIAL); + desc->uniforms[(*next_uniform)++] = (ShaderUniform){ + .name = sstring_make(get_texture_uniform_name(texture_type)), + .type = UniformTexture, + .value.texture = textures[texture_index]}; + + return true; +} + +/// Load all materials from the glTF scene. +/// +/// Return an array of Materials such that the index of each descriptor matches +/// the index of each glTF material in the scene. Also return the number of +/// materials and the textures used by them. +static bool load_materials( + const cgltf_data* data, Gfx* gfx, LoadTextureCmd* load_texture_cmds, + const Texture** textures, Material** materials) { + assert(data); + assert(gfx); + assert(materials); + if (data->textures_count > 0) { + assert(load_texture_cmds); + assert(textures); + } + + for (cgltf_size i = 0; i < data->materials_count; ++i) { + const cgltf_material* mat = &data->materials[i]; + + int next_uniform = 0; + MaterialDesc desc = {0}; + + // TODO: specular/glossiness and other material parameters. + if (mat->has_pbr_metallic_roughness) { + const cgltf_pbr_metallic_roughness* pbr = &mat->pbr_metallic_roughness; + + assert(next_uniform < GFX_MAX_UNIFORMS_PER_MATERIAL); + desc.uniforms[next_uniform++] = (ShaderUniform){ + .name = sstring_make(UNIFORM_BASE_COLOR_FACTOR), + .type = UniformVec4, + .value.vec4 = vec4_from_array(pbr->base_color_factor)}; + + assert(next_uniform < GFX_MAX_UNIFORMS_PER_MATERIAL); + desc.uniforms[next_uniform++] = (ShaderUniform){ + .name = sstring_make(UNIFORM_METALLIC_FACTOR), + .type = UniformFloat, + .value.scalar = pbr->metallic_factor}; + + assert(next_uniform < GFX_MAX_UNIFORMS_PER_MATERIAL); + desc.uniforms[next_uniform++] = (ShaderUniform){ + .name = sstring_make(UNIFORM_ROUGHNESS_FACTOR), + .type = UniformFloat, + .value.scalar = pbr->roughness_factor}; + + assert(next_uniform < GFX_MAX_UNIFORMS_PER_MATERIAL); + desc.uniforms[next_uniform++] = (ShaderUniform){ + .name = sstring_make(UNIFORM_EMISSIVE_FACTOR), + .type = UniformVec3, + .value.vec3 = vec3_from_array(mat->emissive_factor)}; + + if (pbr->base_color_texture.texture) { + if (!load_texture_and_uniform( + data, gfx, &pbr->base_color_texture, BaseColorTexture, textures, + load_texture_cmds, &next_uniform, &desc)) { + return false; + } + } + + if (pbr->metallic_roughness_texture.texture) { + if (!load_texture_and_uniform( + data, gfx, &pbr->metallic_roughness_texture, + MetallicRoughnessTexture, textures, load_texture_cmds, + &next_uniform, &desc)) { + return false; + } + } + } + + if (mat->emissive_texture.texture) { + if (!load_texture_and_uniform( + data, gfx, &mat->emissive_texture, EmissiveTexture, textures, + load_texture_cmds, &next_uniform, &desc)) { + return false; + } + } + + if (mat->occlusion_texture.texture) { + if (!load_texture_and_uniform( + data, gfx, &mat->occlusion_texture, AmbientOcclusionTexture, + textures, load_texture_cmds, &next_uniform, &desc)) { + return false; + } + } + + if (mat->normal_texture.texture) { + if (!load_texture_and_uniform( + data, gfx, &mat->normal_texture, NormalMap, textures, + load_texture_cmds, &next_uniform, &desc)) { + return false; + } + } + + assert(next_uniform < GFX_MAX_UNIFORMS_PER_MATERIAL); + desc.num_uniforms = next_uniform; + + materials[i] = gfx_make_material(&desc); + if (!materials[i]) { + return false; + } + } + + return true; +} + +/// Create a default material for meshes that do not have a material. +static Material* make_default_material() { + MaterialDesc desc = (MaterialDesc){0}; + + assert(desc.num_uniforms < GFX_MAX_UNIFORMS_PER_MATERIAL); + desc.uniforms[desc.num_uniforms++] = (ShaderUniform){ + .name = sstring_make(UNIFORM_BASE_COLOR_FACTOR), + .type = UniformVec4, + .value.vec4 = vec4_make(1, 1, 1, 1)}; + + assert(desc.num_uniforms < GFX_MAX_UNIFORMS_PER_MATERIAL); + desc.uniforms[desc.num_uniforms++] = (ShaderUniform){ + .name = sstring_make(UNIFORM_METALLIC_FACTOR), + .type = UniformFloat, + .value.scalar = 0}; + + assert(desc.num_uniforms < GFX_MAX_UNIFORMS_PER_MATERIAL); + desc.uniforms[desc.num_uniforms++] = (ShaderUniform){ + .name = sstring_make(UNIFORM_ROUGHNESS_FACTOR), + .type = UniformFloat, + .value.scalar = 1}; + + assert(desc.num_uniforms < GFX_MAX_UNIFORMS_PER_MATERIAL); + desc.uniforms[desc.num_uniforms++] = (ShaderUniform){ + .name = sstring_make(UNIFORM_EMISSIVE_FACTOR), + .type = UniformVec3, + .value.vec3 = vec3_make(0, 0, 0)}; + + return gfx_make_material(&desc); +} + +/// Compute the bounding box of the vertices pointed to by the accessor. +/// 'dim' is the dimension of the vertices (2D or 3D). +aabb3 compute_aabb(const cgltf_accessor* accessor) { + aabb3 box = {0}; + if (accessor->has_min && accessor->has_max) { + box = aabb3_make( + vec3_from_array(accessor->min), vec3_from_array(accessor->max)); + } else { + AccessorIter iter = make_accessor_iter(accessor); + AccessorData vertex = {0}; + cgltf_size i = 0; + + while (accessor_iter_next(&iter, &vertex)) { + const vec3 p = vec3_make(vertex.x, vertex.y, vertex.z); + if (i == 0) { + box = aabb3_make(p, p); + } else { + box = aabb3_add(box, p); + } + ++i; + } + } + return box; +} + +/// Load all meshes from the glTF scene. +static bool load_meshes( + const cgltf_data* data, GfxCore* gfxcore, Buffer** buffers, + Buffer** tangent_buffers, const cgltfTangentBuffer* cgltf_tangent_buffers, + cgltf_size num_tangent_buffers, Material** materials, + ShaderProgram* const shader, size_t primitive_count, Geometry** geometries, + Mesh** meshes, SceneObject** scene_objects) { + // Walk through the mesh primitives to create Meshes. A GLTF mesh primitive + // has a material (Mesh) and vertex data (Geometry). A GLTF mesh maps to + // a SceneObject. + // + // glTF gfx + // ---- --- + // Mesh SceneObject + // Mesh primitive Mesh / Geometry + // Accessor + buffer view BufferView + // Buffer Buffer + assert(data); + assert(gfxcore); + assert(buffers); + assert(materials); + assert(geometries); + assert(meshes); + assert(scene_objects); + if (num_tangent_buffers > 0) { + assert(tangent_buffers); + assert(cgltf_tangent_buffers); + } + + // Points to the next available Mesh and also the next available Geometry. + // There is one (Mesh, Geometry) pair per glTF mesh primitive. + size_t next_mesh = 0; + + for (cgltf_size m = 0; m < data->meshes_count; ++m) { + const cgltf_mesh* mesh = &data->meshes[m]; + + ObjectDesc object_desc = {0}; + + for (cgltf_size p = 0; p < mesh->primitives_count; ++p) { + assert(next_mesh < primitive_count); + const cgltf_primitive* prim = &mesh->primitives[p]; + const cgltf_material* mat = prim->material; + + MeshPermutation perm = {0}; + if (mat) { + perm.has_normal_map = mat->normal_texture.texture != 0; + perm.has_occlusion_map = mat->occlusion_texture.texture != 0; + perm.has_emissive_map = mat->emissive_texture.texture != 0; + + if (mat->has_pbr_metallic_roughness) { + const cgltf_pbr_metallic_roughness* pbr = + &mat->pbr_metallic_roughness; + perm.has_albedo_map = pbr->base_color_texture.texture != 0; + perm.has_metallic_roughness_map = + pbr->metallic_roughness_texture.texture != 0; + } else { + // TODO: specular/glossiness and other material parameters. + } + } + + GeometryDesc geometry_desc = { + .type = from_gltf_primitive_type(prim->type), + .buffer_usage = BufferStatic}; + + // Vertex indices. + if (prim->indices) { + const cgltf_accessor* accessor = prim->indices; + const cgltf_buffer_view* view = prim->indices->buffer_view; + const cgltf_size buffer_index = view->buffer - data->buffers; + + assert(buffer_index < data->buffers_count); + Buffer* buffer = buffers[buffer_index]; + + const cgltf_size component_size = + get_component_size(accessor->component_type); + switch (component_size) { + case 1: { + BufferViewIdx8* indices = &geometry_desc.indices8; + // TODO: discards const qualifier. + indices->buffer = buffer; + indices->offset_bytes = accessor->offset + view->offset; + indices->size_bytes = view->size; + indices->stride_bytes = view->stride; + geometry_desc.num_indices = prim->indices->count; + break; + } + case 2: { + BufferViewIdx16* indices = &geometry_desc.indices16; + indices->buffer = buffer; + indices->offset_bytes = accessor->offset + view->offset; + indices->size_bytes = view->size; + indices->stride_bytes = view->stride; + geometry_desc.num_indices = prim->indices->count; + break; + } + default: + // TODO: Handle 32-bit indices. + assert(false); + break; + } + } + + // Vertex attributes. + for (cgltf_size a = 0; a < prim->attributes_count; ++a) { + const cgltf_attribute* attrib = &prim->attributes[a]; + const cgltf_accessor* accessor = attrib->data; + const cgltf_buffer_view* view = accessor->buffer_view; + const cgltf_size offset = accessor->offset + view->offset; + const cgltf_size buffer_index = view->buffer - data->buffers; + + assert(buffer_index < data->buffers_count); + Buffer* buffer = buffers[buffer_index]; + + BufferView2d* buffer_view_2d = 0; + BufferView3d* buffer_view_3d = 0; + BufferView4d* buffer_view_4d = 0; + BufferViewFloat* buffer_view_float = 0; + BufferViewU8* buffer_view_u8 = 0; + BufferViewU16* buffer_view_u16 = 0; + + switch (attrib->type) { + case cgltf_attribute_type_position: { + switch (accessor->type) { + case cgltf_type_vec2: + assert(geometry_desc.positions3d.buffer == 0); + buffer_view_2d = &geometry_desc.positions2d; + geometry_desc.aabb = compute_aabb(accessor); + break; + case cgltf_type_vec3: + assert(geometry_desc.positions2d.buffer == 0); + buffer_view_3d = &geometry_desc.positions3d; + geometry_desc.aabb = compute_aabb(accessor); + break; + default: + FAIL( + "Unhandled accessor type %d in vertex positions", + accessor->type); + assert(false); + return false; + } + // It is assumed that meshes have positions, so there is nothing to + // do for the mesh permutation in this case. + break; + } + case cgltf_attribute_type_normal: + buffer_view_3d = &geometry_desc.normals; + perm.has_normals = true; + break; + case cgltf_attribute_type_tangent: + buffer_view_4d = &geometry_desc.tangents; + perm.has_tangents = true; + break; + case cgltf_attribute_type_texcoord: + buffer_view_2d = &geometry_desc.texcoords; + perm.has_texcoords = true; + break; + case cgltf_attribute_type_color: + // TODO: Add support for color. + break; + case cgltf_attribute_type_joints: + // Joints can be either u8 or u16. + switch (accessor->component_type) { + case cgltf_component_type_r_8u: + buffer_view_u8 = &geometry_desc.joints.u8; + break; + case cgltf_component_type_r_16u: + buffer_view_u16 = &geometry_desc.joints.u16; + break; + default: + assert(false); + return false; + } + perm.has_joints = true; + break; + case cgltf_attribute_type_weights: + // Weights can be either u8, u16, or float. + switch (accessor->component_type) { + case cgltf_component_type_r_8u: + buffer_view_u8 = &geometry_desc.weights.u8; + break; + case cgltf_component_type_r_16u: + buffer_view_u16 = &geometry_desc.weights.u16; + break; + case cgltf_component_type_r_32f: + buffer_view_float = &geometry_desc.weights.floats; + break; + default: + assert(false); + return false; + } + perm.has_weights = true; + break; + case cgltf_attribute_type_invalid: + assert(false); + break; + } + +#define CONFIGURE_BUFFER(buf) \ + if (buf) { \ + buf->buffer = buffer; \ + buf->offset_bytes = offset; \ + buf->size_bytes = view->size; \ + buf->stride_bytes = view->stride; \ + } + CONFIGURE_BUFFER(buffer_view_2d); + CONFIGURE_BUFFER(buffer_view_3d); + CONFIGURE_BUFFER(buffer_view_4d); + CONFIGURE_BUFFER(buffer_view_u8); + CONFIGURE_BUFFER(buffer_view_u16); + CONFIGURE_BUFFER(buffer_view_float); + } // Vertex attributes. + + assert( + (perm.has_joints && perm.has_weights) || + (!perm.has_joints && !perm.has_weights)); + + // If the mesh primitive has no tangents, see if they were computed + // separately. + if (!geometry_desc.tangents.buffer) { + for (cgltf_size t = 0; t < num_tangent_buffers; ++t) { + const cgltfTangentBuffer* cgltf_buffer = &cgltf_tangent_buffers[t]; + + if (cgltf_buffer->primitive == prim) { + BufferView4d* view = &geometry_desc.tangents; + view->buffer = tangent_buffers[t]; + view->offset_bytes = 0; + view->size_bytes = cgltf_buffer->size_bytes; + view->stride_bytes = 0; // Tightly packed. + break; + } + } + } + + // Set the number of vertices in the geometry. Since a geometry can have + // either 2d or 3d positions but not both, here we can perform addition + // to compute the total number of vertices. + geometry_desc.num_verts = + (geometry_desc.positions2d.size_bytes / sizeof(vec2)) + + (geometry_desc.positions3d.size_bytes / sizeof(vec3)); + +#define CHECK_COUNT(buffer_view, type, num_components) \ + if (geometry_desc.buffer_view.buffer) { \ + assert( \ + (geometry_desc.buffer_view.size_bytes / \ + (num_components * sizeof(type))) == geometry_desc.num_verts); \ + } + + // Check that the number of vertices is consistent across all vertex + // attributes. + CHECK_COUNT(normals, vec3, 1); + CHECK_COUNT(tangents, vec4, 1); + CHECK_COUNT(texcoords, vec2, 1); + CHECK_COUNT(joints.u8, uint8_t, 4); + CHECK_COUNT(joints.u16, uint16_t, 4); + CHECK_COUNT(weights.u8, uint8_t, 4); + CHECK_COUNT(weights.u16, uint16_t, 4); + CHECK_COUNT(weights.floats, float, 4); + + Material* material = 0; + if (mat) { + const cgltf_size material_index = mat - data->materials; + assert(material_index < data->materials_count); + material = materials[material_index]; + } else { + // Create a default material for meshes that do not specify one. + material = make_default_material(); + } + assert(material); + + geometries[next_mesh] = gfx_make_geometry(gfxcore, &geometry_desc); + if (!geometries[next_mesh]) { + return false; + } + + // If the user specifies a custom shader, use that instead. Otherwise + // compile a shader based on the mesh's permutation. + // + // Note that Gfx takes care of caching shaders and shader programs. + // + // Caching materials could be useful, but, provided they can share + // shaders, the renderer can check later whether uniforms have the same + // values. Also, changing uniforms is much faster than swapping shaders, + // so shader caching is the most important thing here. + ShaderProgram* mesh_shader = + shader ? shader : make_shader_permutation(gfxcore, perm); + assert(mesh_shader); + + meshes[next_mesh] = gfx_make_mesh(&(MeshDesc){ + .geometry = geometries[next_mesh], + .material = material, + .shader = mesh_shader}); + + if (!meshes[next_mesh]) { + return false; + } + + assert(object_desc.num_meshes < GFX_MAX_NUM_MESHES); + object_desc.meshes[object_desc.num_meshes] = meshes[next_mesh]; + object_desc.num_meshes++; + + ++next_mesh; + } // glTF mesh primitive / gfx Mesh. + + scene_objects[m] = gfx_make_object(&object_desc); + if (!scene_objects[m]) { + return false; + } + } // glTF mesh / gfx SceneObject. + + return true; +} + +/// Compute bounding boxes for the joints in the model. +static void compute_joint_bounding_boxes( + const cgltf_data* data, size_t num_joints, JointDesc* joint_descs) { + assert(data); + assert(joint_descs); + assert(num_joints <= GFX_MAX_NUM_JOINTS); + + // Initialize bounding boxes so that we can compute unions below. + for (size_t i = 0; i < num_joints; ++i) { + joint_descs[i].box = aabb3_make_empty(); + } + + // Iterate over the meshes -> primitives -> vertices -> joint indices, and add + // the vertex to the joint's bounding box. + for (cgltf_size n = 0; n < data->nodes_count; ++n) { + const cgltf_node* node = &data->nodes[n]; + + if (node->skin) { + if (node->mesh) { + const cgltf_mesh* mesh = node->mesh; + + for (cgltf_size pr = 0; pr < mesh->primitives_count; ++pr) { + const cgltf_primitive* prim = &mesh->primitives[pr]; + + // Find the indices of the positions and joints arrays in the + // primitive's attributes. + int positions_index = -1; + int joints_index = -1; + for (int a = 0; a < (int)prim->attributes_count; ++a) { + const cgltf_attribute* attrib = &prim->attributes[a]; + + if (attrib->type == cgltf_attribute_type_position) { + positions_index = a; + } else if (attrib->type == cgltf_attribute_type_joints) { + joints_index = a; + } + } + + if ((positions_index != -1) && (joints_index != -1)) { + const cgltf_accessor* positions = + prim->attributes[positions_index].data; + const cgltf_accessor* joints = prim->attributes[joints_index].data; + + assert(positions->count == joints->count); + + AccessorIter positions_iter = make_accessor_iter(positions); + AccessorIter joints_iter = make_accessor_iter(joints); + AccessorData position = {0}, joint = {0}; + + while (accessor_iter_next(&positions_iter, &position)) { + const bool advance = accessor_iter_next(&joints_iter, &joint); + assert(advance); // Counts should match. + + const vec3 p = vec3_make(position.x, position.y, position.z); + const int64_t j[4] = {joint.xi, joint.yi, joint.wi, joint.zi}; + + for (int i = 0; i < 4; ++i) { + const size_t joint_index = j[i]; + assert((size_t)joint_index < num_joints); + + joint_descs[joint_index].box = + aabb3_add(joint_descs[joint_index].box, p); + } + } + } + } + } + } + } +} + +/// Find the joint node with the smallest index across all skeletons. +/// +/// The channels in glTF may target arbitrary nodes in the scene (those nodes +/// are the joints). However, we want to map the "base joint" (the joint/node +/// with the smallest index) to 0 in the AnimaDesc's joint array. We can do this +/// by subtracting the "base node index" from every joint index or channel +/// target. +/// +/// There is an assumption in the animation library that joints are contiguous +/// anyway, so this "base joint index" works provided the joint nodes are also +/// contiguous in the glTF. The glTF does not guarantee this, but I think it's +/// a reasonable assumption that exporters write glTF files in such a way, and +/// Blender does appear to do so. +cgltf_size find_base_joint_index(const cgltf_data* data) { + assert(data); + + cgltf_size base_joint_index = (cgltf_size)-1; + + for (cgltf_size s = 0; s < data->skins_count; ++s) { + const cgltf_skin* skin = &data->skins[s]; + for (cgltf_size j = 0; j < skin->joints_count; ++j) { + // Joint is an index/pointer into the nodes array. + const cgltf_size node_index = skin->joints[j] - data->nodes; + assert(node_index < data->nodes_count); + // Min. + if (node_index < base_joint_index) { + base_joint_index = node_index; + } + } + } + + return base_joint_index; +} + +/// Load all skins (Gfx skeletons) from the glTF scene. +/// Return the total number of joints. +static size_t load_skins( + const cgltf_data* data, Buffer* const* buffers, cgltf_size base_joint_index, + AnimaDesc* anima_desc) { + assert(data); + assert(buffers); + assert(anima_desc); + assert(base_joint_index < data->nodes_count); + + // Determines whether the ith joint in the node hierarchy is a joint node. + // This is then used to determine whether a joint is a root of the joint + // hierarchy. + bool is_joint_node[GFX_MAX_NUM_JOINTS] = {false}; + + size_t num_joints = 0; + + for (cgltf_size s = 0; s < data->skins_count; ++s) { + const cgltf_skin* skin = &data->skins[s]; + const cgltf_accessor* matrices_accessor = skin->inverse_bind_matrices; + assert(matrices_accessor->count == skin->joints_count); + + num_joints += skin->joints_count; + assert(num_joints < GFX_MAX_NUM_JOINTS); + + SkeletonDesc* skeleton_desc = &anima_desc->skeletons[s]; + *skeleton_desc = (SkeletonDesc){.num_joints = skin->joints_count}; + + // for (cgltf_size j = 0; j < skin->joints_count; ++j) { + AccessorIter iter = make_accessor_iter(matrices_accessor); + AccessorData matrix = {0}; + for (cgltf_size i = 0; accessor_iter_next(&iter, &matrix); ++i) { + const mat4 inv_bind_matrix = mat4_from_array(matrix.floats); + + // Joint is an index/pointer into the nodes array. + const cgltf_size node_index = skin->joints[i] - data->nodes; + assert(node_index < data->nodes_count); + + const cgltf_size parent_node_index = + skin->joints[i]->parent - data->nodes; + assert(parent_node_index < data->nodes_count); + + // Subtract the base index to pack the joints as tightly as possible in + // the AnimaDesc. + assert(node_index >= base_joint_index); + const cgltf_size joint_index = node_index - base_joint_index; + + assert(parent_node_index >= base_joint_index); + const cgltf_size parent_index = parent_node_index - base_joint_index; + + skeleton_desc->joints[i] = joint_index; + + JointDesc* joint_desc = &anima_desc->joints[joint_index]; + joint_desc->parent = parent_index; + joint_desc->inv_bind_matrix = inv_bind_matrix; + + is_joint_node[joint_index] = true; + }; + + // glTF may specify a "skeleton", which is the root of the skin's + // (skeleton's) node hierarchy. + // if (skin->skeleton) { + // // cgltf_size root_index = skin->skeleton - data->nodes; + // // assert(root_index <= data->nodes_count); + // // root_node = nodes[root_index]; + // assert(false); + //} + } + + // Animation library assumes that joints are contiguous. + for (size_t i = 0; i < num_joints; ++i) { + assert(is_joint_node[i]); + } + + // Insert the root joint. + // This is the root of all skeletons. It is, specifically, the root of all + // joints that do not have a parent; skins (skeletons) in glTF are not + // guaranteed to have a common parent, but are generally a set of disjoint + // trees. + const size_t root_index = num_joints; + assert(root_index < GFX_MAX_NUM_JOINTS); + anima_desc->joints[root_index] = (JointDesc){.parent = INDEX_NONE}; + num_joints++; + + // Make root joints point to the root joint at index N. + // The root joints are the ones that have a non-joint node in the glTF as a + // parent. + for (size_t i = 0; i < root_index; ++i) { + JointDesc* joint = &anima_desc->joints[i]; + if ((joint->parent >= root_index) || !is_joint_node[joint->parent]) { + joint->parent = root_index; + } + } + + return num_joints; +} + +/// Load all animations from the glTF scene. +static void load_animations( + const cgltf_data* data, cgltf_size base_joint_index, + AnimaDesc* anima_desc) { + assert(data); + assert(anima_desc); + assert(base_joint_index < data->nodes_count); + assert(data->animations_count <= GFX_MAX_NUM_ANIMATIONS); + + for (cgltf_size a = 0; a < data->animations_count; ++a) { + const cgltf_animation* animation = &data->animations[a]; + AnimationDesc* animation_desc = &anima_desc->animations[a]; + + *animation_desc = (AnimationDesc){ + .name = sstring_make(animation->name), + .num_channels = animation->channels_count}; + + assert(animation->channels_count <= GFX_MAX_NUM_CHANNELS); + for (cgltf_size c = 0; c < animation->channels_count; ++c) { + const cgltf_animation_channel* channel = &animation->channels[c]; + ChannelDesc* channel_desc = &animation_desc->channels[c]; + const cgltf_animation_sampler* sampler = channel->sampler; + + const size_t target_index = channel->target_node - data->nodes; + assert(target_index < data->nodes_count); + + assert(target_index >= base_joint_index); + const size_t tight_target_index = target_index - base_joint_index; + assert(tight_target_index < anima_desc->num_joints); + + *channel_desc = (ChannelDesc){ + .target = tight_target_index, + .type = from_gltf_animation_path_type(channel->target_path), + .interpolation = from_gltf_interpolation_type(sampler->interpolation), + .num_keyframes = 0}; + + // Read time inputs. + AccessorIter iter = make_accessor_iter(sampler->input); + AccessorData input = {0}; + for (cgltf_size i = 0; accessor_iter_next(&iter, &input); ++i) { + channel_desc->keyframes[i].time = input.x; + channel_desc->num_keyframes++; + } + + // Read transform outputs. + AccessorData output = {0}; + switch (channel->target_path) { + case cgltf_animation_path_type_translation: { + iter = make_accessor_iter(sampler->output); + for (cgltf_size i = 0; accessor_iter_next(&iter, &output); ++i) { + channel_desc->keyframes[i].translation = + vec3_make(output.x, output.y, output.z); + } + break; + } + case cgltf_animation_path_type_rotation: { + iter = make_accessor_iter(sampler->output); + for (cgltf_size i = 0; accessor_iter_next(&iter, &output); ++i) { + channel_desc->keyframes[i].rotation = + qmake(output.x, output.y, output.z, output.w); + } + break; + } + default: + // TODO: Handle other channel transformations. + break; + } + } + } +} + +/// Load all nodes from the glTF scene. +/// +/// This function ignores the many scenes and default scene of the glTF spec +/// and instead just loads all nodes into a single gfx Scene. +static void load_nodes( + const cgltf_data* data, SceneNode* root_node, SceneObject** objects, + SceneCamera** cameras, const Anima* anima, SceneNode** nodes) { + // Note that with glTF 2.0, nodes do not form a DAG / scene graph but a + // disjount union of strict trees: + // + // "For Version 2.0 conformance, the glTF node hierarchy is not a directed + // acyclic graph (DAG) or scene graph, but a disjoint union of strict trees. + // That is, no node may be a direct descendant of more than one node. This + // restriction is meant to simplify implementation and facilitate + // conformance." + // + // This matches the gfx library implementation, where every node can have at + // most one parent. + assert(data); + assert(root_node); + assert(objects); + assert(cameras); + assert(nodes); + + cgltf_size next_camera = 0; + + for (cgltf_size n = 0; n < data->nodes_count; ++n) { + const cgltf_node* node = &data->nodes[n]; + + // Add SceneObject, SceneCamera or Lights. + // TODO: Handle lights once they are implemented in the gfx library. + if (node->mesh) { + const cgltf_size mesh_index = node->mesh - data->meshes; + assert(mesh_index < data->meshes_count); + SceneObject* object = objects[mesh_index]; + gfx_construct_object_node(nodes[n], object); + + if (node->skin) { + assert(anima); + + const cgltf_size skin_index = node->skin - data->skins; + assert(skin_index < data->skins_count); + const Skeleton* skeleton = gfx_get_anima_skeleton(anima, skin_index); + gfx_set_object_skeleton(object, skeleton); + } + } else if (node->camera) { + assert(next_camera < data->cameras_count); + + Camera camera; + const cgltf_camera* cam = node->camera; + + // TODO: We could define a function load_cameras() the same way we load + // every mesh and then remove this ad-hoc loading of cameras here, as well + // as remove 'next_camera'. + switch (cam->type) { + case cgltf_camera_type_orthographic: + camera = camera_orthographic( + 0, cam->data.orthographic.xmag, 0, cam->data.orthographic.ymag, + cam->data.orthographic.znear, cam->data.orthographic.zfar); + break; + case cgltf_camera_type_perspective: + camera = camera_perspective( + cam->data.perspective.yfov, cam->data.perspective.aspect_ratio, + cam->data.perspective.znear, cam->data.perspective.zfar); + break; + case cgltf_camera_type_invalid: + break; + } + + gfx_set_camera_camera(cameras[next_camera], &camera); + gfx_construct_camera_node(nodes[n], cameras[next_camera]); + ++next_camera; + } else { + // TODO: implementation for missing node types. + // These nodes currently default to logical nodes. + } + assert(nodes[n]); + + // Set transform. + mat4 transform; + if (node->has_matrix) { + transform = mat4_from_array(node->matrix); + } else { + transform = mat4_id(); + if (node->has_scale) { + const mat4 scale = mat4_scale(vec3_from_array(node->scale)); + transform = mat4_mul(transform, scale); + } + if (node->has_rotation) { + const quat q = quat_from_array(node->rotation); + const mat4 rotate = mat4_from_quat(q); + transform = mat4_mul(transform, rotate); + } + if (node->has_translation) { + const mat4 translate = + mat4_translate(vec3_from_array(node->translation)); + transform = mat4_mul(translate, transform); + } + } + gfx_set_node_transform(nodes[n], &transform); + + // If this is a top-level node in the glTF scene, set its parent to the + // given root node. + if (!node->parent) { + gfx_set_node_parent(nodes[n], root_node); + } else { + const cgltf_size parent_index = node->parent - data->nodes; + assert(parent_index < data->nodes_count); + SceneNode* parent = nodes[parent_index]; + assert(parent); + gfx_set_node_parent(nodes[n], parent); + } + } // SceneNode. +} + +/// Remove joint nodes from the Gfx Scene. +/// +/// Joint nodes are not needed because joints are packed into the Anima. +static void remove_joint_nodes( + const cgltf_data* data, SceneNode** scene_nodes) { + assert(data); + assert(scene_nodes); + + // This works assuming the joint nodes are contiguous. Contiguity is checked + // when loading skins. See load_skins(). + size_t min_joint_index = (size_t)-1; + size_t max_joint_index = 0; + + // First get the minimum and maximum indices of all joint nodes. + for (cgltf_size s = 0; s < data->skins_count; ++s) { + const cgltf_skin* skin = &data->skins[s]; + + for (cgltf_size j = 0; j < skin->joints_count; ++j) { + // Joint is an index/pointer into the nodes array. + const cgltf_size joint_index = skin->joints[j] - data->nodes; + assert(joint_index < data->nodes_count); + + if (joint_index < min_joint_index) { + min_joint_index = joint_index; + } + if (joint_index > max_joint_index) { + max_joint_index = joint_index; + } + } + } + + assert(min_joint_index < data->nodes_count); + assert(max_joint_index < data->nodes_count); + + // Now walk over the joint nodes. If a joint's parent is itself not a joint + // node, then that joint is a root of a joint hierarchy (skins in glTF may + // have multiple roots). In such case, delete the root joint recursively. + for (cgltf_size s = 0; s < data->skins_count; ++s) { + const cgltf_skin* skin = &data->skins[s]; + + for (cgltf_size j = 0; j < skin->joints_count; ++j) { + // Joint is an index/pointer into the nodes array. + const cgltf_size joint_index = skin->joints[j] - data->nodes; + assert(joint_index < data->nodes_count); + + const cgltf_node* joint = &data->nodes[joint_index]; + + // Parent node index. + const cgltf_size parent_index = joint->parent - data->nodes; + assert(parent_index < data->nodes_count); + + // If the parent is not a joint node, recursively delete this joint node. + if ((parent_index < min_joint_index) || + (parent_index > max_joint_index)) { + gfx_destroy_node(&scene_nodes[joint_index]); + } + } + } +} + +/// Load all scenes from the glTF file. +/// +/// If the scene is loaded from memory, set filepath = null. +/// +/// This function ignores the many scenes and default scene of the glTF spec +/// and instead just loads all scenes into a single Gfx Scene. +static Model* load_scene( + cgltf_data* data, Gfx* gfx, const mstring* filepath, ShaderProgram* shader, + const cgltfTangentBuffer* cgltf_tangent_buffers, + cgltf_size num_tangent_buffers) { + // In a GLTF scene, buffers can be shared among meshes, meshes among nodes, + // etc. Each object is referenced by its index in the relevant array. Here we + // do a button-up construction, first allocating our own graphics objects in + // the same quantities and then re-using the GLTF indices to index these + // arrays. + // + // For simplicity, this function also handles all of the cleanup. Arrays are + // allocated up front, and the helper functions construct their elements. If + // an error is encountered, the helper functions can simply return and this + // function cleans up any intermediate objects that had been created up until + // the point of failure. + // + // Loading animation data: + // - Buffers with animation sampler data need to stay on the CPU, not + // uploaded to the GPU. We could try to implement GPU animation at a later + // stage. + assert(data); + assert(gfx); + assert(filepath); + assert((num_tangent_buffers == 0) || (cgltf_tangent_buffers != 0)); + + bool success = false; + + GfxCore* gfxcore = gfx_get_core(gfx); + const size_t primitive_count = get_total_primitives(data); + + const mstring directory = mstring_dirname(*filepath); + LOGD("Filepath: %s", mstring_cstr(filepath)); + LOGD("Directory: %s", mstring_cstr(&directory)); + + Buffer** tangent_buffers = 0; + Buffer** buffers = 0; + LoadTextureCmd* load_texture_cmds = 0; + const Texture** textures = 0; // Textures are owned by asset cache. + Material** materials = 0; + Geometry** geometries = 0; + Mesh** meshes = 0; + AnimaDesc* anima_desc = 0; + SceneObject** scene_objects = 0; + SceneCamera** scene_cameras = 0; + SceneNode** scene_nodes = 0; + Anima* anima = 0; + SceneNode* root_node = 0; + Model* model = 0; + + tangent_buffers = calloc(num_tangent_buffers, sizeof(Buffer*)); + buffers = calloc(data->buffers_count, sizeof(Buffer*)); + textures = calloc(data->textures_count, sizeof(Texture*)); + materials = calloc(data->materials_count, sizeof(Material*)); + geometries = calloc(primitive_count, sizeof(Geometry*)); + meshes = calloc(primitive_count, sizeof(Mesh*)); + scene_objects = calloc(data->meshes_count, sizeof(SceneObject*)); + scene_cameras = calloc(data->cameras_count, sizeof(SceneCamera**)); + scene_nodes = calloc(data->nodes_count, sizeof(SceneNode**)); + // A glTF scene does not necessarily have textures. Materials can be given + // as constants, for example. + if (data->textures_count > 0) { + load_texture_cmds = calloc(data->textures_count, sizeof(LoadTextureCmd)); + } + + if (!buffers || !tangent_buffers || + ((data->textures_count > 0) && !load_texture_cmds) || !textures || + !materials || !geometries || !meshes || !scene_objects || + !scene_cameras || !scene_nodes) { + goto cleanup; + } + + if ((num_tangent_buffers > 0) && + !load_tangent_buffers( + cgltf_tangent_buffers, num_tangent_buffers, gfxcore, + tangent_buffers)) { + goto cleanup; + } + + if (!load_buffers(data, gfxcore, buffers)) { + goto cleanup; + } + + if (data->textures_count > 0) { + load_textures_lazy( + data, gfxcore, mstring_cstr(&directory), load_texture_cmds); + } + + if (!load_materials(data, gfx, load_texture_cmds, textures, materials)) { + goto cleanup; + } + + if (!load_meshes( + data, gfxcore, buffers, tangent_buffers, cgltf_tangent_buffers, + num_tangent_buffers, materials, shader, primitive_count, geometries, + meshes, scene_objects)) { + goto cleanup; + } + + // Skins refer to nodes, and nodes may refer to skins. To break this circular + // dependency, glTF defines skins in terms of node indices. We could do the + // same if Gfx allowed allocating nodes contiguously in memory. For now, + // create the nodes up front and use the indices of the array to map to the + // node_idx. + for (cgltf_size i = 0; i < data->nodes_count; ++i) { + scene_nodes[i] = gfx_make_node(); + } + + // Create the scene's root node. + // This is an anima node if the scene has skins; otherwise it is a logical + // node. + root_node = gfx_make_node(); + if (data->skins_count > 0) { + anima_desc = calloc(1, sizeof(AnimaDesc)); + if (!anima_desc) { + goto cleanup; + } + + const cgltf_size base = find_base_joint_index(data); + + anima_desc->num_skeletons = data->skins_count; + anima_desc->num_animations = data->animations_count; + anima_desc->num_joints = load_skins(data, buffers, base, anima_desc); + load_animations(data, base, anima_desc); + + compute_joint_bounding_boxes( + data, anima_desc->num_joints, anima_desc->joints); + + anima = gfx_make_anima(anima_desc); + gfx_construct_anima_node(root_node, anima); + } + + // The root node becomes the root of all scene nodes. + load_nodes(data, root_node, scene_objects, scene_cameras, anima, scene_nodes); + + // Clean up scene nodes that correspond to joints in the glTF. These are + // not needed anymore. + if (data->skins_count > 0) { + remove_joint_nodes(data, scene_nodes); + } + + model = gfx_make_model(root_node); + + success = true; + +cleanup: + // The arrays of resources are no longer needed. The resources themselves are + // destroyed only if this function fails. + if (tangent_buffers) { + if (!success) { + for (cgltf_size i = 0; i < num_tangent_buffers; ++i) { + if (tangent_buffers[i]) { + gfx_destroy_buffer(gfxcore, &tangent_buffers[i]); + } + } + } + free(tangent_buffers); + } + if (buffers) { + if (!success) { + for (cgltf_size i = 0; i < data->buffers_count; ++i) { + if (buffers[i]) { + gfx_destroy_buffer(gfxcore, &buffers[i]); + } + } + } + free(buffers); + } + if (load_texture_cmds) { + free(load_texture_cmds); + } + if (textures) { + free(textures); + } + if (materials) { + if (!success) { + for (cgltf_size i = 0; i < data->materials_count; ++i) { + if (materials[i]) { + gfx_destroy_material(&materials[i]); + } + } + } + free(materials); + } + if (geometries) { + if (!success) { + for (size_t i = 0; i < primitive_count; ++i) { + if (geometries[i]) { + gfx_destroy_geometry(gfxcore, &geometries[i]); + } + } + } + free(geometries); + } + if (meshes) { + if (!success) { + for (size_t i = 0; i < primitive_count; ++i) { + if (meshes[i]) { + gfx_destroy_mesh(&meshes[i]); + } + } + } + free(meshes); + } + if (anima_desc) { + free(anima_desc); + } + if (scene_objects) { + if (!success) { + for (cgltf_size i = 0; i < data->meshes_count; ++i) { + if (scene_objects[i]) { + gfx_destroy_object(&scene_objects[i]); + } + } + } + free(scene_objects); + } + if (scene_cameras) { + if (!success) { + for (cgltf_size i = 0; i < data->cameras_count; ++i) { + if (scene_cameras[i]) { + gfx_destroy_camera(&scene_cameras[i]); + } + } + } + free(scene_cameras); + } + if (scene_nodes) { + if (!success) { + for (cgltf_size i = 0; i < data->nodes_count; ++i) { + if (scene_nodes[i]) { + gfx_destroy_node(&scene_nodes[i]); + } + } + } + free(scene_nodes); + } + if (!success) { + if (root_node) { + gfx_destroy_node(&root_node); // Node owns the anima. + } else if (anima) { + gfx_destroy_anima(&anima); + } + } + return model; +} + +Model* gfx_model_load(Gfx* gfx, const LoadModelCmd* cmd) { + assert(gfx); + assert(cmd); + + Model* model = 0; + + cgltf_options options = {0}; + cgltf_data* data = NULL; + cgltfTangentBuffer* tangent_buffers = 0; + + cgltf_result result; + switch (cmd->origin) { + case AssetFromFile: + result = cgltf_parse_file(&options, mstring_cstr(&cmd->filepath), &data); + break; + case AssetFromMemory: + result = cgltf_parse(&options, cmd->data, cmd->size_bytes, &data); + break; + } + if (result != cgltf_result_success) { + goto cleanup; + } + + if (cmd->origin == AssetFromFile) { + // Must call cgltf_load_buffers() to load buffer data. + result = cgltf_load_buffers(&options, data, mstring_cstr(&cmd->filepath)); + if (result != cgltf_result_success) { + goto cleanup; + } + } + + // Compute tangents for normal-mapped models that are missing them. + cgltf_size num_tangent_buffers = 0; + cgltf_compute_tangents( + &options, data, &tangent_buffers, &num_tangent_buffers); + + model = load_scene( + data, gfx, &cmd->filepath, cmd->shader, tangent_buffers, + num_tangent_buffers); + +cleanup: + if (data) { + cgltf_free(data); + } + if (tangent_buffers) { + free(tangent_buffers); + } + return model; +} diff --git a/src/asset/model.h b/src/asset/model.h new file mode 100644 index 0000000..d6399b1 --- /dev/null +++ b/src/asset/model.h @@ -0,0 +1,12 @@ +/// Load scene files. +#pragma once + +#include + +typedef struct Gfx Gfx; +typedef struct Model Model; + +/// Load a model. +/// +/// Currently only supports the GLTF format. +Model* gfx_model_load(Gfx*, const LoadModelCmd*); diff --git a/src/asset/texture.c b/src/asset/texture.c new file mode 100644 index 0000000..c790394 --- /dev/null +++ b/src/asset/texture.c @@ -0,0 +1,177 @@ +#include "texture.h" + +#include "gfx/core.h" + +#include "error.h" + +#define STB_IMAGE_IMPLEMENTATION +#include "stb_image.h" + +#include + +static void flip_horizontally( + unsigned char* pixels, int width, int height, int components) { + assert(pixels); + + for (int y = 0; y < height; ++y) { + for (int x = 0; x < width / 2; ++x) { + unsigned char* p1 = &pixels[(y * width + x) * components]; + unsigned char* p2 = &pixels[(y * width + (width - x - 1)) * components]; + + for (int c = 0; c < components; ++c) { + unsigned char tmp = *p1; + *p1 = *p2; + *p2 = tmp; + p1++; + p2++; + } + } + } +} + +// Note that the cubemap coordinate system uses the one in RenderMan: +// +// https://www.khronos.org/opengl/wiki/Cubemap_Texture +// +// This is what happens: +// +// - Cubemaps follow a left-handed coordinate system. Say, +X is right, +Y is +// up, and +Z is forward. +// - The texture coordinate system follow's DirectX's, so +V goes down, not up +// like it does in OpenGL. +// +// For this reason, we do X and Y flips when doing cubemap textures so that we +// can sample cubemaps as if they were given in the usual OpenGL coordinate +// system. +Texture* gfx_texture_load(GfxCore* gfxcore, const LoadTextureCmd* cmd) { + assert(gfxcore); + assert(cmd); + assert(cmd->origin == AssetFromFile || cmd->origin == AssetFromMemory); + assert(cmd->type == LoadTexture || cmd->type == LoadCubemap); + + int width, height, components, old_components; + unsigned char* pixels[6] = {0}; + + switch (cmd->origin) { + case AssetFromFile: + switch (cmd->type) { + case LoadTexture: { + const char* filepath = mstring_cstr(&cmd->data.texture.filepath); + stbi_set_flip_vertically_on_load(0); + pixels[0] = stbi_load(filepath, &width, &height, &components, 0); + if (!pixels[0]) { + log_error("Failed to load texture file: %s", filepath); + } + break; + } + case LoadCubemap: + for (int i = 0; i < 6; ++i) { + // Flip +Y and -Y textures vertically. + stbi_set_flip_vertically_on_load(((i == 2) || (i == 3)) ? 1 : 0); + const char* filepath = + mstring_cstr(&cmd->data.cubemap.filepaths.filepath_pos_x + i); + stbi_uc* image_pixels = + stbi_load(filepath, &width, &height, &components, 0); + if (!image_pixels) { + log_error("Failed to load texture file: %s", filepath); + break; + } + if (i > 0 && components != old_components) { + log_error("All textures in a cubemap must have the same number of " + "components"); + break; + } + if ((i != 2) && (i != 3)) { + flip_horizontally(image_pixels, width, height, components); + } + pixels[i] = image_pixels; + old_components = components; + } + break; + } + break; + case AssetFromMemory: + // TODO: Load textures from memory. + log_error("Loading textures from memory is not yet implemented"); + return 0; + } + + // Error out if we failed to load a texture. + if (!pixels[0] || + (cmd->type == LoadCubemap && + (!pixels[1] || !pixels[2] || !pixels[3] || !pixels[4] || !pixels[5]))) { + for (int i = 0; i < 6; ++i) { + if (pixels[i]) { + stbi_image_free(pixels[i]); + } + } + return 0; + } + + TextureDesc desc = (TextureDesc){0}; + desc.width = width; + desc.height = height; + + switch (cmd->type) { + case LoadTexture: + desc.dimension = Texture2D; + break; + case LoadCubemap: + desc.dimension = TextureCubeMap; + break; + } + + switch (components) { + case 3: + switch (cmd->colour_space) { + case LinearColourSpace: + desc.format = TextureRGB8; + break; + case sRGB: + desc.format = TextureSRGB8; + break; + default: + log_error("Unsupported texture colour space: %d", cmd->colour_space); + return 0; + } + break; + case 4: + switch (cmd->colour_space) { + case LinearColourSpace: + desc.format = TextureRGBA8; + break; + case sRGB: + desc.format = TextureSRGBA8; + break; + default: + log_error("Unsupported texture colour space: %d", cmd->colour_space); + return 0; + } + break; + default: + log_error("Unsupported number of texture components: %d", components); + return 0; + } + + desc.filtering = cmd->filtering; + desc.mipmaps = cmd->mipmaps; + + switch (cmd->type) { + case LoadTexture: + desc.data.pixels = pixels[0]; + break; + case LoadCubemap: + for (int i = 0; i < 6; ++i) { + *(&desc.data.cubemap.pixels_pos_x + i) = pixels[i]; + } + break; + } + + Texture* texture = gfx_make_texture(gfxcore, &desc); + for (int i = 0; i < 6; ++i) { + if (pixels[i]) { + stbi_image_free(pixels[i]); + } + } + return texture; +} diff --git a/src/asset/texture.h b/src/asset/texture.h new file mode 100644 index 0000000..0d38bd9 --- /dev/null +++ b/src/asset/texture.h @@ -0,0 +1,7 @@ +/// Load textures from images. +#pragma once + +#include + +/// Load a texture. +Texture* gfx_texture_load(GfxCore*, const LoadTextureCmd*); diff --git a/src/core/buffer.c b/src/core/buffer.c new file mode 100644 index 0000000..3b7e4bc --- /dev/null +++ b/src/core/buffer.c @@ -0,0 +1,85 @@ +#include "buffer.h" + +#include +#include + +#include +#include +#include + +static size_t get_buffer_size_bytes( + BufferType type, const BufferDataDesc* desc) { + return desc->count * gfx_get_buffer_type_size_bytes(type); +} + +static GLenum get_buffer_usage(BufferUsage usage) { + switch (usage) { + case BufferStatic: + return GL_STATIC_DRAW; + case BufferDynamic: + return GL_DYNAMIC_DRAW; + } + FAIL("Unhandled buffer usage"); + return GL_STATIC_DRAW; +} + +size_t gfx_get_buffer_type_size_bytes(BufferType type) { + switch (type) { + case BufferUntyped: + return 1; + case Buffer2d: + return sizeof(vec2); + case Buffer3d: + return sizeof(vec3); + case Buffer4d: + return sizeof(vec4); + case BufferFloat: + return sizeof(float); + case BufferU8: + return sizeof(uint8_t); + case BufferU16: + return sizeof(uint16_t); + } + FAIL("Unhandled buffer type"); + return 0; +} + +bool gfx_init_buffer(Buffer* buffer, const BufferDesc* desc) { + assert(buffer); + + buffer->type = desc->type; + buffer->usage = desc->usage; + buffer->size_bytes = get_buffer_size_bytes(desc->type, &desc->data); + const GLenum usage = get_buffer_usage(desc->usage); + + glGenBuffers(1, &buffer->vbo); + glBindBuffer(GL_ARRAY_BUFFER, buffer->vbo); + glBufferData(GL_ARRAY_BUFFER, buffer->size_bytes, desc->data.data, usage); + glBindBuffer(GL_ARRAY_BUFFER, 0); + ASSERT_GL; + + return true; +} + +void gfx_del_buffer(Buffer* buffer) { + assert(buffer); + if (buffer->vbo) { + glDeleteBuffers(1, &buffer->vbo); + buffer->vbo = 0; + } +} + +void gfx_update_buffer(Buffer* buffer, const BufferDataDesc* desc) { + assert(buffer); + assert(desc); + // OpenGL allows updating static buffers, but it is not optimal for + // performance, so we enforce data in static buffers remain static. + assert(buffer->usage == BufferDynamic); + + const size_t update_size_bytes = get_buffer_size_bytes(buffer->type, desc); + assert(update_size_bytes <= buffer->size_bytes); + + glBindBuffer(GL_ARRAY_BUFFER, buffer->vbo); + glBufferSubData(GL_ARRAY_BUFFER, 0, update_size_bytes, desc->data); + glBindBuffer(GL_ARRAY_BUFFER, 0); +} diff --git a/src/core/buffer.h b/src/core/buffer.h new file mode 100644 index 0000000..b9080f0 --- /dev/null +++ b/src/core/buffer.h @@ -0,0 +1,26 @@ +#pragma once + +#include + +#include "gl_util.h" + +#include + +#include +#include + +typedef struct Buffer { + GLuint vbo; + BufferType type; + BufferUsage usage; + size_t size_bytes; +} Buffer; + +/// Return the buffer type size in bytes. +size_t gfx_get_buffer_type_size_bytes(BufferType); + +/// Create a buffer from raw data. +bool gfx_init_buffer(Buffer*, const BufferDesc*); + +/// Destroy the buffer. +void gfx_del_buffer(Buffer*); diff --git a/src/core/constants.h b/src/core/constants.h new file mode 100644 index 0000000..a6a3b94 --- /dev/null +++ b/src/core/constants.h @@ -0,0 +1,9 @@ +#pragma once + +// Shaders vertex attribute locations must match the channels here. +#define GFX_POSITION_CHANNEL 0 +#define GFX_NORMAL_CHANNEL 1 +#define GFX_TANGENT_CHANNEL 2 +#define GFX_TEXCOORDS_CHANNEL 3 +#define GFX_JOINTS_CHANNEL 4 +#define GFX_WEIGHTS_CHANNEL 5 diff --git a/src/core/core.c b/src/core/core.c new file mode 100644 index 0000000..90038c6 --- /dev/null +++ b/src/core/core.c @@ -0,0 +1,429 @@ +#include "core_impl.h" + +#include "gl_util.h" + +// #include + +#include + +void gfx_init_gfxcore(GfxCore* gfxcore) { + assert(gfxcore); + + mempool_make(&gfxcore->buffers); + mempool_make(&gfxcore->framebuffers); + mempool_make(&gfxcore->geometries); + mempool_make(&gfxcore->renderbuffers); + mempool_make(&gfxcore->shaders); + mempool_make(&gfxcore->shader_programs); + mempool_make(&gfxcore->textures); + + mempool_make(&gfxcore->shader_cache); + mempool_make(&gfxcore->program_cache); + + glEnable(GL_CULL_FACE); + glFrontFace(GL_CCW); + glCullFace(GL_BACK); + + glEnable(GL_DEPTH_TEST); + + // Filter cubemaps across their faces to avoid seams. + // https://www.khronos.org/opengl/wiki/Cubemap_Texture#Seamless_cubemap + glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); +} + +// Conveniently destroy any objects that have not been destroyed by the +// application. +void gfx_del_gfxcore(GfxCore* gfxcore) { + assert(gfxcore); + + mempool_foreach(&gfxcore->buffers, buffer, { gfx_del_buffer(buffer); }); + + mempool_foreach(&gfxcore->framebuffers, framebuffer, { + gfx_del_framebuffer(framebuffer); + }); + + mempool_foreach( + &gfxcore->geometries, geometry, { gfx_del_geometry(geometry); }); + + mempool_foreach(&gfxcore->renderbuffers, renderbuffer, { + gfx_del_renderbuffer(renderbuffer); + }); + + mempool_foreach( + &gfxcore->shader_programs, prog, { gfx_del_shader_program(prog); }); + + mempool_foreach(&gfxcore->shaders, shader, { gfx_del_shader(shader); }); + + mempool_foreach(&gfxcore->textures, texture, { gfx_del_texture(texture); }); +} + +// ----------------------------------------------------------------------------- +// Render commands. +// ----------------------------------------------------------------------------- + +void gfx_start_frame(GfxCore* gfxcore) { + assert(gfxcore); + + glViewport( + gfxcore->viewport.x, gfxcore->viewport.y, gfxcore->viewport.width, + gfxcore->viewport.height); + glClearColor(0, 0, 0, 0); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + + ASSERT_GL; +} + +void gfx_end_frame(GfxCore* gfxcore) { + assert(gfxcore); + ASSERT_GL; +} + +void gfx_set_viewport(GfxCore* gfxcore, int x, int y, int width, int height) { + assert(gfxcore); + gfxcore->viewport = + (Viewport){.x = x, .y = y, .width = width, .height = height}; +} + +void gfx_get_viewport( + GfxCore* gfxcore, int* x, int* y, int* width, int* height) { + assert(gfxcore); + assert(x); + assert(y); + assert(width); + assert(height); + + *x = gfxcore->viewport.x; + *y = gfxcore->viewport.y; + *width = gfxcore->viewport.width; + *height = gfxcore->viewport.height; +} + +void gfx_clear(GfxCore* gfxcore, vec4 colour) { + assert(gfxcore); + + glClearColor(colour.x, colour.y, colour.z, colour.w); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); +} + +void gfx_set_blending(GfxCore* gfxcore, bool enable) { + assert(gfxcore); + if (enable) { + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + } else { + glDisable(GL_BLEND); + } +} + +void gfx_set_depth_mask(GfxCore* gfxcore, bool enable) { + assert(gfxcore); + glDepthMask(enable ? GL_TRUE : GL_FALSE); +} + +void gfx_set_culling(GfxCore* gfxcore, bool enable) { + assert(gfxcore); + if (enable) { + glEnable(GL_CULL_FACE); + } else { + glDisable(GL_CULL_FACE); + } +} + +void gfx_set_polygon_offset(GfxCore* gfxcore, float scale, float bias) { + assert(gfxcore); + if ((scale != 0.0f) || (bias != 0.0f)) { + glEnable(GL_POLYGON_OFFSET_FILL); + } else { + glDisable(GL_POLYGON_OFFSET_FILL); + } + glPolygonOffset(scale, bias); +} + +void gfx_reset_polygon_offset(GfxCore* gfxcore) { + assert(gfxcore); + glPolygonOffset(0, 0); + glDisable(GL_POLYGON_OFFSET_FILL); +} + +// ----------------------------------------------------------------------------- +// Buffers. +// ----------------------------------------------------------------------------- + +Buffer* gfx_make_buffer(GfxCore* gfxcore, const BufferDesc* desc) { + assert(gfxcore); + assert(desc); + + Buffer* buffer = mempool_alloc(&gfxcore->buffers); + if (!gfx_init_buffer(buffer, desc)) { + mempool_free(&gfxcore->buffers, &buffer); + return 0; + } + return buffer; +} + +void gfx_destroy_buffer(GfxCore* gfxcore, Buffer** buffer) { + assert(gfxcore); + assert(buffer); + if (*buffer) { + gfx_del_buffer(*buffer); + mempool_free(&gfxcore->buffers, buffer); + } +} + +// ----------------------------------------------------------------------------- +// Geometry. +// ----------------------------------------------------------------------------- + +Geometry* gfx_make_geometry(GfxCore* gfxcore, const GeometryDesc* desc) { + assert(gfxcore); + assert(desc); + + Geometry* geometry = mempool_alloc(&gfxcore->geometries); + if (!gfx_init_geometry(geometry, gfxcore, desc)) { + mempool_free(&gfxcore->geometries, &geometry); + return 0; + } + return geometry; +} + +void gfx_destroy_geometry(GfxCore* gfxcore, Geometry** geometry) { + assert(gfxcore); + assert(geometry); + + if (*geometry) { + gfx_del_geometry(*geometry); + mempool_free(&gfxcore->geometries, geometry); + } +} + +// ----------------------------------------------------------------------------- +// Textures. +// ----------------------------------------------------------------------------- + +Texture* gfx_make_texture(GfxCore* gfxcore, const TextureDesc* desc) { + assert(gfxcore); + assert(desc); + + Texture* texture = mempool_alloc(&gfxcore->textures); + if (!gfx_init_texture(texture, desc)) { + mempool_free(&gfxcore->textures, &texture); + return 0; + } + return texture; +} + +void gfx_destroy_texture(GfxCore* gfxcore, Texture** texture) { + assert(gfxcore); + assert(texture); + assert(*texture); + + if (*texture) { + gfx_del_texture(*texture); + mempool_free(&gfxcore->textures, texture); + } +} + +// ----------------------------------------------------------------------------- +// Renderbuffers. +// ----------------------------------------------------------------------------- + +RenderBuffer* gfx_make_renderbuffer( + GfxCore* gfxcore, const RenderBufferDesc* desc) { + assert(gfxcore); + assert(desc); + + RenderBuffer* renderbuffer = mempool_alloc(&gfxcore->renderbuffers); + if (!gfx_init_renderbuffer(renderbuffer, desc)) { + mempool_free(&gfxcore->renderbuffers, &renderbuffer); + } + return renderbuffer; +} + +void gfx_destroy_renderbuffer(GfxCore* gfxcore, RenderBuffer** renderbuffer) { + assert(gfxcore); + assert(renderbuffer); + assert(*renderbuffer); + + if (*renderbuffer) { + gfx_del_renderbuffer(*renderbuffer); + mempool_free(&gfxcore->renderbuffers, renderbuffer); + } +} + +// ----------------------------------------------------------------------------- +// Framebuffers. +// ----------------------------------------------------------------------------- + +FrameBuffer* gfx_make_framebuffer( + GfxCore* gfxcore, const FrameBufferDesc* desc) { + assert(gfxcore); + assert(desc); + + FrameBuffer* framebuffer = mempool_alloc(&gfxcore->framebuffers); + if (!gfx_init_framebuffer(framebuffer, desc)) { + mempool_free(&gfxcore->framebuffers, &framebuffer); + return 0; + } + return framebuffer; +} + +void gfx_destroy_framebuffer(GfxCore* gfxcore, FrameBuffer** framebuffer) { + assert(gfxcore); + assert(framebuffer); + assert(*framebuffer); + + if (*framebuffer) { + gfx_del_framebuffer(*framebuffer); + mempool_free(&gfxcore->framebuffers, framebuffer); + } +} + +// ----------------------------------------------------------------------------- +// Shaders. +// ----------------------------------------------------------------------------- + +static uint64_t hash_shader_desc(const ShaderDesc* desc) { + assert(desc); + // Note that defines may affect shader permutations, so we need to hash those + // as well. + uint64_t hash = 0; + for (size_t i = 0; i < desc->num_defines; ++i) { + const ShaderCompilerDefine* define = &desc->defines[i]; + hash = (((hash << 13) + sstring_hash(define->name)) << 7) + + sstring_hash(define->value); + } + return (hash << 17) + cstring_hash(desc->code); +} + +static uint64_t hash_program_desc(const ShaderProgramDesc* desc) { + assert(desc); + return ((uint64_t)desc->vertex_shader->id << 32) | + (uint64_t)desc->fragment_shader->id; +} + +static Shader* find_cached_shader(ShaderCache* cache, uint64_t hash) { + assert(cache); + mempool_foreach(cache, entry, { + if (entry->hash == hash) { + return entry->shader; + } + }); + return 0; +} + +static ShaderProgram* find_cached_program(ProgramCache* cache, uint64_t hash) { + assert(cache); + mempool_foreach(cache, entry, { + if (entry->hash == hash) { + return entry->program; + } + }); + return 0; +} + +static ShaderCacheEntry* find_shader_cache_entry( + ShaderCache* cache, const Shader* shader) { + assert(cache); + assert(shader); + mempool_foreach(cache, entry, { + if (entry->shader == shader) { + return entry; + } + }); + return 0; +} + +static ShaderProgramCacheEntry* find_program_cache_entry( + ProgramCache* cache, const ShaderProgram* prog) { + assert(cache); + assert(prog); + mempool_foreach(cache, entry, { + if (entry->program == prog) { + return entry; + } + }); + return 0; +} + +Shader* gfx_make_shader(GfxCore* gfxcore, const ShaderDesc* desc) { + assert(gfxcore); + assert(desc); + + // Check the shader cache first. + ShaderCache* cache = &gfxcore->shader_cache; + const uint64_t hash = hash_shader_desc(desc); + Shader* shader = find_cached_shader(cache, hash); + if (shader) { + // LOGD("Found cached shader with hash [%lx]", hash); + return shader; + } + + shader = mempool_alloc(&gfxcore->shaders); + if (!shader) { + return 0; + } + if (!gfx_compile_shader(shader, desc)) { + mempool_free(&gfxcore->shaders, &shader); + return 0; + } + ShaderCacheEntry* entry = mempool_alloc(cache); + *entry = (ShaderCacheEntry){.hash = hash, .shader = shader}; + // LOGD("Added shader with hash [%lx] to cache", hash); + return shader; +} + +void gfx_destroy_shader(GfxCore* gfxcore, Shader** shader) { + assert(gfxcore); + assert(shader); + + if (*shader) { + // Remove the shader from the cache. + ShaderCache* cache = &gfxcore->shader_cache; + ShaderCacheEntry* entry = find_shader_cache_entry(cache, *shader); + assert(entry); // Must be there, shaders can't go untracked. + mempool_free(cache, &entry); + + gfx_del_shader(*shader); + mempool_free(&gfxcore->shaders, shader); + } +} + +ShaderProgram* gfx_make_shader_program( + GfxCore* gfxcore, const ShaderProgramDesc* desc) { + assert(gfxcore); + assert(desc); + + // Check the shader program cache first. + ProgramCache* cache = &gfxcore->program_cache; + const uint64_t hash = hash_program_desc(desc); + ShaderProgram* prog = find_cached_program(cache, hash); + if (prog) { + // LOGD("Found cached shader program with hash [%lx]", hash); + return prog; + } + + prog = mempool_alloc(&gfxcore->shader_programs); + if (!gfx_build_shader_program(prog, desc)) { + mempool_free(&gfxcore->shader_programs, &prog); + return 0; + } + ShaderProgramCacheEntry* entry = mempool_alloc(cache); + *entry = (ShaderProgramCacheEntry){.hash = hash, .program = prog}; + // LOGD("Added shader program with hash [%lx] to cache", hash); + return prog; +} + +void gfx_destroy_shader_program(GfxCore* gfxcore, ShaderProgram** prog) { + assert(gfxcore); + assert(prog); + if (*prog) { + // Remove the shader program from the cache. + ProgramCache* cache = &gfxcore->program_cache; + ShaderProgramCacheEntry* entry = find_program_cache_entry(cache, *prog); + assert(entry); // Must be there, shaders can't go untracked. + mempool_free(cache, &entry); + + gfx_del_shader_program(*prog); + mempool_free(&gfxcore->shader_programs, prog); + } +} diff --git a/src/core/core_impl.h b/src/core/core_impl.h new file mode 100644 index 0000000..eefdfbe --- /dev/null +++ b/src/core/core_impl.h @@ -0,0 +1,68 @@ +#pragma once + +#include +#include + +#include "buffer.h" +#include "framebuffer.h" +#include "geometry.h" +#include "renderbuffer.h" +#include "shader.h" +#include "shader_program.h" +#include "texture.h" + +#include + +#include + +// TODO: Make a generic (hash, void*) structure and define functions over it. +// Then define a macro that defines type-safe macros given the type of the +// entry. +typedef struct ShaderCacheEntry { + uint64_t hash; + Shader* shader; +} ShaderCacheEntry; + +typedef struct ShaderProgramCacheEntry { + uint64_t hash; + ShaderProgram* program; +} ShaderProgramCacheEntry; + +DEF_MEMPOOL(buffer_pool, Buffer, GFX_MAX_NUM_BUFFERS) +DEF_MEMPOOL(framebuffer_pool, FrameBuffer, GFX_MAX_NUM_FRAMEBUFFERS) +DEF_MEMPOOL(geometry_pool, Geometry, GFX_MAX_NUM_GEOMETRIES) +DEF_MEMPOOL(renderbuffer_pool, RenderBuffer, GFX_MAX_NUM_RENDERBUFFERS) +DEF_MEMPOOL(shader_pool, Shader, GFX_MAX_NUM_SHADERS) +DEF_MEMPOOL(shader_program_pool, ShaderProgram, GFX_MAX_NUM_SHADER_PROGRAMS) +DEF_MEMPOOL(texture_pool, Texture, GFX_MAX_NUM_TEXTURES) + +DEF_MEMPOOL(ShaderCache, ShaderCacheEntry, GFX_MAX_NUM_SHADERS) +DEF_MEMPOOL(ProgramCache, ShaderProgramCacheEntry, GFX_MAX_NUM_SHADER_PROGRAMS) + +typedef struct { + int x; + int y; + int width; + int height; +} Viewport; + +typedef struct GfxCore { + Viewport viewport; + // mempools for render-specific objects: textures, geometry, etc. + buffer_pool buffers; + framebuffer_pool framebuffers; + geometry_pool geometries; + renderbuffer_pool renderbuffers; + shader_pool shaders; + shader_program_pool shader_programs; + texture_pool textures; + // Caches. + ShaderCache shader_cache; + ProgramCache program_cache; +} GfxCore; + +/// Create a new render backend. +void gfx_init_gfxcore(GfxCore*); + +/// Destroy the render backend. +void gfx_del_gfxcore(GfxCore*); diff --git a/src/core/framebuffer.c b/src/core/framebuffer.c new file mode 100644 index 0000000..76d9002 --- /dev/null +++ b/src/core/framebuffer.c @@ -0,0 +1,151 @@ +#include "framebuffer.h" + +#include "renderbuffer.h" +#include "texture.h" + +#include + +#include + +static void framebuffer_attach_colour( + FrameBuffer* framebuffer, const FrameBufferAttachment* attachment) { + assert(framebuffer); + assert(attachment); + + switch (attachment->type) { + case FrameBufferNoAttachment: + break; + case FrameBufferTexture: + glFramebufferTexture2D( + GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + attachment->texture.texture->id, attachment->texture.mip_level); + break; + case FrameBufferCubemapTexture: + glFramebufferTexture2D( + GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, + to_GL_cubemap_face(attachment->cubemap.face), + attachment->cubemap.texture->id, attachment->cubemap.mip_level); + break; + case FrameBufferRenderBuffer: + glFramebufferRenderbuffer( + GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, + attachment->renderbuffer->id); + break; + } + + ASSERT_GL; +} + +static void framebuffer_attach_depth( + FrameBuffer* framebuffer, const FrameBufferAttachment* attachment) { + assert(framebuffer); + assert(attachment); + + switch (attachment->type) { + case FrameBufferNoAttachment: + break; + case FrameBufferTexture: + glFramebufferTexture2D( + GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_DEPTH_COMPONENT, + attachment->texture.texture->id, attachment->texture.mip_level); + break; + // TODO: Could distinguish between colour and depth attachment types to make + // this a compile-time error. + case FrameBufferCubemapTexture: + log_error("Cannot use a cubemap texture as a depth framebuffer attachment"); + break; + case FrameBufferRenderBuffer: + glFramebufferRenderbuffer( + GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, + attachment->renderbuffer->id); + break; + } + + ASSERT_GL; +} + +bool gfx_init_framebuffer( + FrameBuffer* framebuffer, const FrameBufferDesc* desc) { + assert(framebuffer); + assert(desc); + + glGenFramebuffers(1, &framebuffer->id); + if (!framebuffer->id) { + log_error("glGenFramebuffers() failed"); + return false; + } + + // Allow incomplete framebuffers for flexibility. + // Attach buffers and check the framebuffer status only if buffers are given + // up front. + if (desc->colour.type != FrameBufferNoAttachment || + desc->depth.type != FrameBufferNoAttachment) { + // TODO: Could use the "named" API to avoid having to bind the framebuffer. + glBindFramebuffer(GL_FRAMEBUFFER, framebuffer->id); + framebuffer_attach_colour(framebuffer, &desc->colour); + framebuffer_attach_depth(framebuffer, &desc->depth); + if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { + log_error("glCheckFramebufferStatus() failed"); + gfx_del_framebuffer(framebuffer); + return false; + } + glBindFramebuffer(GL_FRAMEBUFFER, 0); + } + + ASSERT_GL; + return true; +} + +bool gfx_framebuffer_attach_colour( + FrameBuffer* framebuffer, const FrameBufferAttachment* attachment) { + assert(framebuffer); + assert(attachment); + + // TODO: Could use the "named" API to avoid having to bind the framebuffer. + glBindFramebuffer(GL_FRAMEBUFFER, framebuffer->id); + framebuffer_attach_colour(framebuffer, attachment); + if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { + log_error("glCheckFramebufferStatus() failed"); + return false; + } + return true; +} + +bool gfx_framebuffer_attach_depth( + FrameBuffer* framebuffer, const FrameBufferAttachment* attachment) { + assert(framebuffer); + assert(attachment); + + // TODO: Could use the "named" API to avoid having to bind the framebuffer. + glBindFramebuffer(GL_FRAMEBUFFER, framebuffer->id); + framebuffer_attach_depth(framebuffer, attachment); + if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { + log_error("glCheckFramebufferStatus() failed"); + return false; + } + return true; +} + +void gfx_del_framebuffer(FrameBuffer* framebuffer) { + assert(framebuffer); + if (framebuffer->id) { + glDeleteFramebuffers(1, &framebuffer->id); + framebuffer->id = 0; + } +} + +void gfx_activate_framebuffer(const FrameBuffer* framebuffer) { + assert(framebuffer); + glBindFramebuffer(GL_FRAMEBUFFER, framebuffer->id); +} + +void gfx_deactivate_framebuffer(const FrameBuffer* framebuffer) { + assert(framebuffer); + glBindFramebuffer(GL_FRAMEBUFFER, 0); +} + +void gfx_framebuffer_set_viewport( + FrameBuffer* framebuffer, int x, int y, int width, int height) { + assert(framebuffer); + glViewport(x, y, width, height); +} diff --git a/src/core/framebuffer.h b/src/core/framebuffer.h new file mode 100644 index 0000000..1a3439c --- /dev/null +++ b/src/core/framebuffer.h @@ -0,0 +1,15 @@ +#pragma once + +#include + +#include "gl_util.h" + +typedef struct FrameBuffer { + GLuint id; +} FrameBuffer; + +/// Create a new framebuffer. +bool gfx_init_framebuffer(FrameBuffer*, const FrameBufferDesc*); + +/// Destroy the framebuffer. +void gfx_del_framebuffer(FrameBuffer*); diff --git a/src/core/geometry.c b/src/core/geometry.c new file mode 100644 index 0000000..cfc749f --- /dev/null +++ b/src/core/geometry.c @@ -0,0 +1,326 @@ +#include "geometry.h" + +#include "buffer.h" +#include "constants.h" + +#include + +#include +#include + +/// Determines whether a view is populated. +/// +/// Note that views are allowed to have no data, in which case a buffer of the +/// specified size is created. +#define view_is_populated(BUFFER_VIEW) (BUFFER_VIEW.size_bytes > 0) + +static GLenum primitive_type_to_gl(PrimitiveType type) { + switch (type) { + case Triangles: + return GL_TRIANGLES; + case TriangleFan: + return GL_TRIANGLE_FAN; + case TriangleStrip: + return GL_TRIANGLE_STRIP; + } + FAIL("primitive_type_to_gl(): missing case"); + return GL_INVALID_ENUM; +} + +/// Create a typed buffer for the buffer view if the view does not already point +/// to a buffer. +void init_view_buffer( + GfxCore* gfxcore, BufferView* view, BufferType buffer_type, + BufferUsage buffer_usage) { + if (!view->buffer) { + view->buffer = gfx_make_buffer( + gfxcore, + &(BufferDesc){ + .usage = buffer_usage, + .type = buffer_type, + .data.data = view->data, + .data.count = view->size_bytes / + gfx_get_buffer_type_size_bytes(buffer_type)}); + } + assert(view->size_bytes <= view->buffer->size_bytes); +} + +/// Configure the buffer in teh VAO. +static void configure_buffer( + GfxCore* gfxcore, const GeometryDesc* desc, BufferView* view, + size_t num_components, size_t component_size_bytes, GLenum component_type, + GLboolean normalized, GLuint channel) { + assert(gfxcore); + assert(desc); + assert(view); + assert(view->buffer); + assert( + desc->num_verts <= + view->size_bytes / (num_components * component_size_bytes)); + assert(view->size_bytes <= view->buffer->size_bytes); + + glBindBuffer(GL_ARRAY_BUFFER, view->buffer->vbo); + glEnableVertexAttribArray(channel); + if ((component_type == GL_FLOAT) || normalized) { + glVertexAttribPointer( + channel, num_components, component_type, normalized, view->stride_bytes, + (const void*)view->offset_bytes); + } else { + assert(!normalized); + assert( + (component_type == GL_BYTE) || (component_type == GL_UNSIGNED_BYTE) || + (component_type == GL_SHORT) || (component_type == GL_UNSIGNED_SHORT) || + (component_type == GL_INT) || component_type == GL_UNSIGNED_INT); + glVertexAttribIPointer( + channel, num_components, component_type, view->stride_bytes, + (const void*)view->offset_bytes); + } + glBindBuffer(GL_ARRAY_BUFFER, 0); +} + +static bool configure_vertex_attributes(GfxCore* gfxcore, GeometryDesc* desc) { + assert(gfxcore); + assert(desc); + + if (view_is_populated(desc->positions3d)) { + init_view_buffer( + gfxcore, (BufferView*)&desc->positions3d, Buffer3d, desc->buffer_usage); + if (!desc->positions3d.buffer) { + return false; + } + configure_buffer( + gfxcore, desc, (BufferView*)&desc->positions3d, 3, sizeof(float), + GL_FLOAT, GL_FALSE, GFX_POSITION_CHANNEL); + } else if (view_is_populated(desc->positions2d)) { + init_view_buffer( + gfxcore, (BufferView*)&desc->positions2d, Buffer2d, desc->buffer_usage); + if (!desc->positions2d.buffer) { + return false; + } + configure_buffer( + gfxcore, desc, (BufferView*)&desc->positions2d, 2, sizeof(float), + GL_FLOAT, GL_FALSE, GFX_POSITION_CHANNEL); + } + if (view_is_populated(desc->normals)) { + init_view_buffer( + gfxcore, (BufferView*)&desc->normals, Buffer3d, desc->buffer_usage); + if (!desc->normals.buffer) { + return false; + } + configure_buffer( + gfxcore, desc, (BufferView*)&desc->normals, 3, sizeof(float), GL_FLOAT, + GL_FALSE, GFX_NORMAL_CHANNEL); + } + if (view_is_populated(desc->tangents)) { + init_view_buffer( + gfxcore, (BufferView*)&desc->tangents, Buffer4d, desc->buffer_usage); + if (!desc->tangents.buffer) { + return false; + } + configure_buffer( + gfxcore, desc, (BufferView*)&desc->tangents, 4, sizeof(float), GL_FLOAT, + GL_FALSE, GFX_TANGENT_CHANNEL); + } + if (view_is_populated(desc->texcoords)) { + init_view_buffer( + gfxcore, (BufferView*)&desc->texcoords, Buffer2d, desc->buffer_usage); + if (!desc->texcoords.buffer) { + return false; + } + configure_buffer( + gfxcore, desc, (BufferView*)&desc->texcoords, 2, sizeof(float), + GL_FLOAT, GL_FALSE, GFX_TEXCOORDS_CHANNEL); + } + if (view_is_populated(desc->joints.u8)) { + init_view_buffer( + gfxcore, (BufferView*)&desc->joints.u8, BufferU8, desc->buffer_usage); + if (!desc->joints.u8.buffer) { + return false; + } + configure_buffer( + gfxcore, desc, (BufferView*)&desc->joints.u8, 4, sizeof(uint8_t), + GL_UNSIGNED_BYTE, GL_FALSE, GFX_JOINTS_CHANNEL); + } else if (view_is_populated(desc->joints.u16)) { + init_view_buffer( + gfxcore, (BufferView*)&desc->joints.u16, BufferU16, desc->buffer_usage); + if (!desc->joints.u16.buffer) { + return false; + } + configure_buffer( + gfxcore, desc, (BufferView*)&desc->joints.u16, 4, sizeof(uint16_t), + GL_UNSIGNED_SHORT, GL_FALSE, GFX_JOINTS_CHANNEL); + } + + // If weights are given as unsigned integers, then they are normalized + // when read by the shader. + if (view_is_populated(desc->weights.u8)) { + init_view_buffer( + gfxcore, (BufferView*)&desc->weights.u8, BufferU8, desc->buffer_usage); + if (!desc->weights.u8.buffer) { + return false; + } + configure_buffer( + gfxcore, desc, (BufferView*)&desc->weights.u8, 4, sizeof(uint8_t), + GL_UNSIGNED_BYTE, GL_TRUE, GFX_WEIGHTS_CHANNEL); + } else if (view_is_populated(desc->weights.u16)) { + init_view_buffer( + gfxcore, (BufferView*)&desc->weights.u16, BufferU16, + desc->buffer_usage); + if (!desc->weights.u16.buffer) { + return false; + } + configure_buffer( + gfxcore, desc, (BufferView*)&desc->weights.u16, 4, sizeof(uint16_t), + GL_UNSIGNED_SHORT, GL_TRUE, GFX_WEIGHTS_CHANNEL); + } else if (view_is_populated(desc->weights.floats)) { + init_view_buffer( + gfxcore, (BufferView*)&desc->weights.floats, BufferFloat, + desc->buffer_usage); + if (!desc->weights.floats.buffer) { + return false; + } + configure_buffer( + gfxcore, desc, (BufferView*)&desc->weights.floats, 4, sizeof(float), + GL_FLOAT, GL_FALSE, GFX_WEIGHTS_CHANNEL); + } + + return true; +} + +static bool configure_indices(GfxCore* gfxcore, GeometryDesc* desc) { + assert(gfxcore); + assert(desc); + + if (view_is_populated(desc->indices8)) { + assert(desc->num_indices > 0); + assert( + desc->num_indices <= desc->indices8.size_bytes / sizeof(VertexIndex8)); + init_view_buffer( + gfxcore, (BufferView*)&desc->indices8, BufferU8, desc->buffer_usage); + if (!desc->indices8.buffer) { + return false; + } + } else if (view_is_populated(desc->indices16)) { + assert(desc->num_indices > 0); + assert( + desc->num_indices <= + desc->indices16.size_bytes / sizeof(VertexIndex16)); + init_view_buffer( + gfxcore, (BufferView*)&desc->indices16, BufferU16, desc->buffer_usage); + if (!desc->indices16.buffer) { + return false; + } + } + + return true; +} + +bool gfx_init_geometry( + Geometry* geometry, GfxCore* gfxcore, const GeometryDesc* input_desc) { + assert(geometry); + assert(gfxcore); + assert(input_desc); + assert( + view_is_populated(input_desc->positions3d) || + view_is_populated(input_desc->positions2d)); + assert(input_desc->num_verts > 0); + + geometry->mode = primitive_type_to_gl(input_desc->type); + geometry->desc = *input_desc; + geometry->num_verts = input_desc->num_verts; + geometry->gfxcore = gfxcore; + + // The geometry's copy of the descriptor is manipulated below. Create a + // shorter name for it. + GeometryDesc* desc = &geometry->desc; + + glGenVertexArrays(1, &geometry->vao); + glBindVertexArray(geometry->vao); + if (!configure_vertex_attributes(gfxcore, desc)) { + goto cleanup; + } + if (!configure_indices(gfxcore, desc)) { + goto cleanup; + } + glBindVertexArray(0); + ASSERT_GL; + + return true; + +cleanup: + gfx_del_geometry(geometry); + return 0; +} + +void gfx_del_geometry(Geometry* geometry) { + assert(geometry); + if (geometry->vao) { + glDeleteVertexArrays(1, &geometry->vao); + geometry->vao = 0; + } +} + +void gfx_update_geometry(Geometry* geometry, const GeometryDesc* desc) { + assert(geometry); + assert(desc); + // New geometry size cannot exceed original size. + assert(desc->positions3d.size_bytes <= geometry->desc.positions3d.size_bytes); + assert(desc->positions2d.size_bytes <= geometry->desc.positions2d.size_bytes); + assert(desc->normals.size_bytes <= geometry->desc.normals.size_bytes); + assert(desc->tangents.size_bytes <= geometry->desc.tangents.size_bytes); + assert(desc->texcoords.size_bytes <= geometry->desc.texcoords.size_bytes); + assert(desc->joints.u8.size_bytes <= geometry->desc.joints.u8.size_bytes); + assert(desc->joints.u16.size_bytes <= geometry->desc.joints.u16.size_bytes); + assert(desc->weights.u8.size_bytes <= geometry->desc.weights.u8.size_bytes); + assert(desc->weights.u16.size_bytes <= geometry->desc.weights.u16.size_bytes); + assert( + desc->weights.floats.size_bytes <= + geometry->desc.weights.floats.size_bytes); + + if (desc->positions3d.data) { + // The geometry must already have an underlying GPU buffer. + assert(geometry->desc.positions3d.buffer); + gfx_update_buffer( + geometry->desc.positions3d.buffer, + &(BufferDataDesc){ + .vec3s = desc->positions3d.data, + .count = desc->positions3d.size_bytes / sizeof(vec3)}); + } + // TODO: more + else { + FAIL("TODO: gfx_update_geometry() - handle other buffer types"); + } + + if (desc->num_verts != 0) { + geometry->num_verts = desc->num_verts; + } +} + +void gfx_render_geometry(const Geometry* geometry) { + assert(geometry); + assert(geometry->vao); + + const GeometryDesc* desc = &geometry->desc; + glBindVertexArray(geometry->vao); + + if (desc->indices8.buffer) { + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, desc->indices8.buffer->vbo); + glDrawElements( + geometry->mode, desc->num_indices, GL_UNSIGNED_BYTE, + (const void*)desc->indices8.offset_bytes); + } else if (desc->indices16.buffer) { + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, desc->indices16.buffer->vbo); + glDrawElements( + geometry->mode, desc->num_indices, GL_UNSIGNED_SHORT, + (const void*)desc->indices16.offset_bytes); + } else { + glDrawArrays(geometry->mode, 0, geometry->num_verts); + } + + glBindVertexArray(0); +} + +aabb3 gfx_get_geometry_aabb(const Geometry* geometry) { + assert(geometry); + return geometry->desc.aabb; +} diff --git a/src/core/geometry.h b/src/core/geometry.h new file mode 100644 index 0000000..c37a76f --- /dev/null +++ b/src/core/geometry.h @@ -0,0 +1,28 @@ +#pragma once + +#include + +#include "gl_util.h" + +#include + +/// A piece of renderable geometry. +/// +/// The Geometry does not own its buffers, since buffers are typically shared +/// to reduce the memory footprint and the number of draw calls. More generally, +/// the renderer assumes ownership of all rendering resources, which simplifies +/// their management. +typedef struct Geometry { + GLuint vao; + GLenum mode; + GeometryDesc desc; + size_t num_verts; // May differ from the initial value in the descriptor if + // the geometry is updated. + GfxCore* gfxcore; +} Geometry; + +/// Create new geometry. +bool gfx_init_geometry(Geometry*, GfxCore*, const GeometryDesc*); + +/// Destroy the geometry. +void gfx_del_geometry(Geometry*); diff --git a/src/core/gl_util.h b/src/core/gl_util.h new file mode 100644 index 0000000..d2d6e22 --- /dev/null +++ b/src/core/gl_util.h @@ -0,0 +1,45 @@ +#pragma once + +#include +#include + +#define GFX_GL_CONTEXT_PC 1 +#define GFX_GL_CONTEXT_ES 2 + +#ifndef GFX_GL_CONTEXT +#define GFX_GL_CONTEXT GFX_GL_CONTEXT_PC +#endif // GFX_GL_CONTEXT + +/// Log an error if an OpenGL has occurred. +#ifndef NDEBUG +#define ASSERT_GL \ + { \ + GLenum e = glGetError(); \ + switch (e) { \ + case GL_NO_ERROR: \ + break; \ + case GL_INVALID_ENUM: \ + LOGE("GL_INVALID_ENUM"); \ + break; \ + case GL_INVALID_VALUE: \ + LOGE("GL_INVALID_VALUE"); \ + break; \ + case GL_INVALID_OPERATION: \ + LOGE("GL_INVALID_OPERATION"); \ + break; \ + case GL_INVALID_FRAMEBUFFER_OPERATION: \ + LOGE("GL_INVALID_FRAMEBUFFER_OPERATION"); \ + break; \ + case GL_OUT_OF_MEMORY: \ + LOGE("GL_OUT_OF_MEMORY"); \ + break; \ + /*case GL_STACK_UNDERFLOW: LOGE("GL_STACK_UNDERFLOW");*/ \ + /*case GL_STACK_OVERFLOW: LOGE("GL_STACK_OVERFLOW");*/ \ + default: \ + LOGE("Unknown OpenGL error"); \ + break; \ + } \ + } +#else // Not NDEBUG. +#define ASSERT_GL +#endif diff --git a/src/core/renderbuffer.c b/src/core/renderbuffer.c new file mode 100644 index 0000000..2753f3b --- /dev/null +++ b/src/core/renderbuffer.c @@ -0,0 +1,35 @@ +#include "renderbuffer.h" + +#include "texture.h" + +#include + +bool gfx_init_renderbuffer( + RenderBuffer* renderbuffer, const RenderBufferDesc* desc) { + assert(renderbuffer); + assert(desc); + + glGenRenderbuffers(1, &renderbuffer->id); + if (!renderbuffer->id) { + log_error("glGenRenderbuffers failed"); + return false; + } + + glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer->id); + glRenderbufferStorage( + GL_RENDERBUFFER, to_GL_internal_format(desc->texture_format), desc->width, + desc->height); + glBindRenderbuffer(GL_RENDERBUFFER, 0); + + ASSERT_GL; + return true; +} + +void gfx_del_renderbuffer(RenderBuffer* renderbuffer) { + assert(renderbuffer); + + if (renderbuffer->id) { + glDeleteRenderbuffers(1, &renderbuffer->id); + renderbuffer->id = 0; + } +} diff --git a/src/core/renderbuffer.h b/src/core/renderbuffer.h new file mode 100644 index 0000000..ea11610 --- /dev/null +++ b/src/core/renderbuffer.h @@ -0,0 +1,15 @@ +#pragma once + +#include + +#include "gl_util.h" + +typedef struct RenderBuffer { + GLuint id; +} RenderBuffer; + +/// Create a new renderbuffer. +bool gfx_init_renderbuffer(RenderBuffer*, const RenderBufferDesc*); + +/// Destroy the renderbuffer. +void gfx_del_renderbuffer(RenderBuffer*); diff --git a/src/core/shader.c b/src/core/shader.c new file mode 100644 index 0000000..dded084 --- /dev/null +++ b/src/core/shader.c @@ -0,0 +1,92 @@ +#include "shader.h" + +#include "gl_util.h" +#include + +#include +#include + +#include +#include + +static GLenum shader_type_to_gl(ShaderType type) { + switch (type) { + case VertexShader: + return GL_VERTEX_SHADER; + case FragmentShader: + return GL_FRAGMENT_SHADER; + } + FAIL("shader_type_to_gl(): missing case"); + return GL_INVALID_ENUM; +} + +static lstring make_defines_string(const ShaderDesc* desc) { + lstring defines = {0}; + for (size_t i = 0; i < desc->num_defines; ++i) { + const ShaderCompilerDefine* define = &desc->defines[i]; + lstring_append_cstr(&defines, "#define "); + lstring_append_cstr(&defines, sstring_cstr(&define->name)); + lstring_append_cstr(&defines, " "); + lstring_append_cstr(&defines, sstring_cstr(&define->value)); + lstring_append_cstr(&defines, "\n"); + } + return defines; +} + +/// Creates an OpenGL shader. +/// Returns non-zero on success, 0 on failure. +static GLuint create_shader(const ShaderDesc* desc) { + const GLuint shader = glCreateShader(shader_type_to_gl(desc->type)); + if (!shader) { + return 0; + } + +#if GFX_GL_CONTEXT == GFX_GL_CONTEXT_ES + const char* header = "#version 300 es\n\nprecision highp float;"; +#else + const char* header = "#version 400 core\n\n"; +#endif + + lstring defines = make_defines_string(desc); + + const char* source_bits[] = {header, lstring_cstr(&defines), desc->code}; + const GLint source_lengths[] = { + strlen(header), lstring_length(&defines), strlen(desc->code)}; + + glShaderSource(shader, 3, source_bits, source_lengths); + glCompileShader(shader); + GLint result; + glGetShaderiv(shader, GL_COMPILE_STATUS, &result); + if (result == GL_FALSE) { + GLint log_len; + glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &log_len); + if (log_len > 0) { + char* log = calloc(log_len, sizeof(char)); + glGetShaderInfoLog(shader, log_len, NULL, log); + static const char* sep = "----------"; + LOGE("Failed loading shader: %s\n%s\n%s\n%s", log, sep, desc->code, sep); + free(log); + } else { + LOGE("Failed loading shader:\n%s", desc->code); + } + glDeleteShader(shader); + return 0; + } + ASSERT_GL; + return shader; +} + +bool gfx_compile_shader(Shader* shader, const ShaderDesc* desc) { + shader->id = create_shader(desc); + return shader->id != 0; +} + +void gfx_del_shader(Shader* shader) { + assert(shader); + + if (shader->id) { + glDeleteShader(shader->id); + shader->id = 0; + } + ASSERT_GL; +} diff --git a/src/core/shader.h b/src/core/shader.h new file mode 100644 index 0000000..b9f5679 --- /dev/null +++ b/src/core/shader.h @@ -0,0 +1,17 @@ +#pragma once + +#include + +#include "gl_util.h" + +#include + +typedef struct Shader { + GLuint id; +} Shader; + +/// Compile a new shader. +bool gfx_compile_shader(Shader*, const ShaderDesc*); + +/// Destroy the shader. +void gfx_del_shader(Shader*); diff --git a/src/core/shader_program.c b/src/core/shader_program.c new file mode 100644 index 0000000..3cbe48d --- /dev/null +++ b/src/core/shader_program.c @@ -0,0 +1,291 @@ +#include "shader_program.h" + +#include "gl_util.h" +#include "shader.h" +#include "texture.h" +#include + +#include + +#include +#include + +/// Creates an OpenGL shader program. +/// Returns non-zero on success, 0 on failure. +static GLuint create_program(GLuint vertex_shader, GLuint fragment_shader) { + const GLuint prog = glCreateProgram(); + if (prog == 0) { + LOGE("Failed creating shader program"); + return 0; + } + glAttachShader(prog, vertex_shader); + glAttachShader(prog, fragment_shader); + glLinkProgram(prog); + GLint result; + glGetProgramiv(prog, GL_LINK_STATUS, &result); + if (result == GL_FALSE) { + GLint log_len; + glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &log_len); + if (log_len > 0) { + char* log = calloc(log_len, sizeof(char)); + glGetProgramInfoLog(prog, log_len, NULL, log); + LOGE("Failed creating shader program: %s", log); + free(log); + } else { + LOGE("Failed creating shader program"); + } + glDeleteProgram(prog); + return 0; + } + ASSERT_GL; + return prog; +} + +bool gfx_build_shader_program( + ShaderProgram* prog, const ShaderProgramDesc* desc) { + assert(prog); + assert(desc); + + prog->id = create_program(desc->vertex_shader->id, desc->fragment_shader->id); + return prog->id != 0; +} + +void gfx_del_shader_program(ShaderProgram* prog) { + assert(prog); + + if (prog->id) { + glDeleteProgram(prog->id); + prog->id = 0; + } + ASSERT_GL; +} + +void gfx_activate_shader_program(const ShaderProgram* prog) { + assert(prog); + glUseProgram(prog->id); + ASSERT_GL; +} + +void gfx_deactivate_shader_program(const ShaderProgram* prog) { + assert(prog); + glUseProgram(0); + ASSERT_GL; +} + +static void set_texture_uniform( + GLuint prog, const char* name, int texture_unit, const Texture* texture) { + assert(prog != 0); + assert(name); + assert(texture); + + const GLint location = glGetUniformLocation(prog, name); + if (location >= 0) { + glActiveTexture(GL_TEXTURE0 + texture_unit); + glBindTexture(texture->target, texture->id); + glUniform1i(location, texture_unit); + } +} + +static void set_mat4_uniform( + GLuint prog, const char* name, const mat4* mats, size_t count) { + assert(prog != 0); + assert(name); + assert(mats); + + const GLint location = glGetUniformLocation(prog, name); + if (location >= 0) { + glUniformMatrix4fv(location, count, GL_FALSE, (const float*)mats); + } +} + +static void set_vec3_uniform(GLuint prog, const char* name, vec3 value) { + assert(prog != 0); + assert(name); + + const GLint location = glGetUniformLocation(prog, name); + if (location >= 0) { + glUniform3f(location, value.x, value.y, value.z); + } +} + +static void set_vec4_uniform(GLuint prog, const char* name, vec4 value) { + assert(prog != 0); + assert(name); + + const GLint location = glGetUniformLocation(prog, name); + if (location >= 0) { + glUniform4f(location, value.x, value.y, value.z, value.w); + } +} + +static void set_float_uniform(GLuint prog, const char* name, float value) { + assert(prog != 0); + assert(name); + + const GLint location = glGetUniformLocation(prog, name); + if (location >= 0) { + glUniform1f(location, value); + } +} + +void gfx_apply_uniforms(const ShaderProgram* prog) { + assert(prog); + + int next_texture_unit = 0; + for (int i = 0; i < prog->num_uniforms; ++i) { + const ShaderUniform* uniform = &prog->uniforms[i]; + switch (uniform->type) { + case UniformTexture: + set_texture_uniform( + prog->id, uniform->name.str, next_texture_unit, + uniform->value.texture); + next_texture_unit++; + break; + case UniformMat4: + set_mat4_uniform(prog->id, uniform->name.str, &uniform->value.mat4, 1); + break; + case UniformVec3: + set_vec3_uniform(prog->id, uniform->name.str, uniform->value.vec3); + break; + case UniformVec4: + set_vec4_uniform(prog->id, uniform->name.str, uniform->value.vec4); + break; + case UniformFloat: + set_float_uniform(prog->id, uniform->name.str, uniform->value.scalar); + break; + case UniformMat4Array: + set_mat4_uniform( + prog->id, uniform->name.str, uniform->value.array.values, + uniform->value.array.count); + break; + } + } +} + +// Get the ShaderUniform object by name from the shader program if it already +// exists, or allocate a new one otherwise. +static ShaderUniform* get_or_allocate_uniform( + ShaderProgram* prog, const char* name) { + assert(prog); + assert(name); + + // First search for the uniform in the list. + for (int i = 0; i < prog->num_uniforms; ++i) { + ShaderUniform* uniform = &prog->uniforms[i]; + if (sstring_eq_cstr(uniform->name, name)) { + return uniform; + } + } + + // Create the uniform if it does not exist. + if (prog->num_uniforms == GFX_MAX_UNIFORMS_PER_SHADER) { + FAIL("Exceeded the maximum number of uniforms per shader. Please increase " + "this value."); + return 0; + } + ShaderUniform* uniform = &prog->uniforms[prog->num_uniforms]; + prog->num_uniforms++; + return uniform; +} + +// The functions below save the value of a uniform in the shader program. If the +// uniform does not even exist, then there is no need to store the value. + +void gfx_set_texture_uniform( + ShaderProgram* prog, const char* name, const Texture* texture) { + assert(prog); + assert(name); + assert(texture); + + const GLint location = glGetUniformLocation(prog->id, name); + if (location < 0) { + return; + } + ShaderUniform* uniform = get_or_allocate_uniform(prog, name); + assert(uniform); + uniform->name = sstring_make(name); + uniform->type = UniformTexture; + uniform->value.texture = texture; +} + +void gfx_set_mat4_uniform( + ShaderProgram* prog, const char* name, const mat4* mat) { + assert(prog); + assert(name); + assert(mat); + + const GLint location = glGetUniformLocation(prog->id, name); + if (location < 0) { + return; + } + ShaderUniform* uniform = get_or_allocate_uniform(prog, name); + assert(uniform); + uniform->name = sstring_make(name); + uniform->type = UniformMat4; + uniform->value.mat4 = *mat; +} + +void gfx_set_vec3_uniform(ShaderProgram* prog, const char* name, vec3 value) { + assert(prog); + assert(name); + + const GLint location = glGetUniformLocation(prog->id, name); + if (location < 0) { + return; + } + ShaderUniform* uniform = get_or_allocate_uniform(prog, name); + assert(uniform); + uniform->name = sstring_make(name); + uniform->type = UniformVec3; + uniform->value.vec3 = value; +} + +void gfx_set_vec4_uniform(ShaderProgram* prog, const char* name, vec4 value) { + assert(prog); + assert(name); + + const GLint location = glGetUniformLocation(prog->id, name); + if (location < 0) { + return; + } + ShaderUniform* uniform = get_or_allocate_uniform(prog, name); + assert(uniform); + uniform->name = sstring_make(name); + uniform->type = UniformVec4; + uniform->value.vec4 = value; +} + +void gfx_set_float_uniform(ShaderProgram* prog, const char* name, float value) { + assert(prog); + assert(name); + + // No need to store the uniform on our side if it does not exist in the + // program. + const GLint location = glGetUniformLocation(prog->id, name); + if (location < 0) { + return; + } + ShaderUniform* uniform = get_or_allocate_uniform(prog, name); + assert(uniform); + uniform->name = sstring_make(name); + uniform->type = UniformFloat; + uniform->value.scalar = value; +} + +void gfx_set_mat4_array_uniform( + ShaderProgram* prog, const char* name, const mat4* mats, size_t count) { + assert(prog); + assert(name); + assert(mats); + + const GLint location = glGetUniformLocation(prog->id, name); + if (location < 0) { + return; + } + ShaderUniform* uniform = get_or_allocate_uniform(prog, name); + assert(uniform); + uniform->name = sstring_make(name); + uniform->type = UniformMat4Array; + uniform->value.array.count = count; + uniform->value.array.values = mats; +} diff --git a/src/core/shader_program.h b/src/core/shader_program.h new file mode 100644 index 0000000..1443663 --- /dev/null +++ b/src/core/shader_program.h @@ -0,0 +1,24 @@ +#pragma once + +#include +#include + +#include "gl_util.h" + +#include + +#include + +typedef struct Texture Texture; + +typedef struct ShaderProgram { + GLuint id; + ShaderUniform uniforms[GFX_MAX_UNIFORMS_PER_SHADER]; + int num_uniforms; +} ShaderProgram; + +/// Create a new shader program. +bool gfx_build_shader_program(ShaderProgram*, const ShaderProgramDesc*); + +/// Destroy the shader program. +void gfx_del_shader_program(ShaderProgram*); diff --git a/src/core/texture.c b/src/core/texture.c new file mode 100644 index 0000000..89f7ec0 --- /dev/null +++ b/src/core/texture.c @@ -0,0 +1,218 @@ +#include "texture.h" + +#include + +#include +#include + +#include + +bool gfx_init_texture(Texture* texture, const TextureDesc* desc) { + assert(texture); + assert(desc); + + glGenTextures(1, &texture->id); + if (!texture->id) { + log_error("glGenTextures() failed"); + return false; + } + texture->target = to_GL_dimension(desc->dimension); + glBindTexture(texture->target, texture->id); + + // glTexStorageXD + const int levels = + desc->mipmaps + ? max(max(log2(desc->width), log2(desc->height)), log2(desc->depth)) + + 1 + : 1; + const GLenum internal_format = to_GL_internal_format(desc->format); + switch (texture->target) { + case GL_TEXTURE_2D: + case GL_TEXTURE_CUBE_MAP: + glTexStorage2D( + texture->target, levels, internal_format, desc->width, desc->height); + break; + default: + FAIL("Unhandled texture dimension"); + gfx_del_texture(texture); + return false; + } + + texture->format = to_GL_format(desc->format); + texture->type = to_GL_type(desc->format); + texture->width = desc->width; + texture->height = desc->height; + gfx_update_texture(texture, &desc->data); + + // gfx_update_texture() unbinds the texture at the end, so re-bind it here. + glBindTexture(texture->target, texture->id); + + // Mipmaps. + if (desc->mipmaps) { + glGenerateMipmap(texture->target); + } + + // Texture filtering. + const bool linear = desc->filtering == LinearFiltering; + GLenum min = desc->mipmaps ? (linear ? GL_LINEAR_MIPMAP_LINEAR + : GL_NEAREST_MIPMAP_NEAREST) + : (linear ? GL_LINEAR : GL_NEAREST); + GLenum mag = linear ? GL_LINEAR : GL_NEAREST; + glTexParameteri(texture->target, GL_TEXTURE_MIN_FILTER, min); + glTexParameteri(texture->target, GL_TEXTURE_MAG_FILTER, mag); + + // Texture wrapping. + GLenum wrap = GL_INVALID_ENUM; + switch (desc->wrap) { + case Repeat: + wrap = GL_REPEAT; + break; + case ClampToEdge: + wrap = GL_CLAMP_TO_EDGE; + break; + } + glTexParameteri(texture->target, GL_TEXTURE_WRAP_R, wrap); + glTexParameteri(texture->target, GL_TEXTURE_WRAP_S, wrap); + glTexParameteri(texture->target, GL_TEXTURE_WRAP_T, wrap); + + glBindTexture(texture->target, 0); + return true; +} + +void gfx_del_texture(Texture* texture) { + assert(texture); + + if (texture->id) { + glDeleteTextures(1, &texture->id); + texture->id = 0; + } +} + +void gfx_update_texture(Texture* texture, const TextureDataDesc* desc) { + assert(texture); + assert(desc); + + glBindTexture(texture->target, texture->id); + + // glTexSubImageXD + switch (texture->target) { + case GL_TEXTURE_2D: + if (desc->pixels) { + glTexSubImage2D( + GL_TEXTURE_2D, /*level=*/0, /*xoffset=*/0, + /*yoffset=*/0, texture->width, texture->height, texture->format, + texture->type, desc->pixels); + } + break; + case GL_TEXTURE_CUBE_MAP: + for (int i = 0; i < 6; ++i) { + const void* pixels = *(&desc->cubemap.pixels_pos_x + i); + if (pixels) { + glTexSubImage2D( + GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, /*level=*/0, /*xoffset=*/0, + /*yoffset=*/0, texture->width, texture->height, texture->format, + texture->type, pixels); + } + } + break; + default: + FAIL("Unhandled texture dimension"); + break; + } + + glBindTexture(texture->target, 0); +} + +GLenum to_GL_dimension(TextureDimension dim) { + switch (dim) { + case Texture2D: + return GL_TEXTURE_2D; + case TextureCubeMap: + return GL_TEXTURE_CUBE_MAP; + default: + FAIL("Unhandled TextureDimension"); + return GL_INVALID_ENUM; + } +} + +GLenum to_GL_internal_format(TextureFormat format) { + switch (format) { + case TextureDepth: + return GL_DEPTH_COMPONENT; + case TextureRG16: + return GL_RG16; + case TextureRG16F: + return GL_RG16F; + case TextureRGB8: + return GL_RGB8; + case TextureR11G11B10F: + return GL_R11F_G11F_B10F; + case TextureRGBA8: + return GL_RGBA8; + case TextureSRGB8: + return GL_SRGB8; + case TextureSRGBA8: + return GL_SRGB8_ALPHA8; + default: + FAIL("Unhandled TextureFormat"); + return GL_INVALID_ENUM; + } +} + +GLenum to_GL_format(TextureFormat format) { + switch (format) { + case TextureDepth: + return GL_DEPTH_COMPONENT; + case TextureRG16: + case TextureRG16F: + return GL_RG; + case TextureRGB8: + case TextureR11G11B10F: + case TextureSRGB8: + return GL_RGB; + case TextureRGBA8: + case TextureSRGBA8: + return GL_RGBA; + default: + FAIL("Unhandled TextureFormat"); + return GL_INVALID_ENUM; + } +} + +GLenum to_GL_type(TextureFormat format) { + switch (format) { + case TextureDepth: + case TextureRG16F: + case TextureR11G11B10F: + return GL_FLOAT; + case TextureRG16: + case TextureRGB8: + case TextureRGBA8: + case TextureSRGB8: + case TextureSRGBA8: + return GL_UNSIGNED_BYTE; + default: + FAIL("Unhandled TextureFormat"); + return GL_INVALID_ENUM; + } +} + +GLenum to_GL_cubemap_face(CubemapFace face) { + switch (face) { + case CubemapFacePosX: + return GL_TEXTURE_CUBE_MAP_POSITIVE_X; + case CubemapFaceNegX: + return GL_TEXTURE_CUBE_MAP_NEGATIVE_X; + case CubemapFacePosY: + return GL_TEXTURE_CUBE_MAP_POSITIVE_Y; + case CubemapFaceNegY: + return GL_TEXTURE_CUBE_MAP_NEGATIVE_Y; + case CubemapFacePosZ: + return GL_TEXTURE_CUBE_MAP_POSITIVE_Z; + case CubemapFaceNegZ: + return GL_TEXTURE_CUBE_MAP_NEGATIVE_Z; + default: + FAIL("Unhandled CubemapFace"); + return GL_INVALID_ENUM; + } +} diff --git a/src/core/texture.h b/src/core/texture.h new file mode 100644 index 0000000..4af41e9 --- /dev/null +++ b/src/core/texture.h @@ -0,0 +1,35 @@ +#pragma once + +#include + +#include "gl_util.h" + +typedef struct Texture { + GLuint id; + GLenum target; + GLenum format; + GLenum type; + int width; + int height; +} Texture; + +/// Create a new texture. +bool gfx_init_texture(Texture*, const TextureDesc*); + +/// Destroy the texture. +void gfx_del_texture(Texture*); + +/// Converts a TextureDimension into the OpenGL enum equivalent. +GLenum to_GL_dimension(TextureDimension dim); + +/// Converts a texture format into an OpenGL internal format. +GLenum to_GL_internal_format(TextureFormat format); + +/// Converts a texture format into an OpenGL format. +GLenum to_GL_format(TextureFormat format); + +/// Converts a texture format into an OpenGL type. +GLenum to_GL_type(TextureFormat format); + +/// Converts a cubemap face into the OpenGL enum equivalent. +GLenum to_GL_cubemap_face(CubemapFace face); diff --git a/src/gfx.c b/src/gfx.c new file mode 100644 index 0000000..cd2ac90 --- /dev/null +++ b/src/gfx.c @@ -0,0 +1,73 @@ +#include + +#include "asset/asset_cache.h" +#include "core/core_impl.h" +#include "renderer/imm_renderer_impl.h" +#include "renderer/renderer_impl.h" +#include "scene/scene_memory.h" + +#include + +#include +#include + +typedef struct Gfx { + AssetCache asset_cache; + GfxCore gfxcore; + Renderer renderer; + ImmRenderer imm_renderer; +} Gfx; + +Gfx* gfx_init(void) { + Gfx* gfx = calloc(1, sizeof(Gfx)); + if (!gfx) { + return 0; + } + gfx_init_gfxcore(&gfx->gfxcore); + if (!renderer_make(&gfx->renderer, &gfx->gfxcore)) { + gfx_destroy(&gfx); + return 0; + } + if (!imm_renderer_make(&gfx->imm_renderer, &gfx->gfxcore)) { + // TODO: Add error logs to the initialization failure cases here and inside + // the renderers. + gfx_destroy(&gfx); + return 0; + } + gfx_init_asset_cache(&gfx->asset_cache); + scene_mem_init(); + return gfx; +} + +void gfx_destroy(Gfx** gfx) { + if (!gfx) { + return; + } + scene_mem_destroy(); + gfx_destroy_asset_cache(&(*gfx)->asset_cache); + renderer_destroy(&(*gfx)->renderer); + imm_renderer_destroy(&(*gfx)->imm_renderer); + gfx_del_gfxcore(&(*gfx)->gfxcore); + free(*gfx); + *gfx = 0; +} + +GfxCore* gfx_get_core(Gfx* gfx) { + assert(gfx); + return &gfx->gfxcore; +} + +Renderer* gfx_get_renderer(Gfx* gfx) { + assert(gfx); + return &gfx->renderer; +} + +ImmRenderer* gfx_get_imm_renderer(Gfx* gfx) { + assert(gfx); + return &gfx->imm_renderer; +} + +AssetCache* gfx_get_asset_cache(Gfx* gfx) { + assert(gfx); + return &gfx->asset_cache; +} diff --git a/src/gfx_assert.h b/src/gfx_assert.h new file mode 100644 index 0000000..f4b3aa5 --- /dev/null +++ b/src/gfx_assert.h @@ -0,0 +1,5 @@ +#pragma once + +#include + +#include // Include after log to use log's LOGE(). diff --git a/src/renderer/imm_renderer.c b/src/renderer/imm_renderer.c new file mode 100644 index 0000000..8cf3a10 --- /dev/null +++ b/src/renderer/imm_renderer.c @@ -0,0 +1,260 @@ +#include "imm_renderer_impl.h" + +#include +#include + +#include + +#include +#include // memcpy + +bool imm_renderer_make(ImmRenderer* renderer, GfxCore* gfxcore) { + assert(renderer); + assert(gfxcore); + + const size_t num_triangle_verts = IMM_MAX_NUM_TRIANGLES * 3; + + renderer->gfxcore = gfxcore; + + renderer->triangles = gfx_make_geometry( + gfxcore, &(GeometryDesc){ + .type = Triangles, + .buffer_usage = BufferDynamic, + .num_verts = num_triangle_verts, + .positions3d = (BufferView3d){ + .size_bytes = num_triangle_verts * sizeof(vec3)}}); + if (!renderer->triangles) { + goto cleanup; + } + + renderer->shader = gfx_make_immediate_mode_shader(gfxcore); + if (!renderer->shader) { + goto cleanup; + } + + renderer->matrix_stack[0] = mat4_id(); + renderer->stack_pointer = 0; + + gfx_imm_set_colour(renderer, vec4_make(0.0, 0.0, 0.0, 1.0)); + + return true; + +cleanup: + imm_renderer_destroy(renderer); + return false; +} + +void imm_renderer_destroy(ImmRenderer* renderer) { + assert(renderer); + assert(renderer->gfxcore); + + if (renderer->triangles) { + gfx_destroy_geometry(renderer->gfxcore, &renderer->triangles); + // TODO: Could also destroy the geometry's buffers here. + } + + if (renderer->shader) { + gfx_destroy_shader_program(renderer->gfxcore, &renderer->shader); + } +} + +void imm_renderer_flush(ImmRenderer* renderer) { + assert(renderer); + + if (renderer->num_triangle_verts > 0) { + gfx_update_geometry( + renderer->triangles, + &(GeometryDesc){ + .num_verts = renderer->num_triangle_verts, + .positions3d = (BufferView3d){ + .data = renderer->triangle_verts, + .size_bytes = renderer->num_triangle_verts * sizeof(vec3)} + }); + + gfx_apply_uniforms(renderer->shader); + gfx_render_geometry(renderer->triangles); + + renderer->num_triangle_verts = 0; + } +} + +void gfx_imm_start(ImmRenderer* renderer) { + assert(renderer); + // Shader uniforms are applied lazily. + // TODO: In the event that gfx_activate_shader_program() activates uniforms + // automatically for convenience, call an overload here that doesn't do so. + ShaderProgram* shader = renderer->shader; + gfx_activate_shader_program(shader); +} + +void gfx_imm_end(ImmRenderer* renderer) { + assert(renderer); + imm_renderer_flush(renderer); + gfx_deactivate_shader_program(renderer->shader); +} + +void gfx_imm_draw_triangles( + ImmRenderer* renderer, const vec3 verts[], size_t num_triangles) { + assert(renderer); + assert(verts); + const size_t new_verts = num_triangles * 3; + assert( + renderer->num_triangle_verts + new_verts < (IMM_MAX_NUM_TRIANGLES * 3)); + + memcpy( + renderer->triangle_verts + renderer->num_triangle_verts, verts, + new_verts * sizeof(vec3)); + + renderer->num_triangle_verts += new_verts; +} + +void gfx_imm_draw_triangle(ImmRenderer* renderer, const vec3 verts[3]) { + gfx_imm_draw_triangles(renderer, verts, 1); +} + +void gfx_imm_draw_aabb2(ImmRenderer* renderer, aabb2 box) { + assert(renderer); + + // clang-format off + const vec3 verts[4] = { + vec3_make(box.min.x, box.min.y, 0), // 3 ---- 2 + vec3_make(box.max.x, box.min.y, 0), // | | + vec3_make(box.max.x, box.max.y, 0), // | | + vec3_make(box.min.x, box.max.y, 0)}; // 0 ---- 1 + // clang-format on + +#define tri(i0, i1, i2) verts[i0], verts[i1], verts[i2] + const vec3 tris[6] = {tri(0, 1, 2), tri(0, 2, 3)}; +#undef tri + + gfx_imm_draw_triangles(renderer, tris, 2); +} + +void gfx_imm_draw_aabb3(ImmRenderer* renderer, aabb3 box) { + assert(renderer); + + // clang-format off + const vec3 vertices[8] = { + vec3_make(box.min.x, box.min.y, box.max.z), // 7 ----- 6 + vec3_make(box.max.x, box.min.y, box.max.z), // / /| + vec3_make(box.max.x, box.max.y, box.max.z), // 3 ----- 2 | + vec3_make(box.min.x, box.max.y, box.max.z), // | | | + vec3_make(box.min.x, box.min.y, box.min.z), // | 4 ----- 5 + vec3_make(box.max.x, box.min.y, box.min.z), // |/ |/ + vec3_make(box.max.x, box.max.y, box.min.z), // 0 ----- 1 + vec3_make(box.min.x, box.max.y, box.min.z)}; + // clang-format on + + gfx_imm_draw_box3(renderer, vertices); +} + +void gfx_imm_draw_box3(ImmRenderer* renderer, const vec3 vertices[8]) { + assert(renderer); + assert(vertices); + + // 7 ----- 6 + // / /| + // 3 ----- 2 | + // | | | + // | 4 ----- 5 + // |/ |/ + // 0 ----- 1 + +#define tri(i0, i1, i2) vertices[i0], vertices[i1], vertices[i2] + const vec3 tris[36] = {// Front. + tri(0, 1, 2), tri(0, 2, 3), + // Right. + tri(1, 5, 6), tri(1, 6, 2), + // Back. + tri(5, 4, 7), tri(5, 7, 6), + // Left. + tri(4, 0, 03), tri(4, 3, 7), + // Top. + tri(3, 2, 6), tri(3, 6, 7), + // Bottom. + tri(0, 4, 5), tri(0, 5, 1)}; + + gfx_imm_draw_triangles(renderer, tris, 12); +} + +// Load the top of the matrix stack into the shader. +static void update_shader_model_matrix(ImmRenderer* renderer) { + assert(renderer); + imm_renderer_flush(renderer); + gfx_set_mat4_uniform( + renderer->shader, "Model", + &renderer->matrix_stack[renderer->stack_pointer]); +} + +void gfx_imm_load_identity(ImmRenderer* renderer) { + assert(renderer); + renderer->matrix_stack[0] = mat4_id(); + renderer->stack_pointer = 0; + update_shader_model_matrix(renderer); +} + +void gfx_imm_push_matrix(ImmRenderer* renderer, const mat4* matrix) { + assert(renderer); + assert(matrix); + assert(renderer->stack_pointer >= 0); + assert(renderer->stack_pointer < IMM_MAX_NUM_MATRICES); // TODO: hard assert. + + renderer->matrix_stack[renderer->stack_pointer + 1] = + mat4_mul(*matrix, renderer->matrix_stack[renderer->stack_pointer]); + renderer->stack_pointer += 1; + + update_shader_model_matrix(renderer); +} + +void gfx_imm_pop_matrix(ImmRenderer* renderer) { + assert(renderer); + assert(renderer->stack_pointer > 0); // TODO: hard assert. + + // For debugging, zero out the matrix stack as matrices are popped out. + memset( + &renderer->matrix_stack[renderer->stack_pointer], 0, + sizeof(renderer->matrix_stack[0])); + + renderer->stack_pointer -= 1; + + update_shader_model_matrix(renderer); +} + +void gfx_imm_translate(ImmRenderer* renderer, vec3 offset) { + assert(renderer); + const mat4 mat = mat4_translate(offset); + gfx_imm_push_matrix(renderer, &mat); +} + +void gfx_imm_set_camera(ImmRenderer* renderer, const Camera* camera) { + assert(renderer); + assert(renderer->shader); + imm_renderer_flush(renderer); + const mat4 view = spatial3_inverse_transform(&camera->spatial); + const mat4 view_proj = mat4_mul(camera->projection, view); + gfx_imm_set_view_projection_matrix(renderer, &view_proj); +} + +void gfx_imm_set_model_matrix(ImmRenderer* renderer, const mat4* model) { + assert(renderer); + assert(model); + imm_renderer_flush(renderer); + renderer->matrix_stack[0] = *model; + renderer->stack_pointer = 0; + update_shader_model_matrix(renderer); +} + +void gfx_imm_set_view_projection_matrix( + ImmRenderer* renderer, const mat4* view_proj) { + assert(renderer); + assert(renderer->shader); + imm_renderer_flush(renderer); + gfx_set_mat4_uniform(renderer->shader, "ViewProjection", view_proj); +} + +void gfx_imm_set_colour(ImmRenderer* renderer, vec4 colour) { + assert(renderer); + assert(renderer->shader); + imm_renderer_flush(renderer); + gfx_set_vec4_uniform(renderer->shader, "Colour", colour); +} diff --git a/src/renderer/imm_renderer_impl.h b/src/renderer/imm_renderer_impl.h new file mode 100644 index 0000000..5ece354 --- /dev/null +++ b/src/renderer/imm_renderer_impl.h @@ -0,0 +1,44 @@ +#pragma once + +#include +#include + +#include +#include + +#include +#include + +typedef struct Geometry Geometry; +typedef struct ShaderProgram ShaderProgram; + +/// Immediate mode renderer. +/// +/// Currently, the immediate mode renderer can only draw up to a maximum number +/// of primitives per frame. It does not adjust this number dynamically. Keeps +/// things simple while the extra complexity is not needed. +typedef struct ImmRenderer { + GfxCore* gfxcore; + ShaderProgram* shader; + Geometry* triangles; + size_t num_triangle_verts; // Number of triangle verts this frame. + // TODO: wireframe rendering. + struct { + bool wireframe : 1; + } flags; + vec3 triangle_verts[IMM_MAX_NUM_TRIANGLES * 3]; + // Matrix stack contains pre-multiplied matrices. + // It is also never empty. The top of the stack is an identity matrix when the + // stack is "empty" from the user's perspective. + mat4 matrix_stack[IMM_MAX_NUM_MATRICES]; + int stack_pointer; +} ImmRenderer; + +/// Create a new immediate mode renderer. +bool imm_renderer_make(ImmRenderer*, GfxCore*); + +/// Destroy the immediate mode renderer. +void imm_renderer_destroy(ImmRenderer*); + +/// Flush draw commands. +void imm_renderer_flush(ImmRenderer*); diff --git a/src/renderer/renderer.c b/src/renderer/renderer.c new file mode 100644 index 0000000..c2a7dda --- /dev/null +++ b/src/renderer/renderer.c @@ -0,0 +1,396 @@ +#include "renderer_impl.h" + +#include "scene/animation_impl.h" +#include "scene/camera_impl.h" +#include "scene/light_impl.h" +#include "scene/material_impl.h" +#include "scene/mesh_impl.h" +#include "scene/model_impl.h" +#include "scene/node_impl.h" +#include "scene/object_impl.h" +#include "scene/scene_impl.h" +#include "scene/scene_memory.h" + +#include +#include +#include + +#include +#include +#include + +#include + +// TODO: Move to a header like "constants.h". +static const int IRRADIANCE_MAP_WIDTH = 1024; +static const int IRRADIANCE_MAP_HEIGHT = 1024; +static const int PREFILTERED_ENVIRONMENT_MAP_WIDTH = 128; +static const int PREFILTERED_ENVIRONMENT_MAP_HEIGHT = 128; +static const int BRDF_INTEGRATION_MAP_WIDTH = 512; +static const int BRDF_INTEGRATION_MAP_HEIGHT = 512; + +bool renderer_make(Renderer* renderer, GfxCore* gfxcore) { + assert(renderer); + assert(gfxcore); + + renderer->gfxcore = gfxcore; + + return true; +} + +void renderer_destroy(Renderer* renderer) { + if (!renderer) { + return; + } + assert(renderer->gfxcore); + GfxCore* gfxcore = renderer->gfxcore; + if (renderer->ibl) { + gfx_destroy_ibl(gfxcore, &renderer->ibl); + } + if (renderer->shaders.debug) { + gfx_destroy_shader_program(gfxcore, &renderer->shaders.debug); + } + if (renderer->shaders.normals) { + gfx_destroy_shader_program(gfxcore, &renderer->shaders.normals); + } + if (renderer->shaders.normal_mapped_normals) { + gfx_destroy_shader_program( + gfxcore, &renderer->shaders.normal_mapped_normals); + } + if (renderer->shaders.tangents) { + gfx_destroy_shader_program(gfxcore, &renderer->shaders.tangents); + } +} + +/// Initialize renderer state for IBL if not already initialized. +static bool init_ibl(Renderer* renderer) { + assert(renderer); + + if (!renderer->ibl && !(renderer->ibl = gfx_make_ibl(renderer->gfxcore))) { + return false; + } + + if (!renderer->brdf_integration_map && + !(renderer->brdf_integration_map = gfx_make_brdf_integration_map( + renderer->ibl, renderer->gfxcore, BRDF_INTEGRATION_MAP_WIDTH, + BRDF_INTEGRATION_MAP_HEIGHT))) { + return false; + } + + return true; +} + +static ShaderProgram* load_shader(Renderer* renderer, RenderSceneMode mode) { + assert(renderer); + +#define LOAD_AND_RETURN(pShader, constructor) \ + { \ + if (!pShader) { \ + pShader = constructor(renderer->gfxcore); \ + } \ + assert(pShader); \ + return pShader; \ + } + + switch (mode) { + case RenderDefault: + return 0; + case RenderDebug: + LOAD_AND_RETURN(renderer->shaders.debug, gfx_make_debug3d_shader); + case RenderNormals: + LOAD_AND_RETURN(renderer->shaders.normals, gfx_make_view_normals_shader); + case RenderNormalMappedNormals: + LOAD_AND_RETURN( + renderer->shaders.normal_mapped_normals, + gfx_make_view_normal_mapped_normals_shader); + case RenderTangents: + LOAD_AND_RETURN(renderer->shaders.tangents, gfx_make_view_tangents_shader); + } + assert(false); + return 0; +} + +// static void log_matrix(const mat4* m) { +// for (int row = 0; row < 4; ++row) { +// LOGI("[ %5.2f, %5.2f, %5.2f, %5.2f ]", m->val[0][row], m->val[1][row], +// m->val[2][row], m->val[3][row]); +// } +// } + +/// Computes irradiance and prefiltered environment maps for the light if they +/// have not been already computed. +static bool setup_environment_light( + Renderer* renderer, GfxCore* gfxcore, EnvironmentLight* light) { + assert(renderer); + assert(light); + + if (!init_ibl(renderer)) { + return false; + } + + if (light->irradiance_map) { + assert(light->prefiltered_environment_map); + return true; + } + + Texture* irradiance_map = 0; + Texture* prefiltered_environment_map = 0; + + if (!(irradiance_map = gfx_make_irradiance_map( + renderer->ibl, gfxcore, light->environment_map, + IRRADIANCE_MAP_WIDTH, IRRADIANCE_MAP_HEIGHT))) { + goto cleanup; + } + + int max_mip_level = 0; + if (!(prefiltered_environment_map = gfx_make_prefiltered_environment_map( + renderer->ibl, gfxcore, light->environment_map, + PREFILTERED_ENVIRONMENT_MAP_WIDTH, + PREFILTERED_ENVIRONMENT_MAP_HEIGHT, &max_mip_level))) { + goto cleanup; + } + + light->irradiance_map = irradiance_map; + light->prefiltered_environment_map = prefiltered_environment_map; + light->max_reflection_lod = max_mip_level; + + return true; + +cleanup: + if (irradiance_map) { + gfx_destroy_texture(gfxcore, &irradiance_map); + } + if (prefiltered_environment_map) { + gfx_destroy_texture(gfxcore, &prefiltered_environment_map); + } + return false; +} + +typedef struct RenderState { + GfxCore* gfxcore; + Renderer* renderer; + ShaderProgram* shader; // Null to use scene shaders. + const Scene* scene; + const Camera* camera; + const mat4* camera_rotation; // From camera to world space, rotation only. + const mat4* view_matrix; + const mat4* projection; + const float fovy; + const float aspect; + Light* environment_light; + const Anima* anima; + size_t num_joints; + mat4 joint_matrices[GFX_MAX_NUM_JOINTS]; +} RenderState; + +/// Load joint matrices into the render state. +static void load_skeleton(RenderState* state, skeleton_idx skeleton_index) { + assert(state); + assert(skeleton_index.val != 0); + + const Skeleton* skeleton = mem_get_skeleton(skeleton_index); + assert(skeleton); + assert(skeleton->num_joints <= GFX_MAX_NUM_JOINTS); + + state->num_joints = skeleton->num_joints; + + for (size_t i = 0; i < skeleton->num_joints; ++i) { + const joint_idx joint_index = skeleton->joints[i]; + const Joint* joint = &state->anima->joints[joint_index]; + state->joint_matrices[i] = joint->joint_matrix; + } +} + +/// Draw the scene recursively. +static void draw_recursively( + RenderState* state, mat4 parent_transform, const SceneNode* node) { + assert(state); + const mat4 node_transform = mat4_mul(parent_transform, node->transform); + + // Anima. + if (node->type == AnimaNode) { + state->anima = gfx_get_node_anima(node); + } + // Activate light. + else if (node->type == LightNode) { + Light* light = mem_get_light(node->light); + assert(light); + + if (light->type == EnvironmentLightType) { + bool result = setup_environment_light( + state->renderer, state->gfxcore, &light->environment); + // TODO: Handle the result in a better way. + assert(result); + state->environment_light = light; + } + } + // Model. + else if (node->type == ModelNode) { + const Model* model = gfx_get_node_model(node); + const SceneNode* root = mem_get_node(model->root); + draw_recursively(state, parent_transform, root); + } + // Render object. + else if (node->type == ObjectNode) { + const SceneObject* object = mem_get_object(node->object); + assert(object); + + // TODO: Here we would frustum-cull the object. + + // TODO: Avoid computing matrices like Modelview or MVP if the shader does + // not use them. + const mat4 model_matrix = node_transform; + const mat4 modelview = mat4_mul(*state->view_matrix, model_matrix); + const mat4 mvp = mat4_mul(*state->projection, modelview); + + if (object->skeleton.val) { + load_skeleton(state, object->skeleton); + } + + for (mesh_link_idx mesh_link_index = object->mesh_link; + mesh_link_index.val;) { + const MeshLink* mesh_link = mem_get_mesh_link(mesh_link_index); + mesh_link_index = mesh_link->next; + + const Mesh* mesh = mem_get_mesh(mesh_link->mesh); + if (!mesh) { + continue; + } + assert(mesh->geometry); + assert(mesh->material); + + // TODO: Here we would frustum-cull the mesh. The AABB would have to be + // transformed by the model matrix. Rotation would make the AABB + // relatively large, but still, the culling would be conservative. + + // Apply common shader uniforms not captured by materials. + ShaderProgram* shader = state->shader ? state->shader : mesh->shader; + gfx_set_mat4_uniform(shader, "ModelMatrix", &model_matrix); + gfx_set_mat4_uniform(shader, "Modelview", &modelview); + gfx_set_mat4_uniform(shader, "View", state->view_matrix); + gfx_set_mat4_uniform(shader, "Projection", state->projection); + gfx_set_mat4_uniform(shader, "MVP", &mvp); + gfx_set_mat4_uniform(shader, "CameraRotation", state->camera_rotation); + gfx_set_float_uniform(shader, "Fovy", state->fovy); + gfx_set_float_uniform(shader, "Aspect", state->aspect); + if (state->camera) { + gfx_set_vec3_uniform( + shader, "CameraPosition", state->camera->spatial.p); + } + if (state->num_joints > 0) { + gfx_set_mat4_array_uniform( + shader, "JointMatrices", state->joint_matrices, state->num_joints); + } + // Apply lights. + if (state->environment_light) { + const EnvironmentLight* light = &state->environment_light->environment; + assert(light->environment_map); + assert(light->irradiance_map); + assert(light->prefiltered_environment_map); + assert(state->renderer->brdf_integration_map); + gfx_set_texture_uniform( + shader, "BRDFIntegrationMap", + state->renderer->brdf_integration_map); + gfx_set_texture_uniform(shader, "Sky", light->environment_map); + gfx_set_texture_uniform(shader, "IrradianceMap", light->irradiance_map); + gfx_set_texture_uniform( + shader, "PrefilteredEnvironmentMap", + light->prefiltered_environment_map); + gfx_set_float_uniform( + shader, "MaxReflectionLOD", light->max_reflection_lod); + } + material_activate(shader, mesh->material); + gfx_activate_shader_program(shader); + gfx_apply_uniforms(shader); + gfx_render_geometry(mesh->geometry); + } + + // Reset state for next object. + state->num_joints = 0; + } + + // Render children recursively. + for (node_idx child_index = node->child; child_index.val;) { + const SceneNode* child = mem_get_node(child_index); + draw_recursively(state, node_transform, child); + child_index = child->next; + } +} + +void gfx_render_scene(Renderer* renderer, const RenderSceneParams* params) { + assert(renderer); + assert(params); + assert(params->scene); + + ShaderProgram* const shader = load_shader(renderer, params->mode); + + const Scene* scene = params->scene; + const SceneCamera* camera = params->camera; + + GfxCore* gfxcore = renderer->gfxcore; + + mat4 projection, camera_rotation, view_matrix; + if (camera) { + projection = camera->camera.projection; + camera_rotation = + mat4_rotation(spatial3_transform(&camera->camera.spatial)); + view_matrix = spatial3_inverse_transform(&camera->camera.spatial); + } else { + projection = mat4_id(); + camera_rotation = mat4_id(); + view_matrix = mat4_id(); + } + + int x, y, width, height; + gfx_get_viewport(gfxcore, &x, &y, &width, &height); + const float aspect = (float)width / (float)height; + + RenderState state = { + .gfxcore = gfxcore, + .renderer = renderer, + .shader = shader, + .scene = scene, + .camera = &camera->camera, + .camera_rotation = &camera_rotation, + .view_matrix = &view_matrix, + .projection = &projection, + .environment_light = 0, + // Assuming a perspective matrix. + .fovy = atan(1.0 / (mat4_at(projection, 1, 1))) * 2, + .aspect = aspect}; + + draw_recursively(&state, mat4_id(), scene->root); +} + +static void update_rec(SceneNode* node, const SceneCamera* camera, R t) { + assert(node); + assert(camera); + + const NodeType node_type = gfx_get_node_type(node); + + // TODO: Models do not need to be animated if they are not visible to the + // camera. + if (node_type == AnimaNode) { + Anima* anima = gfx_get_node_anima_mut(node); + gfx_update_animation(anima, (R)t); + } else if (node_type == ModelNode) { + Model* model = gfx_get_node_model_mut(node); + SceneNode* root = gfx_get_model_root_mut(model); + update_rec(root, camera, t); + } + + // Children. + SceneNode* child = gfx_get_node_child_mut(node); + while (child) { + update_rec(child, camera, t); + child = gfx_get_node_sibling_mut(child); + } +} + +void gfx_update(Scene* scene, const SceneCamera* camera, R t) { + assert(scene); + assert(camera); + + SceneNode* node = gfx_get_scene_root(scene); + update_rec(node, camera, t); +} diff --git a/src/renderer/renderer_impl.h b/src/renderer/renderer_impl.h new file mode 100644 index 0000000..fc14dcb --- /dev/null +++ b/src/renderer/renderer_impl.h @@ -0,0 +1,27 @@ +#pragma once + +#include + +#include + +typedef struct IBL IBL; +typedef struct ShaderProgram ShaderProgram; +typedef struct Texture Texture; + +typedef struct Renderer { + GfxCore* gfxcore; + IBL* ibl; + Texture* brdf_integration_map; + struct { + ShaderProgram* debug; + ShaderProgram* normals; + ShaderProgram* normal_mapped_normals; + ShaderProgram* tangents; + } shaders; +} Renderer; + +/// Create a new renderer. +bool renderer_make(Renderer*, GfxCore*); + +/// Destroy the renderer. +void renderer_destroy(Renderer*); diff --git a/src/scene/animation.c b/src/scene/animation.c new file mode 100644 index 0000000..08d02ce --- /dev/null +++ b/src/scene/animation.c @@ -0,0 +1,524 @@ +#include "animation_impl.h" + +#include "node_impl.h" +#include "scene_memory.h" + +#include + +// #include // Debugging. + +static const R PLAYBACK_UNINITIALIZED = -1; + +static joint_idx get_anima_root_joint_index(Anima* anima) { + assert(anima); + assert(anima->num_joints > 0); + assert(anima->num_joints < GFX_MAX_NUM_JOINTS); + return anima->num_joints - 1; +} + +static Joint* get_anima_root_joint(Anima* anima) { + assert(anima); + return &anima->joints[get_anima_root_joint_index(anima)]; +} + +static const Joint* get_anima_joint(const Anima* anima, joint_idx index) { + assert(anima); + assert(index < GFX_MAX_NUM_JOINTS); + assert(index != INDEX_NONE); + assert(index < anima->num_joints); + return &anima->joints[index]; +} + +static Joint* get_anima_joint_mut(Anima* anima, joint_idx index) { + return (Joint*)get_anima_joint(anima, index); +} + +static const Joint* get_skeleton_joint( + const Anima* anima, const Skeleton* skeleton, joint_idx index) { + assert(anima); + assert(skeleton); + return get_anima_joint(anima, skeleton->joints[index]); +} + +static void set_joint_parent( + Anima* anima, joint_idx joint_index, joint_idx parent_index) { + assert(anima); + assert(joint_index != INDEX_NONE); + assert(joint_index != get_anima_root_joint_index(anima)); + assert(parent_index != INDEX_NONE); + + Joint* parent = get_anima_joint_mut(anima, parent_index); + + if (parent->child == INDEX_NONE) { + parent->child = joint_index; + } else { + // Find the last child in the chain of children. + Joint* child = get_anima_joint_mut(anima, parent->child); + while (child->next != INDEX_NONE) { + child = get_anima_joint_mut(anima, child->next); + } + // Wire up this joint as the last child's sibling. + child->next = joint_index; + } +} + +static void make_joint(Anima* anima, const JointDesc* desc, Joint* joint) { + assert(anima); + assert(desc); + assert(joint); + + // The joint matrix needs to be initialized so that meshes look right even if + // no animation is played. Initializing joint matrices to the identity makes + // meshes appear in their bind pose. + joint->child = INDEX_NONE; + joint->next = INDEX_NONE; + joint->transform = mat4_id(); + joint->inv_bind_matrix = desc->inv_bind_matrix; + joint->joint_matrix = mat4_id(); + joint->box = desc->box; +} + +static Skeleton* make_skeleton(const SkeletonDesc* desc) { + assert(desc); + assert(desc->num_joints <= GFX_MAX_NUM_JOINTS); + + Skeleton* skeleton = mem_alloc_skeleton(); + skeleton->num_joints = desc->num_joints; + memcpy( + skeleton->joints, desc->joints, + desc->num_joints * sizeof(skeleton->joints[0])); + return skeleton; +} + +static Animation* make_animation(const AnimationDesc* desc) { + assert(desc); + assert(desc->num_channels < GFX_MAX_NUM_CHANNELS); + + Animation* animation = mem_alloc_animation(); + animation->name = desc->name; + animation->duration = 0; + animation->num_channels = desc->num_channels; + R start_time = 0; + R end_time = 0; + + for (size_t c = 0; c < desc->num_channels; ++c) { + const ChannelDesc* channel_desc = &desc->channels[c]; + Channel* channel = &animation->channels[c]; + + channel->target = channel_desc->target; + channel->type = channel_desc->type; + channel->interpolation = channel_desc->interpolation; + channel->num_keyframes = channel_desc->num_keyframes; + assert(channel_desc->num_keyframes < GFX_MAX_NUM_KEYFRAMES); + + for (size_t k = 0; k < channel_desc->num_keyframes; ++k) { + const KeyframeDesc* keyframe_desc = &channel_desc->keyframes[k]; + Keyframe* keyframe = &channel->keyframes[k]; + + keyframe->time = keyframe_desc->time; + keyframe->translation = keyframe_desc->translation; + keyframe->rotation = keyframe_desc->rotation; + + start_time = keyframe->time < start_time ? keyframe->time : start_time; + end_time = keyframe->time > end_time ? keyframe->time : end_time; + } + } + + // LOGD("Animation start/end: %f / %f", start_time, end_time); + animation->duration = end_time - start_time; + assert(animation->duration >= 0); + return animation; +} + +Anima* gfx_make_anima(const AnimaDesc* desc) { + assert(desc); + assert(desc->num_joints > 0); + assert(desc->num_joints <= GFX_MAX_NUM_JOINTS); + // All joints should have a parent except for the root. + for (size_t i = 0; i < desc->num_joints - 1; ++i) { + const joint_idx parent = desc->joints[i].parent; + assert(parent != INDEX_NONE); + assert(parent < desc->num_joints); + } + // The root should have no parent. + assert(desc->joints[desc->num_joints - 1].parent == INDEX_NONE); + + Anima* anima = mem_alloc_anima(); + + // Wire the skeletons in the same order they are given in the descriptor. + Skeleton* last_skeleton = 0; + for (size_t i = 0; i < desc->num_skeletons; ++i) { + Skeleton* skeleton = make_skeleton(&desc->skeletons[i]); + const skeleton_idx skeleton_index = mem_get_skeleton_index(skeleton); + if (last_skeleton == 0) { + anima->skeleton = skeleton_index; + } else { + last_skeleton->next = skeleton_index; + } + last_skeleton = skeleton; + } + + // Wire the animations in the same order they are given in the descriptor. + Animation* last_animation = 0; + for (size_t i = 0; i < desc->num_animations; ++i) { + Animation* animation = make_animation(&desc->animations[i]); + const animation_idx animation_index = mem_get_animation_index(animation); + if (last_animation == 0) { + anima->animation = animation_index; + } else { + last_animation->next = animation_index; + } + last_animation = animation; + } + + // Create joints. + anima->num_joints = desc->num_joints; + // Initialize all joints. + // Child and sibling pointers must be initialized before wiring up the + // hierarchy. + for (size_t i = 0; i < desc->num_joints; ++i) { + Joint* joint = get_anima_joint_mut(anima, i); + make_joint(anima, &desc->joints[i], joint); + } + // Wire up joints to their parents. -1 to skip the root. + for (size_t i = 0; i < desc->num_joints - 1; ++i) { + set_joint_parent(anima, i, desc->joints[i].parent); + } + + return anima; +} + +void gfx_destroy_anima(Anima** anima) { + assert(anima); + + if (*anima) { + for (skeleton_idx i = (*anima)->skeleton; i.val != 0;) { + Skeleton* skeleton = mem_get_skeleton(i); + i = skeleton->next; + mem_free_skeleton(&skeleton); + } + + for (animation_idx i = (*anima)->animation; i.val != 0;) { + Animation* animation = mem_get_animation(i); + i = animation->next; + mem_free_animation(&animation); + } + + if ((*anima)->parent.val) { + gfx_del_node((*anima)->parent); + } + + mem_free_anima(anima); + } +} + +static Animation* find_animation(animation_idx index, const char* name) { + assert(name); + + while (index.val != 0) { + Animation* animation = mem_get_animation(index); + if (sstring_eq_cstr(animation->name, name)) { + // LOGD( + // "Found animation at index %u, %s - %s", index.val, + // sstring_cstr(&animation->name), name); + // LOGD("Animation has duration %f", animation->duration); + return animation; + } + index = animation->next; + } + + return 0; +} + +bool gfx_play_animation(Anima* anima, const AnimationPlaySettings* settings) { + assert(anima); + assert(settings); + + // TODO: Should we animate at t=0 here to kickstart the animation? Otherwise + // the client is forced to call gfx_update_animation() to do this. + Animation* animation = find_animation(anima->animation, settings->name); + if (!animation) { + return false; + } + // Playback initialized on first call to update(). + AnimationState* state = &anima->state; + state->start_time = PLAYBACK_UNINITIALIZED; + state->animation = mem_get_animation_index(animation); + state->loop = settings->loop; + return true; +} + +static void gfx_set_joint_position(Joint* joint, vec3 position) { + assert(joint); + mat4_set_v3(&joint->transform, position); +} + +static void gfx_set_joint_rotation(Joint* joint, quat rotation) { + assert(joint); + mat4_set_3x3(&joint->transform, mat4_from_quat(rotation)); +} + +static void find_keyframes(const Channel* channel, R t, int* prev, int* next) { + assert(channel); + assert(prev); + assert(next); + + *prev = -1; + *next = 0; + while (((*next + 1) < (int)channel->num_keyframes) && + (t >= channel->keyframes[*next + 1].time)) { + (*prev)++; + (*next)++; + } +} + +static R normalize_time(R a, R b, R t) { + assert(a <= t); + assert(t <= b); + return (t - a) / (b - a); +} + +static quat interpolate_rotation( + const Channel* channel, int prev, int next, R t) { + assert(channel); + + if (next == 0) { + // Animation has not started at this point in time yet. + return channel->keyframes[next].rotation; + } else { + switch (channel->interpolation) { + case StepInterpolation: + return channel->keyframes[prev].rotation; + case LinearInterpolation: { + const R normalized_t = normalize_time( + channel->keyframes[prev].time, channel->keyframes[next].time, t); + return qnormalize(qslerp( + channel->keyframes[prev].rotation, channel->keyframes[next].rotation, + normalized_t)); + break; + } + case CubicSplineInterpolation: + assert(false); // TODO + return qmake(0, 0, 0, 0); + default: + assert(false); + return qmake(0, 0, 0, 0); + } + } +} + +static vec3 interpolate_translation( + const Channel* channel, int prev, int next, R t) { + assert(channel); + + if (next == 0) { + // Animation has not started at this point in time yet. + return channel->keyframes[next].translation; + } else { + switch (channel->interpolation) { + case StepInterpolation: + return channel->keyframes[prev].translation; + case LinearInterpolation: { + const R normalized_t = normalize_time( + channel->keyframes[prev].time, channel->keyframes[next].time, t); + return vec3_lerp( + channel->keyframes[prev].translation, + channel->keyframes[next].translation, normalized_t); + break; + } + case CubicSplineInterpolation: + assert(false); // TODO + return vec3_make(0, 0, 0); + default: + assert(false); + return vec3_make(0, 0, 0); + } + } +} + +static void animate_channel(Anima* anima, const Channel* channel, R t) { + assert(anima); + assert(channel); + assert(channel->target < anima->num_joints); + + int prev, next; + find_keyframes(channel, t, &prev, &next); + + // Note that not all channels extend to the duration of an animation; some + // channels may stop animating their targets earlier. Clamp the animation time + // to the channel's end keyframe to make the rest of the math (normalize_time) + // work. + t = t > channel->keyframes[next].time ? channel->keyframes[next].time : t; + + Joint* target = get_anima_joint_mut(anima, channel->target); + + switch (channel->type) { + case RotationChannel: { + const quat rotation = interpolate_rotation(channel, prev, next, t); + gfx_set_joint_rotation(target, rotation); + break; + } + case TranslationChannel: { + const vec3 translation = interpolate_translation(channel, prev, next, t); + gfx_set_joint_position(target, translation); + break; + } + // Not yet supported. + case ScaleChannel: + case WeightsChannel: + default: + // TODO: Add back the assertion or add support for scaling. + // assert(false); + break; + } +} + +static void compute_joint_matrices_rec( + Anima* anima, Joint* joint, const mat4* parent_global_joint_transform, + const mat4* root_inv_global_transform) { + assert(anima); + assert(joint); + assert(parent_global_joint_transform); + assert(root_inv_global_transform); + + const mat4 global_joint_transform = + mat4_mul(*parent_global_joint_transform, joint->transform); + + // Compute this joint's matrix. + joint->joint_matrix = mat4_mul( + *root_inv_global_transform, + mat4_mul(global_joint_transform, joint->inv_bind_matrix)); + + // Recursively compute the joint matrices for this joint's siblings. + if (joint->next != INDEX_NONE) { + Joint* sibling = get_anima_joint_mut(anima, joint->next); + + compute_joint_matrices_rec( + anima, sibling, parent_global_joint_transform, + root_inv_global_transform); + } + + // Recursively compute the joint matrices for this joint's children. + if (joint->child != INDEX_NONE) { + Joint* child = get_anima_joint_mut(anima, joint->child); + + compute_joint_matrices_rec( + anima, child, &global_joint_transform, root_inv_global_transform); + } +} + +void gfx_update_animation(Anima* anima, R t) { + assert(anima); + + AnimationState* state = &anima->state; + if (state->animation.val == 0) { + return; // No active animation. + } + const Animation* animation = mem_get_animation(state->animation); + assert(animation); + + // On a call to play(), the start time is set to -1 to signal that the + // animation playback has not yet been initialized. + if (state->start_time == PLAYBACK_UNINITIALIZED) { + state->start_time = t; + } + // Locate the current time point inside the animation's timeline. + assert(t >= state->start_time); + assert(animation->duration >= 0.0); + const R local_time = t - state->start_time; + const R animation_time = state->loop + ? rmod(local_time, animation->duration) + : clamp(local_time, 0.0, animation->duration); + + // LOGD( + // "animation_time = %f, animation duration: %f", animation_time, + // animation->duration); + + // Play through the animation to transform skeleton nodes. + for (size_t i = 0; i < animation->num_channels; ++i) { + const Channel* channel = &animation->channels[i]; + animate_channel(anima, channel, animation_time); + } + + // Compute joint matrices after having transformed the skeletons. + // + // The anima's parent node is the common ancestor of all skeletons, and its + // transform maps the skeletons from object space to world space. This is the + // transform used as the "global transform" in the joint matrix equations. + // + // Joint matrix calculation begins by descending from the anima's root joint, + // which we have constructed to be the common root of all skeletons. + // + // This procedure touches every joint exactly once. + SceneNode* root_node = mem_get_node(anima->parent); + // LOGD("Root: %u, child: %u", anima->parent.val, root->child.val); + const mat4 root_global_transform = gfx_get_node_global_transform(root_node); + const mat4 root_inv_global_transform = mat4_inverse(root_global_transform); + + Joint* root_joint = get_anima_root_joint(anima); + compute_joint_matrices_rec( + anima, root_joint, &root_global_transform, &root_inv_global_transform); +} + +const Skeleton* gfx_get_anima_skeleton(const Anima* anima, size_t i) { + assert(anima); + + skeleton_idx skeleton_index = anima->skeleton; + const Skeleton* skeleton = mem_get_skeleton(skeleton_index); + + for (size_t j = 1; j < i; ++j) { + skeleton_index = skeleton->next; + mem_get_skeleton(skeleton_index); + } + + return skeleton; +} + +size_t gfx_get_skeleton_num_joints(const Skeleton* skeleton) { + assert(skeleton); + return skeleton->num_joints; +} + +bool gfx_joint_has_box( + const Anima* anima, const Skeleton* skeleton, size_t joint_index) { + assert(anima); + assert(skeleton); + assert(joint_index < skeleton->num_joints); + + const Joint* joint = get_skeleton_joint(anima, skeleton, joint_index); + return !aabb3_is_empty(joint->box); +} + +Box gfx_get_joint_box( + const Anima* anima, const Skeleton* skeleton, size_t joint_index) { + assert(anima); + assert(skeleton); + + const Joint* joint = get_skeleton_joint(anima, skeleton, joint_index); + + // Transform the box to anima space. + // Note that joint matrices do not usually have a translation since joints + // mostly just rotate with respect to their parent. + const vec3 pmin = joint->box.min; + const vec3 pmax = joint->box.max; + return (Box){ + .vertices = { + mat4_mul_vec3( + joint->joint_matrix, vec3_make(pmin.x, pmin.y, pmax.z), 1), + mat4_mul_vec3( + joint->joint_matrix, vec3_make(pmax.x, pmin.y, pmax.z), 1), + mat4_mul_vec3( + joint->joint_matrix, vec3_make(pmax.x, pmax.y, pmax.z), 1), + mat4_mul_vec3( + joint->joint_matrix, vec3_make(pmin.x, pmax.y, pmax.z), 1), + mat4_mul_vec3( + joint->joint_matrix, vec3_make(pmin.x, pmin.y, pmin.z), 1), + mat4_mul_vec3( + joint->joint_matrix, vec3_make(pmax.x, pmin.y, pmin.z), 1), + mat4_mul_vec3( + joint->joint_matrix, vec3_make(pmax.x, pmax.y, pmin.z), 1), + mat4_mul_vec3( + joint->joint_matrix, vec3_make(pmin.x, pmax.y, pmin.z), 1), + } + }; +} diff --git a/src/scene/animation_impl.h b/src/scene/animation_impl.h new file mode 100644 index 0000000..4408158 --- /dev/null +++ b/src/scene/animation_impl.h @@ -0,0 +1,98 @@ +#pragma once + +#include +#include + +#include "types.h" + +#include +#include +#include +#include +#include + +#include +#include + +typedef struct Buffer Buffer; + +// Currently ignoring scale in skinning and animation. +// +// TODO: Simultaneous animation of disjoint animations. + +/// Skeleton joint. +/// Joints are mutable and store the transform and joint matrices that result +/// from animation, aside from the inverse bind matrix. +typedef struct Joint { + joint_idx child; /// First child Joint; index into Anima's joints. + joint_idx next; /// Next sibling Joint; index into Anima's joints. + mat4 transform; /// Local transform relative to parent. + mat4 inv_bind_matrix; /// Transforms the mesh into the joint's local space. + mat4 joint_matrix; /// inv(global) * global joint transform * inv(bind). + aabb3 box; /// Bounding box of vertices affected by joint. +} Joint; + +/// Animation skeleton. +typedef struct Skeleton { + skeleton_idx next; + size_t num_joints; + joint_idx joints[GFX_MAX_NUM_JOINTS]; /// Indices into Anima's joints array. +} Skeleton; + +/// A keyframe of animation. +typedef struct Keyframe { + R time; /// Start time in [0, end animation time] + union { + vec3 translation; + quat rotation; + }; +} Keyframe; + +/// Animation channel. +typedef struct Channel { + joint_idx target; /// Index into Anima's joints array. + ChannelType type; + AnimationInterpolation interpolation; + size_t num_keyframes; + Keyframe keyframes[GFX_MAX_NUM_KEYFRAMES]; +} Channel; + +/// A skeletal animation. +typedef struct Animation { + animation_idx next; + sstring name; + R duration; + size_t num_channels; + Channel channels[GFX_MAX_NUM_CHANNELS]; +} Animation; + +/// Animation state. +/// +/// This represents the current state of an animation. +typedef struct AnimationState { + R start_time; // Time when the current animation started playing. -1 means the + // animation playback has not yet been initialized. + animation_idx animation; // Current animation. 0 = no animation. + bool loop; +} AnimationState; + +/// Animation object. +/// +/// This is the top-level animation object that encapsulates everything +/// necessary for animation. +/// +/// For lack of a better name, this is called an Anima. It is short and the +/// Latin root of animation. +/// +/// The last joint of the joints array at index 'num_joints - 1' is the root of +/// all skeletons; specifically, the root of all joints that otherwise would +/// have no parent (a skeleton need not have its own root and can be a set of +/// disjoint node hierarchies). +typedef struct Anima { + node_idx parent; /// Parent SceneNode. + skeleton_idx skeleton; /// Index of first skeleton. + animation_idx animation; /// Index of first animation. + AnimationState state; /// Current animation state. + size_t num_joints; /// Number of actual joints in the array. + Joint joints[GFX_MAX_NUM_JOINTS]; /// Shared by all skeletons. +} Anima; diff --git a/src/scene/camera.c b/src/scene/camera.c new file mode 100644 index 0000000..be7d806 --- /dev/null +++ b/src/scene/camera.c @@ -0,0 +1,37 @@ +#include "camera_impl.h" + +#include "node_impl.h" +#include "scene_memory.h" + +#include + +SceneCamera* gfx_make_camera() { + SceneCamera* camera = mem_alloc_camera(); + + camera->camera = camera_perspective( + /*fovy=*/90.0 * TO_RAD, /*aspect=*/16.0 / 9.0, + /*near=*/0.1, /*far=*/1000); + + return camera; +} + +void gfx_destroy_camera(SceneCamera** camera) { + assert(camera); + if (*camera) { + if ((*camera)->parent.val) { + gfx_del_node((*camera)->parent); + } + mem_free_camera(camera); + } +} + +void gfx_set_camera_camera(SceneCamera* scene_camera, Camera* camera) { + assert(scene_camera); + assert(camera); + scene_camera->camera = *camera; +} + +Camera* gfx_get_camera_camera(SceneCamera* camera) { + assert(camera); + return &camera->camera; +} diff --git a/src/scene/camera_impl.h b/src/scene/camera_impl.h new file mode 100644 index 0000000..20c3890 --- /dev/null +++ b/src/scene/camera_impl.h @@ -0,0 +1,12 @@ +#pragma once + +#include + +#include "types.h" + +#include + +typedef struct SceneCamera { + Camera camera; + node_idx parent; // Parent SceneNode. +} SceneCamera; diff --git a/src/scene/light.c b/src/scene/light.c new file mode 100644 index 0000000..adbec8d --- /dev/null +++ b/src/scene/light.c @@ -0,0 +1,42 @@ +#include "light_impl.h" + +#include "node_impl.h" +#include "scene_memory.h" + +#include + +static void make_environment_light( + Light* light, const EnvironmentLightDesc* desc) { + assert(light); + assert(desc); + light->type = EnvironmentLightType; + light->environment.environment_map = desc->environment_map; +} + +Light* gfx_make_light(const LightDesc* desc) { + assert(desc); + + Light* light = mem_alloc_light(); + + switch (desc->type) { + case EnvironmentLightType: + make_environment_light(light, &desc->light.environment); + break; + default: + log_error("Unhandled light type"); + gfx_destroy_light(&light); + return 0; + } + + return light; +} + +void gfx_destroy_light(Light** light) { + assert(light); + if (*light) { + if ((*light)->parent.val) { + gfx_del_node((*light)->parent); + } + mem_free_light(light); + } +} diff --git a/src/scene/light_impl.h b/src/scene/light_impl.h new file mode 100644 index 0000000..1aa0bb4 --- /dev/null +++ b/src/scene/light_impl.h @@ -0,0 +1,25 @@ +#pragma once + +#include + +#include "types.h" + +typedef struct Texture Texture; + +/// An environment light. +typedef struct EnvironmentLight { + const Texture* environment_map; + const Texture* irradiance_map; // Renderer implementation. + const Texture* prefiltered_environment_map; // Renderer implementation. + int max_reflection_lod; // Mandatory when prefiltered_environment_map is + // given. +} EnvironmentLight; + +/// A scene light. +typedef struct Light { + LightType type; + union { + EnvironmentLight environment; + }; + node_idx parent; // Parent SceneNode. +} Light; diff --git a/src/scene/material.c b/src/scene/material.c new file mode 100644 index 0000000..3248243 --- /dev/null +++ b/src/scene/material.c @@ -0,0 +1,57 @@ +#include "material_impl.h" + +#include "scene_memory.h" + +#include + +static void material_make(Material* material, const MaterialDesc* desc) { + assert(material); + assert(desc); + assert(desc->num_uniforms < GFX_MAX_UNIFORMS_PER_MATERIAL); + material->num_uniforms = desc->num_uniforms; + for (int i = 0; i < desc->num_uniforms; ++i) { + material->uniforms[i] = desc->uniforms[i]; + } +} + +Material* gfx_make_material(const MaterialDesc* desc) { + assert(desc); + Material* material = mem_alloc_material(); + material_make(material, desc); + return material; +} + +void gfx_destroy_material(Material** material) { mem_free_material(material); } + +static void set_uniform(ShaderProgram* prog, const ShaderUniform* uniform) { + switch (uniform->type) { + case UniformTexture: + gfx_set_texture_uniform(prog, uniform->name.str, uniform->value.texture); + break; + case UniformMat4: + gfx_set_mat4_uniform(prog, uniform->name.str, &uniform->value.mat4); + break; + case UniformVec3: + gfx_set_vec3_uniform(prog, uniform->name.str, uniform->value.vec3); + break; + case UniformVec4: + gfx_set_vec4_uniform(prog, uniform->name.str, uniform->value.vec4); + break; + case UniformFloat: + gfx_set_float_uniform(prog, uniform->name.str, uniform->value.scalar); + break; + case UniformMat4Array: + gfx_set_mat4_array_uniform( + prog, uniform->name.str, uniform->value.array.values, + uniform->value.array.count); + break; + } +} + +void material_activate(ShaderProgram* shader, const Material* material) { + assert(material); + for (int i = 0; i < material->num_uniforms; ++i) { + const ShaderUniform* uniform = &material->uniforms[i]; + set_uniform(shader, uniform); + } +} diff --git a/src/scene/material_impl.h b/src/scene/material_impl.h new file mode 100644 index 0000000..a6aa95b --- /dev/null +++ b/src/scene/material_impl.h @@ -0,0 +1,16 @@ +#pragma once + +#include + +typedef struct ShaderProgram ShaderProgram; + +typedef struct Material { + ShaderUniform uniforms[GFX_MAX_UNIFORMS_PER_MATERIAL]; + int num_uniforms; +} Material; + +/// Activate the material. +/// +/// This activates the material's shader and configures the shader uniforms that +/// are specific to the material. +void material_activate(ShaderProgram* shader, const Material* material); diff --git a/src/scene/mesh.c b/src/scene/mesh.c new file mode 100644 index 0000000..1a93bed --- /dev/null +++ b/src/scene/mesh.c @@ -0,0 +1,24 @@ +#include "mesh_impl.h" + +#include "scene_memory.h" + +#include + +static void mesh_make(Mesh* mesh, const MeshDesc* desc) { + assert(mesh); + assert(desc); + assert(desc->geometry); + assert(desc->material); + assert(desc->shader); + mesh->geometry = desc->geometry; + mesh->material = desc->material; + mesh->shader = desc->shader; +} + +Mesh* gfx_make_mesh(const MeshDesc* desc) { + Mesh* mesh = mem_alloc_mesh(); + mesh_make(mesh, desc); + return mesh; +} + +void gfx_destroy_mesh(Mesh** mesh) { mem_free_mesh(mesh); } diff --git a/src/scene/mesh_impl.h b/src/scene/mesh_impl.h new file mode 100644 index 0000000..560b77e --- /dev/null +++ b/src/scene/mesh_impl.h @@ -0,0 +1,12 @@ +#pragma once + +#include + +typedef struct Mesh { + const Geometry* geometry; + const Material* material; + ShaderProgram* shader; +} Mesh; + +// TODO: a mesh_render() that takes a transform, applies the material and the +// transform, and then renders the geometry. diff --git a/src/scene/model.c b/src/scene/model.c new file mode 100644 index 0000000..cc41a9a --- /dev/null +++ b/src/scene/model.c @@ -0,0 +1,45 @@ +#include "model_impl.h" + +#include + +#include "scene_memory.h" + +#include + +Model* gfx_make_model(const SceneNode* root) { + assert(root); + + Model* model = mem_alloc_model(); + model->root = mem_get_node_index(root); + return model; +} + +void gfx_del_model(Model** model) { + assert(model); + + if (*model) { + SceneNode* root = mem_get_node((*model)->root); + gfx_destroy_node(&root); + *model = 0; + } +} + +Anima* gfx_get_model_anima(Model* model) { + assert(model); + + SceneNode* root = mem_get_node(model->root); + if (gfx_get_node_type(root) == AnimaNode) { + return gfx_get_node_anima_mut(root); + } else { + return 0; + } +} + +const SceneNode* gfx_get_model_root(const Model* model) { + assert(model); + return mem_get_node(model->root); +} + +SceneNode* gfx_get_model_root_mut(Model* model) { + return (SceneNode*)gfx_get_model_root(model); +} diff --git a/src/scene/model_impl.h b/src/scene/model_impl.h new file mode 100644 index 0000000..a99d32c --- /dev/null +++ b/src/scene/model_impl.h @@ -0,0 +1,17 @@ +#pragma once + +#include + +#include "scene_memory.h" + +/// Model. +typedef struct Model { + node_idx root; + node_idx parent; // Parent SceneNode. +} Model; + +/// Create a new model. +Model* gfx_make_model(const SceneNode* root); + +/// Destroy the model. +void gfx_del_model(Model**); diff --git a/src/scene/node.c b/src/scene/node.c new file mode 100644 index 0000000..67ce93c --- /dev/null +++ b/src/scene/node.c @@ -0,0 +1,409 @@ +#include "node_impl.h" + +#include "animation_impl.h" +#include "camera_impl.h" +#include "light_impl.h" +#include "model_impl.h" +#include "object_impl.h" +#include "scene_graph.h" +#include "scene_memory.h" + +#include "gfx_assert.h" + +#include +#include + +static void scene_node_make(SceneNode* node) { + assert(node); + node->type = LogicalNode; + node->transform = mat4_id(); +} + +SceneNode* gfx_make_node() { + SceneNode* node = mem_alloc_node(); + scene_node_make(node); + return node; +} + +SceneNode* gfx_make_anima_node(Anima* anima) { + assert(anima); + SceneNode* node = gfx_make_node(); + node->type = AnimaNode; + node->anima = mem_get_anima_index(anima); + anima->parent = mem_get_node_index(node); + return node; +} + +SceneNode* gfx_make_camera_node(SceneCamera* camera) { + assert(camera); + SceneNode* node = gfx_make_node(); + node->type = CameraNode; + node->camera = mem_get_camera_index(camera); + camera->parent = mem_get_node_index(node); + return node; +} + +SceneNode* gfx_make_light_node(Light* light) { + assert(light); + SceneNode* node = gfx_make_node(); + node->type = LightNode; + node->light = mem_get_light_index(light); + light->parent = mem_get_node_index(node); + return node; +} + +SceneNode* gfx_make_model_node(Model* model) { + assert(model); + SceneNode* node = gfx_make_node(); + node->type = ModelNode; + node->model = mem_get_model_index(model); + model->parent = mem_get_node_index(node); + return node; +} + +SceneNode* gfx_make_object_node(SceneObject* object) { + assert(object); + SceneNode* node = gfx_make_node(); + node->type = ObjectNode; + node->object = mem_get_object_index(object); + object->parent = mem_get_node_index(node); + return node; +} + +/// Frees the node's resource. +static void free_node_resource(SceneNode* node) { + assert(node); + + // Set the resource's parent node back to 0 to avoid a recursive call into + // gfx_del_node(). + switch (node->type) { + case AnimaNode: { + Anima* anima = mem_get_anima(node->anima); + anima->parent.val = 0; + gfx_destroy_anima(&anima); + return; + } + case CameraNode: { + SceneCamera* camera = mem_get_camera(node->camera); + camera->parent.val = 0; + gfx_destroy_camera(&camera); + return; + } + case LightNode: { + Light* light = mem_get_light(node->light); + light->parent.val = 0; + gfx_destroy_light(&light); + return; + } + case ModelNode: { + return; // Model data is owned by the asset cache. + } + case ObjectNode: { + SceneObject* object = mem_get_object(node->object); + object->parent.val = 0; + gfx_destroy_object(&object); + return; + } + case LogicalNode: + return; // Logical nodes have no resource. + } + FAIL("unhandled node type"); +} + +void gfx_construct_anima_node(SceneNode* node, Anima* anima) { + assert(node); + assert(anima); + free_node_resource(node); + node->type = AnimaNode; + node->anima = mem_get_anima_index(anima); + anima->parent = mem_get_node_index(node); +} + +void gfx_construct_camera_node(SceneNode* node, SceneCamera* camera) { + assert(node); + assert(camera); + free_node_resource(node); + node->type = CameraNode; + node->camera = mem_get_camera_index(camera); + camera->parent = mem_get_node_index(node); +} + +// TODO: Add a common helper function between each gfx_make_xyz_node() and +// gfx_construct_xyz_node() pair. +void gfx_construct_light_node(SceneNode* node, Light* light) { + assert(node); + assert(light); + free_node_resource(node); + node->type = LightNode; + node->light = mem_get_light_index(light); + light->parent = mem_get_node_index(node); +} + +void gfx_construct_model_node(SceneNode* node, Model* model) { + assert(node); + assert(model); + free_node_resource(node); + node->type = ModelNode; + node->model = mem_get_model_index(model); + model->parent = mem_get_node_index(node); +} + +void gfx_construct_object_node(SceneNode* node, SceneObject* object) { + assert(node); + assert(object); + free_node_resource(node); + node->type = ObjectNode; + node->object = mem_get_object_index(object); + object->parent = mem_get_node_index(node); +} + +static void destroy_node_rec(SceneNode* node) { + assert(node); + + // First child. + if (node->child.val) { + destroy_node_rec(mem_get_node(node->child)); + } + + // Right sibling. + if (node->next.val) { + destroy_node_rec(mem_get_node(node->next)); + } + + free_node_resource(node); + mem_free_node(&node); +} + +void gfx_destroy_node(SceneNode** node) { + assert(node); + if (*node) { + // Since the node and the whole hierarchy under it gets destroyed, there is + // no need to individually detach every node from its hierarchy. We can + // simply detach the given node and then destroy it and its sub-hierarchy. + TREE_REMOVE(*node); + destroy_node_rec(*node); + *node = 0; + } +} + +// TODO: Think more about ownership of nodes and resources. Should this function +// even exist? +void gfx_del_node(node_idx index) { + assert(index.val); + SceneNode* node = mem_get_node(index); + assert(node); + // TODO: Should destroy children recursively? + TREE_REMOVE(node); + mem_free_node(&node); +} + +NodeType gfx_get_node_type(const SceneNode* node) { + assert(node); + return node->type; +} + +#define NODE_GET(node, field, expected_type) \ + { \ + assert(node); \ + assert(node->type == expected_type); \ + return mem_get_##field(node->field); \ + } + +const Anima* gfx_get_node_anima(const SceneNode* node) { + NODE_GET(node, anima, AnimaNode); +} + +Anima* gfx_get_node_anima_mut(SceneNode* node) { + NODE_GET(node, anima, AnimaNode); +} + +const SceneCamera* gfx_get_node_camera(const SceneNode* node) { + NODE_GET(node, camera, CameraNode); +} + +SceneCamera* gfx_get_node_camera_mut(SceneNode* node) { + NODE_GET(node, camera, CameraNode); +} + +const Light* gfx_get_node_light(const SceneNode* node) { + NODE_GET(node, light, LightNode); +} + +Light* gfx_get_node_light_mut(SceneNode* node) { + NODE_GET(node, light, LightNode); +} + +const Model* gfx_get_node_model(const SceneNode* node) { + NODE_GET(node, model, ModelNode); +} + +Model* gfx_get_node_model_mut(SceneNode* node) { + NODE_GET(node, model, ModelNode); +} + +const SceneObject* gfx_get_node_object(const SceneNode* node) { + NODE_GET(node, object, ObjectNode); +} + +SceneObject* gfx_get_node_object_mut(SceneNode* node) { + NODE_GET(node, object, ObjectNode); +} + +const SceneNode* gfx_get_node_parent(const SceneNode* node) { + assert(node); + return mem_get_node(node->parent); +} + +SceneNode* gfx_get_node_parent_mut(SceneNode* node) { + assert(node); + return mem_get_node(node->parent); +} + +const SceneNode* gfx_get_node_child(const SceneNode* node) { + assert(node); + if (node->child.val) { + return mem_get_node(node->child); + } else { + return 0; + } +} + +SceneNode* gfx_get_node_child_mut(SceneNode* node) { + return (SceneNode*)gfx_get_node_child(node); +} + +const SceneNode* gfx_get_node_sibling(const SceneNode* node) { + assert(node); + if (node->next.val) { + return mem_get_node(node->next); + } else { + return 0; + } +} + +SceneNode* gfx_get_node_sibling_mut(SceneNode* node) { + return (SceneNode*)gfx_get_node_sibling(node); +} + +mat4 gfx_get_node_transform(const SceneNode* node) { + assert(node); + return node->transform; +} + +mat4 gfx_get_node_global_transform(const SceneNode* node) { + assert(node); + mat4 transform = node->transform; + node_idx parent_index = node->parent; + while (parent_index.val != 0) { + const SceneNode* parent = mem_get_node(parent_index); + transform = mat4_mul(parent->transform, transform); + parent_index = parent->parent; + } + return transform; +} + +void gfx_set_node_parent(SceneNode* child, SceneNode* parent_node) { + assert(child); + // Parent can be null. + SET_PARENT(child, parent_node); +} + +void gfx_set_node_transform(SceneNode* node, const mat4* transform) { + assert(node); + assert(transform); + node->transform = *transform; +} + +void gfx_set_node_position(SceneNode* node, const vec3* position) { + assert(node); + assert(position); + mat4_set_v3(&node->transform, *position); +} + +void gfx_set_node_rotation(SceneNode* node, const quat* rotation) { + assert(node); + assert(rotation); + mat4_set_3x3(&node->transform, mat4_from_quat(*rotation)); +} + +void gfx_set_node_rotation_mat(SceneNode* node, const mat4* rotation) { + assert(node); + assert(rotation); + mat4_set_3x3(&node->transform, *rotation); +} + +static const char* get_node_type_str(NodeType type) { + switch (type) { + case LogicalNode: + return "LogicalNode"; + case AnimaNode: + return "AnimaNode"; + case CameraNode: + return "CameraNode"; + case LightNode: + return "LightNode"; + case ModelNode: + return "ModelNode"; + case ObjectNode: + return "ObjectNode"; + } + FAIL("Unhandled node type"); + return ""; +} + +static void log_node_hierarchy_rec(const SceneNode* node, const sstring* pad) { + assert(node); + assert(pad); + + LOGI( + "%s%s (%u)", sstring_cstr(pad), get_node_type_str(node->type), + mem_get_node_index(node).val); + + // Log the children. + if (node->child.val) { + const sstring new_pad = sstring_concat_cstr(*pad, " "); + log_node_hierarchy_rec(mem_get_node(node->child), &new_pad); + } + + // Then log the siblings. + if (node->next.val) { + log_node_hierarchy_rec(mem_get_node(node->next), pad); + } +} + +void gfx_log_node_hierarchy(const SceneNode* node) { + const sstring pad = sstring_make(""); + log_node_hierarchy_rec(node, &pad); +} + +static SceneNode* clone_scene_rec(const SceneNode* node) { + assert(node); + + SceneNode* copy = mem_alloc_node(); + *copy = *node; // Shallow clone of the node's resource. + + if (node->child.val) { + SceneNode* child = mem_get_node(node->child); + SceneNode* child_copy = clone_scene_rec(child); + copy->child = mem_get_node_index(child_copy); + child_copy->parent = mem_get_node_index(copy); + } + + if (node->next.val) { + SceneNode* next = mem_get_node(node->next); + SceneNode* next_copy = clone_scene_rec(next); + copy->next = mem_get_node_index(next_copy); + next_copy->prev = mem_get_node_index(copy); + } + + return copy; +} + +SceneNode* gfx_clone_scene_shallow(const SceneNode* node) { + assert(node); + // Must be a root node; not allowed to have siblings. + assert(!node->prev.val); + assert(!node->next.val); + + return clone_scene_rec(node); +} diff --git a/src/scene/node_impl.h b/src/scene/node_impl.h new file mode 100644 index 0000000..c79f252 --- /dev/null +++ b/src/scene/node_impl.h @@ -0,0 +1,40 @@ +#pragma once + +#include + +#include "types.h" + +#include +#include + +/// Scene node. +/// +/// The SceneNode owns its cameras, objects, lights and child nodes. These +/// together form a strict tree hierarchy and not a more general DAG. +typedef struct SceneNode { + NodeType type; + union { + anima_idx anima; + camera_idx camera; + light_idx light; + model_idx model; + object_idx object; + }; + mat4 transform; // Transformation for this node and its children. + node_idx parent; // Parent SceneNode. + node_idx child; // First child SceneNode. + node_idx next; // Next sibling SceneNode. + node_idx prev; // Previous sibling SceneNode. +} SceneNode; + +/// Recursively destroy a node given its index but without destroying the node +/// resources. +/// +/// The node and its children are removed from the scene graph. +/// +/// This function is for the library's internal use only. +void gfx_del_node(node_idx); + +/// Return a shallow clone of the scene rooted at the given node. +/// The given node must have no siblings (must be a root node). +SceneNode* gfx_clone_scene_shallow(const SceneNode*); diff --git a/src/scene/object.c b/src/scene/object.c new file mode 100644 index 0000000..e8e3ee6 --- /dev/null +++ b/src/scene/object.c @@ -0,0 +1,83 @@ +#include "object_impl.h" + +#include + +#include "mesh_impl.h" +#include "node_impl.h" +#include "scene_memory.h" + +#include + +static aabb3 calc_object_aabb(const SceneObject* object) { + assert(object); + + bool first = true; + aabb3 box; + + mesh_link_idx ml = object->mesh_link; + while (ml.val) { + const MeshLink* mesh_link = mem_get_mesh_link(ml); + const mesh_idx mi = mesh_link->mesh; + if (mi.val) { + const Mesh* mesh = mem_get_mesh(mi); + const aabb3 mesh_box = gfx_get_geometry_aabb(mesh->geometry); + if (first) { + box = mesh_box; + first = false; + } else { + box = aabb3_sum(box, mesh_box); + } + } + ml = mesh_link->next; + } + + return box; +} + +static void add_object_mesh(SceneObject* object, Mesh* mesh) { + assert(object); + assert(mesh); + + MeshLink* link = mem_alloc_mesh_link(); + link->mesh = mem_get_mesh_index(mesh); + link->next = object->mesh_link; + object->mesh_link = mem_get_mesh_link_index(link); +} + +SceneObject* gfx_make_object(const ObjectDesc* desc) { + assert(desc); + + SceneObject* object = mem_alloc_object(); + for (size_t i = 0; i < desc->num_meshes; ++i) { + add_object_mesh(object, desc->meshes[i]); + } + object->box = calc_object_aabb(object); + return object; +} + +void gfx_destroy_object(SceneObject** object) { + assert(object); + + if (*object) { + if ((*object)->parent.val) { + gfx_del_node((*object)->parent); + } + mem_free_object(object); + } +} + +void gfx_set_object_skeleton(SceneObject* object, const Skeleton* skeleton) { + assert(object); + assert(skeleton); + object->skeleton = mem_get_skeleton_index(skeleton); +} + +const Skeleton* gfx_get_object_skeleton(const SceneObject* object) { + assert(object); + return (object->skeleton.val == 0) ? 0 : mem_get_skeleton(object->skeleton); +} + +aabb3 gfx_get_object_aabb(const SceneObject* object) { + assert(object); + return object->box; +} diff --git a/src/scene/object_impl.h b/src/scene/object_impl.h new file mode 100644 index 0000000..88f8e31 --- /dev/null +++ b/src/scene/object_impl.h @@ -0,0 +1,26 @@ +#pragma once + +#include + +#include "types.h" + +#include + +typedef struct MeshLink { + mesh_idx mesh; + mesh_link_idx next; // Next MeshLink in the list. +} MeshLink; + +/// Scene object. +/// +/// A SceneObject does not own its Meshes, and they are instead shared for +/// re-use. The SceneObject consequently embeds a list of MeshLinks as opposed +/// to a list of Meshes. The MeshLinks define a list of Meshes, which can be +/// different for each SceneObject. Each SceneObject may then have a unique list +/// of Meshes, and the Meshes are re-used. +typedef struct SceneObject { + mesh_link_idx mesh_link; /// First MeshLink in the list. + skeleton_idx skeleton; /// 0 for static objects. + node_idx parent; /// Parent SceneNode. + aabb3 box; +} SceneObject; diff --git a/src/scene/scene.c b/src/scene/scene.c new file mode 100644 index 0000000..54452dd --- /dev/null +++ b/src/scene/scene.c @@ -0,0 +1,25 @@ +#include "scene_impl.h" + +#include "node_impl.h" +#include "scene_memory.h" + +#include + +Scene* gfx_make_scene(void) { + Scene* scene = mem_alloc_scene(); + scene->root = gfx_make_node(); + return scene; +} + +void gfx_destroy_scene(Scene** scene) { + assert(scene); + if (*scene) { + gfx_destroy_node(&(*scene)->root); + mem_free_scene(scene); + } +} + +SceneNode* gfx_get_scene_root(Scene* scene) { + assert(scene); + return scene->root; +} diff --git a/src/scene/scene_graph.h b/src/scene/scene_graph.h new file mode 100644 index 0000000..a26f828 --- /dev/null +++ b/src/scene/scene_graph.h @@ -0,0 +1,138 @@ +/// Functions for list manipulation. +#pragma once + +#include "scene_memory.h" + +// NOTE: SceneMemory guarantees that index 0 can be regarded as an invalid +// index. + +#define MEM_GET(INDEX) \ + _Generic((INDEX), camera_idx \ + : mem_get_camera, material_idx \ + : mem_get_material, mesh_idx \ + : mem_get_mesh, mesh_link_idx \ + : mem_get_mesh_link, node_idx \ + : mem_get_node, object_idx \ + : mem_get_object, scene_idx \ + : mem_get_scene)(INDEX) + +#define MEM_GET_INDEX(ITEM) \ + _Generic((ITEM), SceneCamera * \ + : mem_get_camera_index, Material * \ + : mem_get_material_index, Mesh * \ + : mem_get_mesh_index, MeshLink * \ + : mem_get_mesh_link_index, SceneNode * \ + : mem_get_node_index, SceneObject * \ + : mem_get_object_index, Scene * \ + : mem_get_scene_index)(ITEM) + +/// Assert the list node invariant. +/// +/// - A node does not point to itself. +#define ASSERT_LIST_NODE_INVARIANT(ITEM) \ + { \ + const gfx_idx item_idx = MEM_GET_INDEX(ITEM).val; \ + assert((ITEM)->prev.val != item_idx); \ + assert((ITEM)->next.val != item_idx); \ + } + +/// Assert the tree node invariant. +/// +/// - A node does not point to itself. +/// - The node's left and right siblings cannot be equal, unless both are 0. +/// - The node's left/right sibling cannot be its child, unless both are 0. +/// - The node's parent cannot be the node's child or sibling, unless it's 0. +/// - If the node has a parent and the node is the leftmost sibling, then the +/// parent's child is the node. +#define ASSERT_TREE_NODE_INVARIANT(ITEM) \ + { \ + const gfx_idx item_idx = MEM_GET_INDEX(ITEM).val; \ + assert((ITEM)->prev.val != item_idx); \ + assert((ITEM)->next.val != item_idx); \ + if ((ITEM)->prev.val) { \ + assert((ITEM)->prev.val != (ITEM)->next.val); \ + } \ + if ((ITEM)->child.val) { \ + assert((ITEM)->child.val != (ITEM)->prev.val); \ + assert((ITEM)->child.val != (ITEM)->next.val); \ + } \ + assert((ITEM)->parent.val != item_idx); \ + if ((ITEM)->parent.val && !(ITEM)->prev.val) { \ + assert((ITEM)->parent.val != (ITEM)->prev.val); \ + assert((ITEM)->parent.val != (ITEM)->next.val); \ + const __typeof__(ITEM) item_parent = MEM_GET((ITEM)->parent); \ + assert(item_parent->child.val == item_idx); \ + } \ + } + +/// Prepend an item to a list. +/// Modify HEAD_INDEX to equal the index of the new head. +#define LIST_PREPEND(HEAD_INDEX, ITEM) \ + (ITEM)->next = HEAD_INDEX; \ + if (HEAD_INDEX.val) { \ + __typeof__(ITEM) old_head = MEM_GET(HEAD_INDEX); \ + old_head->prev = MEM_GET_INDEX(ITEM); \ + } \ + HEAD_INDEX = MEM_GET_INDEX(ITEM); \ + ASSERT_LIST_NODE_INVARIANT(ITEM); + +/// Disconnect an item from its siblings. +#define LIST_REMOVE(ITEM) \ + if ((ITEM)->prev.val) { \ + __typeof__(ITEM) prev_sibling = MEM_GET((ITEM)->prev); \ + prev_sibling->next = (ITEM)->next; \ + } \ + if ((ITEM)->next.val) { \ + __typeof__(ITEM) next_sibling = MEM_GET((ITEM)->next); \ + next_sibling->prev = (ITEM)->prev; \ + } \ + (ITEM)->prev.val = 0; \ + (ITEM)->next.val = 0; \ + ASSERT_LIST_NODE_INVARIANT(ITEM); + +/// Set the child's parent. +/// +/// The hierarchy is a strict tree hierarchy and a parent node points to its +/// first/leftmost child only. To add a new child, the new child becomes the +/// leftmost node in the list of siblings, the one that the parent then points +/// to. +/// +/// The child is also completely disconnected from its previous hierarchy. This +/// is because siblings in a hierarchy must all point to the same parent. +#define SET_PARENT(CHILD, PARENT) \ + assert(CHILD); \ + assert(CHILD != PARENT); \ + ASSERT_TREE_NODE_INVARIANT(CHILD); \ + ASSERT_TREE_NODE_INVARIANT(PARENT); \ + TREE_REMOVE(CHILD); /* Disconnect CHILD from its previous hierarchy. */ \ + if (PARENT) { \ + LIST_PREPEND((PARENT)->child, CHILD); \ + (CHILD)->parent = MEM_GET_INDEX(PARENT); \ + } else { \ + (CHILD)->parent.val = 0; \ + } \ + ASSERT_TREE_NODE_INVARIANT(CHILD); \ + if (PARENT) { \ + ASSERT_TREE_NODE_INVARIANT(PARENT); \ + } + +/// Remove an item from its hierarchy. +/// +/// The item is disconnected from its parents and siblings. The hierarchy rooted +/// under the item remains intact. +#define TREE_REMOVE(ITEM) \ + assert(ITEM); \ + if ((ITEM)->parent.val) { \ + /* The parent points only to its first/leftmost child. If this item is */ \ + /* the leftmost sibling, then we need to rewire the parent to point to */ \ + /* the next sibling to keep the parent connected to its children. */ \ + __typeof__(ITEM) parent = MEM_GET((ITEM)->parent); \ + const __typeof__(ITEM) parent_child = MEM_GET(parent->child); \ + if (parent_child == ITEM) { \ + assert((ITEM)->prev.val == 0); \ + parent->child = (ITEM)->next; \ + } \ + } \ + (ITEM)->parent.val = 0; \ + LIST_REMOVE(ITEM); /* Disconnect ITEM from its siblings. */ \ + ASSERT_TREE_NODE_INVARIANT(ITEM); diff --git a/src/scene/scene_impl.h b/src/scene/scene_impl.h new file mode 100644 index 0000000..992f620 --- /dev/null +++ b/src/scene/scene_impl.h @@ -0,0 +1,13 @@ +#pragma once + +#include + +#include "types.h" + +typedef struct SceneNode SceneNode; + +typedef struct Scene { + SceneNode* root; + scene_idx next; + scene_idx prev; +} Scene; diff --git a/src/scene/scene_memory.c b/src/scene/scene_memory.c new file mode 100644 index 0000000..85c27e7 --- /dev/null +++ b/src/scene/scene_memory.c @@ -0,0 +1,149 @@ +#include "scene_memory.h" + +#include + +#include "animation_impl.h" +#include "camera_impl.h" +#include "light_impl.h" +#include "material_impl.h" +#include "mesh_impl.h" +#include "model_impl.h" +#include "node_impl.h" +#include "object_impl.h" +#include "scene_impl.h" + +#include + +DEF_MEMPOOL(anima_pool, Anima, GFX_MAX_NUM_ANIMAS) +DEF_MEMPOOL(animation_pool, Animation, GFX_MAX_NUM_ANIMATIONS) +DEF_MEMPOOL(camera_pool, SceneCamera, GFX_MAX_NUM_CAMERAS) +DEF_MEMPOOL(light_pool, Light, GFX_MAX_NUM_LIGHTS) +DEF_MEMPOOL(material_pool, Material, GFX_MAX_NUM_MATERIALS) +DEF_MEMPOOL(mesh_pool, Mesh, GFX_MAX_NUM_MESHES) +DEF_MEMPOOL(mesh_link_pool, MeshLink, GFX_MAX_NUM_MESH_LINKS) +DEF_MEMPOOL(model_pool, Model, GFX_MAX_NUM_MODELS) +DEF_MEMPOOL(node_pool, SceneNode, GFX_MAX_NUM_NODES) +DEF_MEMPOOL(object_pool, SceneObject, GFX_MAX_NUM_OBJECTS) +DEF_MEMPOOL(scene_pool, Scene, GFX_MAX_NUM_SCENES) +DEF_MEMPOOL(skeleton_pool, Skeleton, GFX_MAX_NUM_SKELETONS) + +/// Scene memory. +/// +/// Holds memory pools for every type of scene object. +typedef struct SceneMemory { + anima_pool animas; + animation_pool animations; + camera_pool cameras; + light_pool lights; + material_pool materials; + mesh_pool meshs; // Purposeful typo to make the PLURAL() macro work. + mesh_link_pool mesh_links; + model_pool models; + node_pool nodes; + object_pool objects; + scene_pool scenes; + skeleton_pool skeletons; +} SceneMemory; + +static SceneMemory mem; + +#define ALLOC_DUMMY(POOL) \ + { \ + const void* object = mempool_alloc(POOL); \ + assert(mempool_get_block_index(POOL, object) == 0); \ + } + +#define PLURAL(name) name##s +#define MEM_FIELD(name) mem.PLURAL(name) + +void scene_mem_init() { + mempool_make(&mem.animas); + mempool_make(&mem.animations); + mempool_make(&mem.cameras); + mempool_make(&mem.lights); + mempool_make(&mem.materials); + mempool_make(&mem.meshs); + mempool_make(&mem.mesh_links); + mempool_make(&mem.models); + mempool_make(&mem.nodes); + mempool_make(&mem.objects); + mempool_make(&mem.scenes); + mempool_make(&mem.skeletons); + + // Allocate dummy objects at index 0 to guarantee that no objects allocated by + // the caller map to index 0. + ALLOC_DUMMY(&mem.animas); + ALLOC_DUMMY(&mem.animations); + ALLOC_DUMMY(&mem.cameras); + ALLOC_DUMMY(&mem.lights); + ALLOC_DUMMY(&mem.materials); + ALLOC_DUMMY(&mem.meshs); + ALLOC_DUMMY(&mem.mesh_links); + ALLOC_DUMMY(&mem.models); + ALLOC_DUMMY(&mem.nodes); + ALLOC_DUMMY(&mem.objects); + ALLOC_DUMMY(&mem.scenes); + ALLOC_DUMMY(&mem.skeletons); +} + +void scene_mem_destroy() { + // NOTE: the dummy objects are not constructed, so the destruction code below + // always skips index 0. (I don't really like the conditional inside the loop, + // but this gets the job done without having to specialize the loop macro.) +#define DESTROY(name) \ + mempool_foreach(&MEM_FIELD(name), obj, { \ + if (i > 0) { \ + gfx_destroy_##name(&obj); \ + } \ + }) + + // Models contain scene elements. Destruction is handled by the remainder of + // scene destructionb elow. + // + // First destroy the scenes. This will recursively destroy the scene's nodes + // and their objects and avoid a double-free when we then destroy any stray + // scene elements. + DESTROY(scene); + // Then delete stray nodes. This will delete their children nodes and + // resource. + DESTROY(node); + // Destroy remaining scene elements. + DESTROY(anima); + // Animations are owned by animas and do not have a destructor. + DESTROY(camera); + DESTROY(light); + DESTROY(material); + DESTROY(mesh); + // Mesh links don't have a destructor. + DESTROY(object); + // Skeletons are owned by animas and do not have a destructor. +} + +#define DEF_MEMORY(name, type) \ + /* xyz* mem_alloc_xyz(); */ \ + type* mem_alloc_##name() { return mempool_alloc(&MEM_FIELD(name)); } \ + /* void mem_free_xyz(xyz**); */ \ + void mem_free_##name(type** obj) { mempool_free(&MEM_FIELD(name), obj); } \ + /* xyz* mem_get_xyz(xyz_idx); */ \ + type* mem_get_##name(NAMED_INDEX(name) index) { \ + assert(index.val != 0); /* 0 is the dummy allocation. */ \ + return mempool_get_block(&MEM_FIELD(name), index.val); \ + } \ + /* xyz_idx mem_get_xyz_index(const xyz*); */ \ + NAMED_INDEX(name) mem_get_##name##_index(const type* obj) { \ + return (NAMED_INDEX(name)){ \ + .val = mempool_get_block_index(&MEM_FIELD(name), obj)}; \ + } + +DEF_MEMORY(anima, Anima) +DEF_MEMORY(animation, Animation) +DEF_MEMORY(camera, SceneCamera) +DEF_MEMORY(light, Light) +DEF_MEMORY(material, Material) +DEF_MEMORY(mesh, Mesh) +DEF_MEMORY(mesh_link, MeshLink) +DEF_MEMORY(model, Model) +DEF_MEMORY(node, SceneNode) +DEF_MEMORY(object, SceneObject) +DEF_MEMORY(scene, Scene) +DEF_MEMORY(skeleton, Skeleton) diff --git a/src/scene/scene_memory.h b/src/scene/scene_memory.h new file mode 100644 index 0000000..d175cba --- /dev/null +++ b/src/scene/scene_memory.h @@ -0,0 +1,39 @@ +/// Memory management of scene objects. +#pragma once + +#include "types.h" + +/// Initialize scene memory. +/// +/// The scene memory guarantees that every object maps to an index different +/// than 0. This way, 0 can be used as a special index to denote "no value". +void scene_mem_init(); + +/// Destroy the scene memory and all allocated objects. +void scene_mem_destroy(); + +#define NAMED_INDEX(name) name##_idx + +#define DECL_MEMORY(name, type) \ + typedef struct type type; \ + /* xyz* mem_alloc_xyz() */ \ + type* mem_alloc_##name(); \ + /* mem_free_xyz(xyz**) */ \ + void mem_free_##name(type**); \ + /* xyz* mem_get_xyz(xyz_idx); */ \ + type* mem_get_##name(NAMED_INDEX(name)); \ + /* xyz_idx mem_get_xyz_index(const xyz*); */ \ + NAMED_INDEX(name) mem_get_##name##_index(const type*); + +DECL_MEMORY(anima, Anima) +DECL_MEMORY(animation, Animation) +DECL_MEMORY(camera, SceneCamera) +DECL_MEMORY(light, Light) +DECL_MEMORY(material, Material) +DECL_MEMORY(mesh, Mesh) +DECL_MEMORY(mesh_link, MeshLink) +DECL_MEMORY(model, Model) +DECL_MEMORY(node, SceneNode) +DECL_MEMORY(object, SceneObject) +DECL_MEMORY(scene, Scene) +DECL_MEMORY(skeleton, Skeleton) diff --git a/src/scene/types.h b/src/scene/types.h new file mode 100644 index 0000000..d0ffc41 --- /dev/null +++ b/src/scene/types.h @@ -0,0 +1,24 @@ +/// Strongly-typed indices for every kind of scene node resource. +#pragma once + +#include + +typedef uint16_t gfx_idx; + +#define DEF_STRONG_INDEX(TYPE_NAME, IDX_TYPE) \ + typedef struct TYPE_NAME##_idx { \ + IDX_TYPE val; \ + } TYPE_NAME##_idx; + +DEF_STRONG_INDEX(anima, gfx_idx) +DEF_STRONG_INDEX(animation, gfx_idx) +DEF_STRONG_INDEX(camera, gfx_idx) +DEF_STRONG_INDEX(light, gfx_idx) +DEF_STRONG_INDEX(material, gfx_idx) +DEF_STRONG_INDEX(mesh, gfx_idx) +DEF_STRONG_INDEX(mesh_link, gfx_idx) +DEF_STRONG_INDEX(model, gfx_idx) +DEF_STRONG_INDEX(node, gfx_idx) +DEF_STRONG_INDEX(object, gfx_idx) +DEF_STRONG_INDEX(scene, gfx_idx) +DEF_STRONG_INDEX(skeleton, gfx_idx) diff --git a/src/util/geometry.c b/src/util/geometry.c new file mode 100644 index 0000000..afe0109 --- /dev/null +++ b/src/util/geometry.c @@ -0,0 +1,44 @@ +#include + +#include + +static void make_quad_11_positions(vec2 positions[4]) { + positions[0] = vec2_make(-1, +1); + positions[1] = vec2_make(-1, -1); + positions[2] = vec2_make(+1, +1); + positions[3] = vec2_make(+1, -1); +} + +static void make_quad_01_positions(vec2 positions[4]) { + positions[0] = vec2_make(0, 0); + positions[1] = vec2_make(1, 0); + positions[2] = vec2_make(1, 1); + positions[3] = vec2_make(0, 1); +} + +static GeometryDesc make_quad_desc(vec2 positions[4]) { + GeometryDesc desc = (GeometryDesc){0}; + desc.positions2d.data = positions; + desc.positions2d.size_bytes = 4 * sizeof(vec2); + desc.num_verts = 4; + desc.type = TriangleStrip; + return desc; +} + +Geometry* gfx_make_quad_11(GfxCore* gfxcore) { + assert(gfxcore); + + vec2 positions[4]; + make_quad_11_positions(positions); + const GeometryDesc geometry_desc = make_quad_desc(positions); + return gfx_make_geometry(gfxcore, &geometry_desc); +} + +Geometry* gfx_make_quad_01(GfxCore* gfxcore) { + assert(gfxcore); + + vec2 positions[4]; + make_quad_01_positions(positions); + const GeometryDesc geometry_desc = make_quad_desc(positions); + return gfx_make_geometry(gfxcore, &geometry_desc); +} diff --git a/src/util/ibl.c b/src/util/ibl.c new file mode 100644 index 0000000..5a79990 --- /dev/null +++ b/src/util/ibl.c @@ -0,0 +1,328 @@ +#include + +#include +#include +#include +#include + +#include +#include + +typedef struct IBL { + Geometry* quad; + ShaderProgram* brdf_integration_map_shader; + ShaderProgram* irradiance_map_shader; + ShaderProgram* prefiltered_environment_map_shader; + Texture* brdf_integration_map; + FrameBuffer* framebuffer; + mat4 rotations[6]; +} IBL; + +static const CubemapFace faces[6] = { + CubemapFacePosX, // Right. + CubemapFaceNegX, // Left. + CubemapFacePosY, // Up. + CubemapFaceNegY, // Down. + CubemapFacePosZ, // Back. + CubemapFaceNegZ, // Front. +}; + +static const float flips[6] = { + -1.0f, // Right. + -1.0f, // Left. + +1.0f, // Up. + +1.0f, // Down. + -1.0f, // Back. + -1.0f, // Front. +}; + +IBL* gfx_make_ibl(GfxCore* gfxcore) { + assert(gfxcore); + + IBL* ibl = calloc(1, sizeof(IBL)); + if (!ibl) { + return 0; + } + + if (!(ibl->quad = gfx_make_quad_11(gfxcore))) { + goto cleanup; + } + + // We only need the BRDF integration once since we are caching the map, but + // compiling the shader up front may lead to fewer surprises. Not that the + // shader is fully compiled up front anyway, since the driver will typically + // defer full compilation to the first draw call. + if (!(ibl->brdf_integration_map_shader = + gfx_make_brdf_integration_map_shader(gfxcore))) { + goto cleanup; + } + + if (!(ibl->irradiance_map_shader = gfx_make_irradiance_map_shader(gfxcore))) { + goto cleanup; + } + + if (!(ibl->prefiltered_environment_map_shader = + gfx_make_prefiltered_environment_map_shader(gfxcore))) { + goto cleanup; + } + + // Create an empty framebuffer for now. Will attach the colour buffer later + // as we render the faces of the cube. + if (!(ibl->framebuffer = gfx_make_framebuffer( + gfxcore, + &(FrameBufferDesc){ + .colour = + (FrameBufferAttachment){.type = FrameBufferNoAttachment}, + .depth = (FrameBufferAttachment){ + .type = FrameBufferNoAttachment}}))) { + goto cleanup; + } + + // TODO: Debug the camera rotations. Irradiance debug output should appear + // just like the input cubemap. + + // Right. + ibl->rotations[0] = mat4_lookat( + /*position=*/vec3_make(0, 0, 0), + /*target=*/vec3_make(1, 0, 0), + /*up=*/vec3_make(0, 1, 0)); + // Left. + ibl->rotations[1] = mat4_lookat( + /*position=*/vec3_make(0, 0, 0), + /*target=*/vec3_make(-1, 0, 0), + /*up=*/vec3_make(0, 1, 0)); + // Up. + ibl->rotations[2] = mat4_lookat( + /*position=*/vec3_make(0, 0, 0), + /*target=*/vec3_make(0, 1, 0), + /*up=*/vec3_make(0, 0, 1)); + // Down. + ibl->rotations[3] = mat4_lookat( + /*position=*/vec3_make(0, 0, 0), + /*target=*/vec3_make(0, -1, 0), + /*up=*/vec3_make(0, 0, -1)); + // Back. + ibl->rotations[4] = mat4_lookat( + /*position=*/vec3_make(0, 0, 0), + /*target=*/vec3_make(0, 0, 1), + /*up=*/vec3_make(0, 1, 0)); + // Front. + ibl->rotations[5] = mat4_lookat( + /*position=*/vec3_make(0, 0, 0), + /*target=*/vec3_make(0, 0, -1), + /*up=*/vec3_make(0, 1, 0)); + + return ibl; + +cleanup: + gfx_destroy_ibl(gfxcore, &ibl); + return 0; +} + +void gfx_destroy_ibl(GfxCore* gfxcore, IBL** ibl) { + if (!ibl) { + return; + } + if ((*ibl)->quad) { + gfx_destroy_geometry(gfxcore, &(*ibl)->quad); + } + if ((*ibl)->brdf_integration_map_shader) { + gfx_destroy_shader_program(gfxcore, &(*ibl)->brdf_integration_map_shader); + } + if ((*ibl)->irradiance_map_shader) { + gfx_destroy_shader_program(gfxcore, &(*ibl)->irradiance_map_shader); + } + if ((*ibl)->prefiltered_environment_map_shader) { + gfx_destroy_shader_program( + gfxcore, &(*ibl)->prefiltered_environment_map_shader); + } + if ((*ibl)->brdf_integration_map) { + gfx_destroy_texture(gfxcore, &(*ibl)->brdf_integration_map); + } + if ((*ibl)->framebuffer) { + gfx_destroy_framebuffer(gfxcore, &(*ibl)->framebuffer); + } + free(*ibl); + *ibl = 0; +} + +Texture* gfx_make_brdf_integration_map( + IBL* ibl, GfxCore* gfxcore, int width, int height) { + assert(ibl); + assert(gfxcore); + + if (ibl->brdf_integration_map) { + return ibl->brdf_integration_map; + } + + bool success = false; + + if (!(ibl->brdf_integration_map = gfx_make_texture( + gfxcore, &(TextureDesc){ + .width = width, + .height = height, + .depth = 1, + .dimension = Texture2D, + .format = TextureRG16F, + .filtering = LinearFiltering, + .wrap = ClampToEdge, + .mipmaps = false}))) { + goto cleanup; + } + + gfx_activate_framebuffer(ibl->framebuffer); + gfx_framebuffer_set_viewport(ibl->framebuffer, 0, 0, width, height); + gfx_activate_shader_program(ibl->brdf_integration_map_shader); + if (!gfx_framebuffer_attach_colour( + ibl->framebuffer, &(FrameBufferAttachment){ + .type = FrameBufferTexture, + .texture.texture = ibl->brdf_integration_map, + .texture.mip_level = 0})) { + goto cleanup; + } + gfx_render_geometry(ibl->quad); + + success = true; + +cleanup: + gfx_deactivate_shader_program(ibl->brdf_integration_map_shader); + gfx_deactivate_framebuffer(ibl->framebuffer); + if (!success && ibl->brdf_integration_map) { + gfx_destroy_texture(gfxcore, &ibl->brdf_integration_map); + return 0; + } else { + return ibl->brdf_integration_map; + } +} + +Texture* gfx_make_irradiance_map( + IBL* ibl, GfxCore* gfxcore, const Texture* environment_map, int width, + int height) { + assert(ibl); + assert(gfxcore); + assert(environment_map); + + bool success = false; + + Texture* irradiance_map = 0; + + // TODO: Could define colour-renderable texture formats separately to make + // framebuffer creation less error-prone. Or, at the very least, validate the + // choice at runtime. + // + // Make sure to use a float colour format to avoid [0,1] clamping when the + // irradiance values are computed! + if (!(irradiance_map = gfx_make_texture( + gfxcore, &(TextureDesc){ + .width = width, + .height = height, + .depth = 1, + .dimension = TextureCubeMap, + .format = TextureR11G11B10F, + .filtering = LinearFiltering, + .mipmaps = false}))) { + goto cleanup; + } + + gfx_activate_framebuffer(ibl->framebuffer); + gfx_framebuffer_set_viewport(ibl->framebuffer, 0, 0, width, height); + gfx_activate_shader_program(ibl->irradiance_map_shader); + gfx_set_texture_uniform(ibl->irradiance_map_shader, "Sky", environment_map); + for (int i = 0; i < 6; ++i) { + if (!gfx_framebuffer_attach_colour( + ibl->framebuffer, &(FrameBufferAttachment){ + .type = FrameBufferCubemapTexture, + .cubemap.face = faces[i], + .cubemap.texture = irradiance_map})) { + goto cleanup; + } + gfx_set_float_uniform(ibl->irradiance_map_shader, "Flip", flips[i]); + gfx_set_mat4_uniform( + ibl->irradiance_map_shader, "CameraRotation", &ibl->rotations[i]); + gfx_apply_uniforms(ibl->irradiance_map_shader); + gfx_render_geometry(ibl->quad); + } + + success = true; + +cleanup: + gfx_deactivate_shader_program(ibl->irradiance_map_shader); + gfx_deactivate_framebuffer(ibl->framebuffer); + if (!success && irradiance_map) { + gfx_destroy_texture(gfxcore, &irradiance_map); + return 0; + } else { + return irradiance_map; + } +} + +Texture* gfx_make_prefiltered_environment_map( + IBL* ibl, GfxCore* gfxcore, const Texture* environment_map, int width, + int height, int* max_mip_level) { + assert(ibl); + assert(gfxcore); + assert(environment_map); + assert(max_mip_level); + + bool success = false; + + Texture* prefiltered_env_map = 0; + + if (!(prefiltered_env_map = gfx_make_texture( + gfxcore, &(TextureDesc){ + .width = width, + .height = height, + .depth = 1, + .dimension = TextureCubeMap, + .format = TextureR11G11B10F, + .filtering = LinearFiltering, + .mipmaps = true}))) { + goto cleanup; + } + + gfx_activate_framebuffer(ibl->framebuffer); + gfx_activate_shader_program(ibl->prefiltered_environment_map_shader); + gfx_set_texture_uniform( + ibl->prefiltered_environment_map_shader, "Sky", environment_map); + const int max_mip = (int)(rlog2(min(width, height))); + for (int mip = 0; mip <= max_mip; ++mip) { + const int mip_width = width >> mip; + const int mip_height = height >> mip; + const float roughness = (float)mip / (float)(max_mip); + gfx_framebuffer_set_viewport(ibl->framebuffer, 0, 0, mip_width, mip_height); + gfx_set_float_uniform( + ibl->prefiltered_environment_map_shader, "Roughness", roughness); + + for (int i = 0; i < 6; ++i) { + if (!gfx_framebuffer_attach_colour( + ibl->framebuffer, &(FrameBufferAttachment){ + .type = FrameBufferCubemapTexture, + .cubemap.face = faces[i], + .cubemap.mip_level = mip, + .cubemap.texture = prefiltered_env_map})) { + goto cleanup; + } + gfx_set_float_uniform( + ibl->prefiltered_environment_map_shader, "Flip", flips[i]); + gfx_set_mat4_uniform( + ibl->prefiltered_environment_map_shader, "CameraRotation", + &ibl->rotations[i]); + gfx_apply_uniforms(ibl->prefiltered_environment_map_shader); + gfx_render_geometry(ibl->quad); + } + } + + *max_mip_level = max_mip; + + success = true; + +cleanup: + gfx_deactivate_shader_program(ibl->prefiltered_environment_map_shader); + gfx_deactivate_framebuffer(ibl->framebuffer); + if (!success && prefiltered_env_map) { + gfx_destroy_texture(gfxcore, &prefiltered_env_map); + return 0; + } else { + return prefiltered_env_map; + } +} diff --git a/src/util/shader.c b/src/util/shader.c new file mode 100644 index 0000000..f5c22cc --- /dev/null +++ b/src/util/shader.c @@ -0,0 +1,136 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +static ShaderProgram* make_shader_program( + GfxCore* gfxcore, const char* vert_source, const char* frag_source, + const ShaderCompilerDefine* defines, size_t num_defines) { + assert(gfxcore); + assert(vert_source); + assert(frag_source); + + Shader* vert = 0; + Shader* frag = 0; + + ShaderDesc vertex_shader_desc = { + .code = vert_source, .type = VertexShader, .num_defines = num_defines}; + ShaderDesc fragment_shader_desc = { + .code = frag_source, .type = FragmentShader, .num_defines = num_defines}; + if (num_defines > 0) { + memcpy( + vertex_shader_desc.defines, defines, + num_defines * sizeof(ShaderCompilerDefine)); + memcpy( + fragment_shader_desc.defines, defines, + num_defines * sizeof(ShaderCompilerDefine)); + } + vert = gfx_make_shader(gfxcore, &vertex_shader_desc); + if (!vert) { + goto cleanup; + } + frag = gfx_make_shader(gfxcore, &fragment_shader_desc); + if (!frag) { + goto cleanup; + } + + ShaderProgramDesc shader_program_desc = { + .vertex_shader = vert, .fragment_shader = frag}; + ShaderProgram* prog = gfx_make_shader_program(gfxcore, &shader_program_desc); + if (!prog) { + goto cleanup; + } + return prog; + +cleanup: + if (vert) { + gfx_destroy_shader(gfxcore, &vert); + } + if (frag) { + gfx_destroy_shader(gfxcore, &frag); + } + return 0; +} + +ShaderProgram* gfx_make_brdf_integration_map_shader(GfxCore* gfxcore) { + return make_shader_program( + gfxcore, quad_vert, brdf_integration_map_frag, 0, 0); +} + +ShaderProgram* gfx_make_cook_torrance_shader(GfxCore* gfxcore) { + return make_shader_program( + gfxcore, cook_torrance_vert, cook_torrance_frag, 0, 0); +} + +ShaderProgram* gfx_make_cook_torrance_shader_perm( + GfxCore* gfxcore, const ShaderCompilerDefine* defines, size_t num_defines) { + return make_shader_program( + gfxcore, cook_torrance_vert, cook_torrance_frag, defines, num_defines); +} + +ShaderProgram* gfx_make_immediate_mode_shader(GfxCore* gfxcore) { + return make_shader_program( + gfxcore, immediate_mode_vert, immediate_mode_frag, 0, 0); +} + +ShaderProgram* gfx_make_irradiance_map_shader(GfxCore* gfxcore) { + return make_shader_program( + gfxcore, cubemap_filtering_vert, irradiance_map_frag, 0, 0); +} + +ShaderProgram* gfx_make_prefiltered_environment_map_shader(GfxCore* gfxcore) { + return make_shader_program( + gfxcore, cubemap_filtering_vert, prefiltered_environment_map_frag, 0, 0); +} + +ShaderProgram* gfx_make_debug3d_shader(GfxCore* gfxcore) { + return make_shader_program(gfxcore, debug3d_vert, debug3d_frag, 0, 0); +} + +ShaderProgram* gfx_make_skyquad_shader(GfxCore* gfxcore) { + return make_shader_program(gfxcore, skyquad_vert, skyquad_frag, 0, 0); +} + +ShaderProgram* gfx_make_view_normal_mapped_normals_shader(GfxCore* gfxcore) { + return make_shader_program( + gfxcore, view_normal_mapped_normals_vert, view_normal_mapped_normals_frag, + 0, 0); +} + +ShaderProgram* gfx_make_view_normals_shader(GfxCore* gfxcore) { + return make_shader_program( + gfxcore, view_normals_vert, view_normals_frag, 0, 0); +} + +ShaderProgram* gfx_make_view_tangents_shader(GfxCore* gfxcore) { + return make_shader_program( + gfxcore, view_tangents_vert, view_tangents_frag, 0, 0); +} + +ShaderProgram* gfx_make_view_texture_shader(GfxCore* gfxcore) { + return make_shader_program( + gfxcore, view_texture_vert, view_texture_frag, 0, 0); +} diff --git a/src/util/skyquad.c b/src/util/skyquad.c new file mode 100644 index 0000000..08fa044 --- /dev/null +++ b/src/util/skyquad.c @@ -0,0 +1,161 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +SceneObject* gfx_make_skyquad(GfxCore* gfxcore, const Texture* texture) { + assert(gfxcore); + assert(texture); + + ShaderProgram* shader = 0; + Geometry* geometry = 0; + Material* material = 0; + Mesh* mesh = 0; + SceneObject* object = 0; + + shader = gfx_make_skyquad_shader(gfxcore); + if (!shader) { + goto cleanup; + } + + geometry = gfx_make_quad_11(gfxcore); + if (!geometry) { + goto cleanup; + } + + MaterialDesc material_desc = (MaterialDesc){0}; + material_desc.uniforms[0] = (ShaderUniform){ + .type = UniformTexture, + .value.texture = texture, + .name = sstring_make("Skyquad")}; + material_desc.num_uniforms = 1; + material = gfx_make_material(&material_desc); + if (!material) { + goto cleanup; + } + + MeshDesc mesh_desc = (MeshDesc){0}; + mesh_desc.geometry = geometry; + mesh_desc.material = material; + mesh_desc.shader = shader; + mesh = gfx_make_mesh(&mesh_desc); + if (!mesh) { + goto cleanup; + } + + object = gfx_make_object(&(ObjectDesc){.num_meshes = 1, .meshes = {mesh}}); + if (!object) { + goto cleanup; + } + + return object; + +cleanup: + if (shader) { + gfx_destroy_shader_program(gfxcore, &shader); + } + if (geometry) { + gfx_destroy_geometry(gfxcore, &geometry); + } + if (material) { + gfx_destroy_material(&material); + } + if (mesh) { + gfx_destroy_mesh(&mesh); + } + if (object) { + gfx_destroy_object(&object); + } + return false; +} + +/// Create an environment light node. +static SceneNode* make_environment_light( + SceneNode* root, const Texture* environment_map) { + assert(root); + assert(environment_map); + + Light* light = 0; + SceneNode* light_node = 0; + + light = gfx_make_light(&(LightDesc){ + .type = EnvironmentLightType, + .light = {(EnvironmentLightDesc){.environment_map = environment_map}}}); + if (!light) { + goto cleanup; + } + + light_node = gfx_make_light_node(light); + if (!light_node) { + goto cleanup; + } + gfx_set_node_parent(light_node, root); + + return light_node; + +cleanup: + if (light) { + gfx_destroy_light(&light); + } + if (light_node) { + gfx_destroy_node(&light_node); + } + return 0; +} + +SceneNode* gfx_setup_skyquad( + GfxCore* gfxcore, SceneNode* root, const Texture* environment_map) { + assert(gfxcore); + assert(root); + assert(environment_map); + + SceneObject* skyquad_object = 0; + SceneNode* object_node = 0; + SceneNode* light_node = 0; + + // Create the skyquad object. + skyquad_object = gfx_make_skyquad(gfxcore, environment_map); + if (!skyquad_object) { + goto cleanup; + } + + // Create an object node to render the skyquad in the background. + object_node = gfx_make_object_node(skyquad_object); + if (!object_node) { + goto cleanup; + } + gfx_set_node_parent(object_node, root); + + // Create an environment light node under which to root objects affected by + // the skyquad. + light_node = make_environment_light(root, environment_map); + if (!light_node) { + goto cleanup; + } + + return light_node; + +cleanup: + if (skyquad_object) { + gfx_destroy_object(&skyquad_object); + } + if (object_node) { + gfx_destroy_node(&object_node); + } + if (light_node) { + gfx_destroy_node(&light_node); + } + return 0; +} -- cgit v1.2.3